From 17c7b6b3d85a89414f362ed72473d4bf300716e7 Mon Sep 17 00:00:00 2001 From: jubrad Date: Mon, 16 Nov 2026 16:44:51 -0600 Subject: [PATCH 1/4] catalog: infer relationships between relations from view definitions Add mz_internal.mz_inferred_relationships, a builtin materialized view on mz_catalog_server that reads the relationships between user relations out of the environment's view and materialized view definitions, with no declared keys. A new scalar function, mz_internal.parse_catalog_view_joins, walks a persisted create_sql's resolved AST and returns the column pairs the view equates (ON, WHERE, USING, and IN (SELECT ...) semijoins) and its output columns that are input columns unchanged. Qualifiers resolve through a stack of SELECT scopes, and anything not bound to a catalog relation (a CTE, a subquery, a table function, an alias that renames columns) is opaque, so the function errs toward missing a relationship. The view orients each join toward a column that alone keys an index, then a column named id, then away from a column named *_id, and keeps a join nothing settles undirected. A passed-through key references its source, and a passed-through non-key column shares its references with its source, to a fixed point with WITH MUTUALLY RECURSIVE. Propagating through keys too would build the transitive closure of a view stack, which grows with the square of its depth. The function is gated by a new enable_inferred_relationships feature flag, default off, on in CI. The builtin is planned with item parsing flags on, so it is maintained regardless of the flag. Co-Authored-By: Claude Opus 5.5 --- .../content/sql/system-catalog/mz_internal.md | 24 + misc/python/materialize/mzcompose/__init__.py | 3 + src/catalog-decode/src/create_sql.rs | 2 +- src/catalog-decode/src/lib.rs | 1 + src/catalog-decode/src/view_joins.rs | 506 ++++++++++++++++++ src/catalog/src/builtin.rs | 4 + .../src/builtin/mz_inferred_relationships.rs | 274 ++++++++++ .../tests/snapshots/func_registry.json | 1 + .../snapshots/func_registry_digests.json | 2 +- .../tests/snapshots/func_registry_source.json | 1 + src/compute-types/tests/snapshots/lir_v1.json | 6 + src/expr/src/scalar/func/impls/catalog.rs | 7 +- src/expr/src/scalar/func/unary.rs | 1 + src/pgrepr-consts/src/oid.rs | 3 + src/pgrepr-consts/src/regproc.rs | 1 + src/sql/src/func.rs | 8 + src/sql/src/session/vars/definitions.rs | 6 + src/sql/system-parameters.json | 9 + .../autogenerated/mz_internal.slt | 11 + test/sqllogictest/catalog_server_explain.slt | 24 +- .../information_schema_tables.slt | 4 + .../mz_catalog_server_index_accounting.slt | 171 +++--- .../mz_inferred_relationships.slt | 158 ++++++ test/sqllogictest/oid.slt | 3 + 24 files changed, 1133 insertions(+), 97 deletions(-) create mode 100644 src/catalog-decode/src/view_joins.rs create mode 100644 src/catalog/src/builtin/mz_inferred_relationships.rs create mode 100644 test/sqllogictest/mz_inferred_relationships.slt diff --git a/doc/user/content/sql/system-catalog/mz_internal.md b/doc/user/content/sql/system-catalog/mz_internal.md index 0c3d1e9c66511..1172407ae36ba 100644 --- a/doc/user/content/sql/system-catalog/mz_internal.md +++ b/doc/user/content/sql/system-catalog/mz_internal.md @@ -536,6 +536,30 @@ deploying the changes to production. | `details` | [`text`] | Additional details on why the `hint` was proposed based on the dependencies of the object. | | `referenced_object_ids` | [`list`] | The IDs of objects referenced by `details`. Corresponds to [mz_objects.id](/sql/system-catalog/mz_catalog/#mz_objects). | +## `mz_inferred_relationships` + +The `mz_inferred_relationships` view describes relationships between user +relations that the definitions of views and materialized views imply, without +declared keys. A view that joins two relations on a pair of columns implies a +relationship between them. A view that passes a key column through, as in +`SELECT o.id AS org_id`, implies that its output column references that key. + +The referenced side of a join is a column that alone keys an index, then a +column named `id`, then the side not named `*_id`. A relationship that none of +these settle is undirected. Relationships implied by passed-through columns +describe the columns' domain, not their data: a view may filter, so its input +column can hold values that its output never shows. + + +| Field | Type | Meaning | +| --------------- | ----------- | -------- | +| `source_id` | [`text`] | The ID of the relation holding the referencing column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | +| `source_column` | [`text`] | The referencing column. | +| `target_id` | [`text`] | The ID of the relation holding the referenced column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | +| `target_column` | [`text`] | The referenced column. | +| `is_directed` | [`boolean`] | Whether a key decides which side references the other. When false, the two columns are only known to be joined, and their order is arbitrary. | +| `inferred_from` | [`text array`] | The IDs of the views and materialized views whose definitions imply the relationship. | + ## `mz_materialization_dependencies` The `mz_materialization_dependencies` view describes the dependency structure between each materialization (materialized view, index, or sink) and the sources of its data. diff --git a/misc/python/materialize/mzcompose/__init__.py b/misc/python/materialize/mzcompose/__init__.py index b576d064895bf..d876950786f1d 100644 --- a/misc/python/materialize/mzcompose/__init__.py +++ b/misc/python/materialize/mzcompose/__init__.py @@ -340,6 +340,9 @@ def get_variable_system_parameters( # On by default so CI exercises the jq function, which is off in # production while it earns trust. VariableSystemParameter("enable_jq", "true", ["true", "false"]), + VariableSystemParameter( + "enable_inferred_relationships", "true", ["true", "false"] + ), # On by default so CI exercises the columnar merge batcher, which is # off in production while it earns trust. VariableSystemParameter( diff --git a/src/catalog-decode/src/create_sql.rs b/src/catalog-decode/src/create_sql.rs index 7b6f924737d13..3227eed4c896a 100644 --- a/src/catalog-decode/src/create_sql.rs +++ b/src/catalog-decode/src/create_sql.rs @@ -35,7 +35,7 @@ use serde_json::json; use crate::durable; /// Parses `sql`, which must contain exactly one statement. -fn parse_single_statement(sql: &str) -> Result, String> { +pub(crate) fn parse_single_statement(sql: &str) -> Result, String> { let mut stmts = mz_sql_parser::parser::parse_statements(sql) .map_err(|e| format!("failed to parse create_sql: {e}"))?; match stmts.len() { diff --git a/src/catalog-decode/src/lib.rs b/src/catalog-decode/src/lib.rs index 321a21c7610f9..4e466782f90e1 100644 --- a/src/catalog-decode/src/lib.rs +++ b/src/catalog-decode/src/lib.rs @@ -20,3 +20,4 @@ pub mod audit_log; pub mod create_sql; pub mod durable; +pub mod view_joins; diff --git a/src/catalog-decode/src/view_joins.rs b/src/catalog-decode/src/view_joins.rs new file mode 100644 index 0000000000000..e694aaf1da70b --- /dev/null +++ b/src/catalog-decode/src/view_joins.rs @@ -0,0 +1,506 @@ +// Copyright Materialize, Inc. and contributors. All rights reserved. +// +// Use of this software is governed by the Business Source License +// included in the LICENSE file. +// +// As of the Change Date specified in that file, in accordance with +// the Business Source License, use of this software will be governed +// by the Apache License, Version 2.0. + +//! The joins and passed-through columns of a view definition, which +//! `mz_internal.mz_inferred_relationships` reads relationships from. +//! +//! The input is a persisted `create_sql`, whose relation references are +//! resolved to catalog ids (`[u4 AS "db"."schema"."name"]`). A column is +//! attributed to a relation only when its qualifier is bound to exactly that +//! relation in an enclosing scope. Any other binding, such as a CTE, a +//! subquery, a table function, or an alias that renames columns, is opaque, +//! so a column read through it is never attributed. This errs toward missing +//! a relationship over reporting a wrong one. + +use std::collections::BTreeMap; + +use mz_sql_parser::ast::{ + CteBlock, Expr, Ident, JoinConstraint, JoinOperator, Query, Raw, RawItemName, Select, + SelectItem, SetExpr, Statement, TableFactor, TableWithJoins, +}; +use serde_json::json; + +/// A column of a catalog relation. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct ColumnRef { + id: String, + column: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Binding { + Relation(String), + /// Bound to something that is not a catalog relation's columns. + Opaque, +} + +#[derive(Default)] +struct Extracted { + joins: Vec<(ColumnRef, ColumnRef)>, + usings: Vec<(String, String, Vec)>, + outputs: Vec<(String, ColumnRef)>, +} + +/// The scopes enclosing the expression being read, innermost last. +type Scopes = Vec>; + +/// Returns, as JSON, the column pairs the view equates (`joins`), its +/// `JOIN ... USING` clauses with the relations joined before them +/// (`using`), and its output columns that are input columns unchanged +/// (`outputs`). Statements other than views and materialized views yield +/// empty lists. +pub fn view_joins(sql: &str) -> Result { + let stmt = crate::create_sql::parse_single_statement(sql)?; + let (query, renames) = match &stmt { + Statement::CreateView(view) => (&view.definition.query, &view.definition.columns), + Statement::CreateMaterializedView(mv) => (&mv.query, &mv.columns), + _ => return Ok(json!({"joins": [], "using": [], "outputs": []})), + }; + let mut out = Extracted::default(); + let mut scopes = Scopes::new(); + walk_query(query, &mut scopes, &mut out, true); + + // `CREATE VIEW v (a, b) AS ...` renames the outputs by position. + if !renames.is_empty() { + out.outputs = out + .outputs + .into_iter() + .enumerate() + .filter_map(|(i, (_, source))| { + renames + .get(i) + .map(|name| (name.as_str().to_string(), source)) + }) + .collect(); + } + out.outputs.retain(|(_, source)| !source.id.is_empty()); + + Ok(json!({ + "joins": out.joins.iter().map(|(l, r)| json!({ + "left_id": l.id, "left_column": l.column, + "right_id": r.id, "right_column": r.column, + })).collect::>(), + "using": out.usings.iter().map(|(right, column, candidates)| json!({ + "right_id": right, "column": column, "candidates": candidates, + })).collect::>(), + "outputs": out.outputs.iter().map(|(column, source)| json!({ + "column": column, "source_id": source.id, "source_column": source.column, + })).collect::>(), + })) +} + +fn walk_query(query: &Query, scopes: &mut Scopes, out: &mut Extracted, is_top: bool) { + match &query.ctes { + CteBlock::Simple(ctes) => { + for cte in ctes { + walk_query(&cte.query, scopes, out, false); + } + } + CteBlock::MutuallyRecursive(block) => { + for cte in &block.ctes { + walk_query(&cte.query, scopes, out, false); + } + } + } + walk_set_expr(&query.body, scopes, out, is_top); +} + +fn walk_set_expr(expr: &SetExpr, scopes: &mut Scopes, out: &mut Extracted, is_top: bool) { + match expr { + SetExpr::Select(select) => walk_select(select, scopes, out, is_top), + SetExpr::Query(query) => walk_query(query, scopes, out, is_top), + // Outputs mix several SELECT lists, so none is a single input column. + SetExpr::SetOperation { left, right, .. } => { + walk_set_expr(left, scopes, out, false); + walk_set_expr(right, scopes, out, false); + } + SetExpr::Values(_) | SetExpr::Show(_) | SetExpr::Table(_) => {} + } +} + +fn walk_select(select: &Select, scopes: &mut Scopes, out: &mut Extracted, is_top: bool) { + scopes.push(BTreeMap::new()); + let mut conditions = Vec::new(); + let mut relations = Vec::new(); + for item in &select.from { + bind_table_with_joins(item, scopes, out, &mut conditions, &mut relations); + } + if let Some(selection) = &select.selection { + conditions.push(selection); + } + for condition in conditions { + read_condition(condition, scopes, out); + } + + if is_top { + // An unqualified column belongs to the FROM clause's only relation. + let single = match (select.from.as_slice(), relations.as_slice()) { + ([only], [relation]) if only.joins.is_empty() => Some(relation.clone()), + _ => None, + }; + for item in &select.projection { + let SelectItem::Expr { expr, alias } = item else { + // Columns after a wildcard have no position or name to read. + break; + }; + match column_ref(expr, scopes, single.as_deref()) { + Some(source) => { + let name = alias + .as_ref() + .map(|a| a.as_str().to_string()) + .unwrap_or_else(|| source.column.clone()); + out.outputs.push((name, source)); + } + // Keeps positions aligned for a renaming column list, and is + // dropped after renaming. + None => out.outputs.push((String::new(), ColumnRef::placeholder())), + } + } + } + scopes.pop(); +} + +impl ColumnRef { + fn placeholder() -> Self { + ColumnRef { + id: String::new(), + column: String::new(), + } + } +} + +/// Binds the FROM item's relations in the innermost scope, and collects its +/// join conditions and the relations it names, in order. +fn bind_table_with_joins<'a>( + item: &'a TableWithJoins, + scopes: &mut Scopes, + out: &mut Extracted, + conditions: &mut Vec<&'a Expr>, + relations: &mut Vec, +) { + let mut joined: Vec = Vec::new(); + bind_factor(&item.relation, scopes, out, conditions, &mut joined); + for join in &item.joins { + let before = joined.clone(); + let right = bind_factor(&join.relation, scopes, out, conditions, &mut joined); + let constraint = match &join.join_operator { + JoinOperator::Inner(c) + | JoinOperator::LeftOuter(c) + | JoinOperator::RightOuter(c) + | JoinOperator::FullOuter(c) => Some(c), + JoinOperator::CrossJoin => None, + }; + match constraint { + Some(JoinConstraint::On(expr)) => conditions.push(expr), + Some(JoinConstraint::Using { columns, .. }) => { + if let Some(right) = right { + let mut candidates = before; + candidates.dedup(); + if !candidates.is_empty() { + for column in columns { + out.usings.push(( + right.clone(), + column.as_str().to_string(), + candidates.clone(), + )); + } + } + } + } + Some(JoinConstraint::Natural) | None => {} + } + } + relations.extend(joined); +} + +/// Binds one FROM item. Returns the catalog relation it names, if any. +fn bind_factor<'a>( + factor: &'a TableFactor, + scopes: &mut Scopes, + out: &mut Extracted, + conditions: &mut Vec<&'a Expr>, + joined: &mut Vec, +) -> Option { + let scope = scopes.last_mut().expect("a SELECT pushed its scope"); + match factor { + TableFactor::Table { name, alias } => { + let (binding, default_name) = match name { + RawItemName::Id(id, name, _) => (Binding::Relation(id.clone()), name), + // A CTE. + RawItemName::Name(name) => (Binding::Opaque, name), + }; + let renames = alias.as_ref().is_some_and(|a| !a.columns.is_empty()); + let binding = if renames { Binding::Opaque } else { binding }; + let bound_name = match alias { + Some(alias) => alias.name.as_str().to_string(), + None => match default_name.0.last() { + Some(ident) => ident.as_str().to_string(), + None => return None, + }, + }; + bind(scope, bound_name, binding.clone()); + match binding { + Binding::Relation(id) => { + joined.push(id.clone()); + Some(id) + } + Binding::Opaque => None, + } + } + TableFactor::Derived { + subquery, alias, .. + } => { + if let Some(alias) = alias { + bind(scope, alias.name.as_str().to_string(), Binding::Opaque); + } + walk_query(subquery, scopes, out, false); + None + } + TableFactor::Function { alias, .. } | TableFactor::RowsFrom { alias, .. } => { + if let Some(alias) = alias { + bind(scope, alias.name.as_str().to_string(), Binding::Opaque); + } + None + } + TableFactor::NestedJoin { join, .. } => { + let mut relations = Vec::new(); + bind_table_with_joins(join, scopes, out, conditions, &mut relations); + joined.extend(relations); + None + } + } +} + +/// Binding a name twice in one scope makes it ambiguous. +fn bind(scope: &mut BTreeMap, name: String, binding: Binding) { + match scope.get(&name) { + Some(existing) if *existing != binding => { + scope.insert(name, Binding::Opaque); + } + _ => { + scope.insert(name, binding); + } + } +} + +fn lookup(scopes: &Scopes, name: &str) -> Option { + scopes + .iter() + .rev() + .find_map(|scope| scope.get(name).cloned()) +} + +/// The relation column an expression is, if it is a bare column reference. +fn column_ref(expr: &Expr, scopes: &Scopes, single: Option<&str>) -> Option { + match expr { + Expr::Nested(inner) => column_ref(inner, scopes, single), + Expr::Identifier(parts) => match parts.as_slice() { + [qualifier, column] => match lookup(scopes, qualifier.as_str())? { + Binding::Relation(id) => Some(ColumnRef { + id, + column: column.as_str().to_string(), + }), + Binding::Opaque => None, + }, + [column] => single.map(|id| ColumnRef { + id: id.to_string(), + column: column.as_str().to_string(), + }), + _ => None, + }, + _ => None, + } +} + +fn is_equals(op: &str, namespace: &Option>) -> bool { + op == "=" && namespace.is_none() +} + +/// Reads the column equalities among a condition's top-level conjuncts, and +/// walks the subqueries they hold. +fn read_condition(expr: &Expr, scopes: &mut Scopes, out: &mut Extracted) { + match expr { + Expr::Nested(inner) => read_condition(inner, scopes, out), + Expr::And { left, right } => { + read_condition(left, scopes, out); + read_condition(right, scopes, out); + } + Expr::Op { + op, + expr1, + expr2: Some(expr2), + } if is_equals(&op.op, &op.namespace) => { + let left = column_ref(expr1, scopes, None); + let right = column_ref(expr2, scopes, None); + if let (Some(left), Some(right)) = (left, right) { + if left.id != right.id { + out.joins.push((left, right)); + } + } + } + // `a.x IN (SELECT b.y FROM b ...)` is a semijoin on `a.x = b.y`. + Expr::InSubquery { + expr, + subquery, + negated: false, + } => { + if let (Some(left), SetExpr::Select(select)) = + (column_ref(expr, scopes, None), &subquery.body) + { + if let [SelectItem::Expr { expr: inner, .. }] = select.projection.as_slice() { + scopes.push(BTreeMap::new()); + let mut relations = Vec::new(); + let mut ignored = Vec::new(); + for item in &select.from { + bind_table_with_joins(item, scopes, out, &mut ignored, &mut relations); + } + let single = match (select.from.as_slice(), relations.as_slice()) { + ([only], [relation]) if only.joins.is_empty() => Some(relation.clone()), + _ => None, + }; + let right = column_ref(inner, scopes, single.as_deref()); + scopes.pop(); + if let Some(right) = right { + if left.id != right.id { + out.joins.push((left, right)); + } + } + } + } + walk_query(subquery, scopes, out, false); + } + Expr::Exists(subquery) | Expr::Subquery(subquery) => { + walk_query(subquery, scopes, out, false); + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::view_joins; + + fn joins(sql: &str) -> Vec { + let out = view_joins(sql).expect("parses"); + out["joins"] + .as_array() + .unwrap() + .iter() + .map(|j| { + format!( + "{}.{}={}.{}", + j["left_id"].as_str().unwrap(), + j["left_column"].as_str().unwrap(), + j["right_id"].as_str().unwrap(), + j["right_column"].as_str().unwrap() + ) + }) + .collect() + } + + fn outputs(sql: &str) -> Vec { + let out = view_joins(sql).expect("parses"); + out["outputs"] + .as_array() + .unwrap() + .iter() + .map(|o| { + format!( + "{}<-{}.{}", + o["column"].as_str().unwrap(), + o["source_id"].as_str().unwrap(), + o["source_column"].as_str().unwrap() + ) + }) + .collect() + } + + // Fixtures are `create_sql` as v26.50 stores it, for an auction schema: + // u3 auctions, u4 bids, u5 organizations, u6 users, u7 winning_bids. + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn aliased_joins_and_passed_columns() { + let sql = r#"CREATE VIEW "materialize"."agents"."org_spend" AS SELECT "o"."id" AS "org_id", "o"."name", "pg_catalog"."sum"("w"."amount") AS "spend" FROM [u5 AS "materialize"."auction"."organizations"] AS "o" JOIN [u6 AS "materialize"."auction"."users"] AS "u" ON "u"."org_id" = "o"."id" JOIN [u7 AS "materialize"."auction"."winning_bids"] AS "w" ON "w"."buyer" = "u"."id" GROUP BY "o"."id", "o"."name""#; + assert_eq!(joins(sql), ["u6.org_id=u5.id", "u7.buyer=u6.id"]); + assert_eq!(outputs(sql), ["org_id<-u5.id", "name<-u5.name"]); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn materialized_view_with_distinct_on() { + let sql = r#"CREATE MATERIALIZED VIEW "materialize"."auction"."winning_bids" IN CLUSTER [u2] WITH (REFRESH = ON COMMIT) AS SELECT DISTINCT ON ("a"."id") "b"."id" AS "bid_id", "a"."id" AS "auction_id", "b"."buyer" FROM [u3 AS "materialize"."auction"."auctions"] AS "a" JOIN [u4 AS "materialize"."auction"."bids"] AS "b" ON "a"."id" = "b"."auction_id" WHERE "b"."bid_time" < "a"."end_time""#; + assert_eq!(joins(sql), ["u3.id=u4.auction_id"]); + assert_eq!( + outputs(sql), + ["bid_id<-u4.id", "auction_id<-u3.id", "buyer<-u4.buyer"] + ); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn semijoins_and_correlated_conditions() { + let sql = r#"CREATE VIEW "v" AS SELECT * FROM [u4 AS "materialize"."auction"."bids"] AS "b" WHERE "b"."auction_id" IN (SELECT "a"."id" FROM [u3 AS "materialize"."auction"."auctions"] AS "a" WHERE "a"."seller" = "b"."buyer")"#; + assert_eq!(joins(sql), ["u4.auction_id=u3.id", "u3.seller=u4.buyer"]); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn opaque_bindings_resolve_nothing() { + // A CTE named like nothing in the catalog. + let cte = r#"CREATE VIEW "v" AS WITH "x" AS (SELECT "seller" FROM [u3 AS "materialize"."auction"."auctions"]) SELECT "u"."name" FROM "x", [u6 AS "materialize"."auction"."users"] AS "u" WHERE "u"."id" = "x"."seller""#; + assert!(joins(cte).is_empty()); + // An inner alias shadows the outer one inside the subquery only. + let shadow = r#"CREATE VIEW "v" AS SELECT "a"."id" FROM [u3 AS "materialize"."auction"."auctions"] AS "a" JOIN (SELECT "a"."id" FROM [u4 AS "materialize"."auction"."bids"] AS "a") AS "s" ON "s"."id" = "a"."id""#; + assert!(joins(shadow).is_empty()); + // An alias that renames columns. + let renamed = r#"CREATE VIEW "v" AS SELECT 1 FROM [u4 AS "materialize"."auction"."bids"] AS "b" ("x", "auction_id") JOIN [u3 AS "materialize"."auction"."auctions"] AS "a" ON "a"."id" = "b"."auction_id""#; + assert!(joins(renamed).is_empty()); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn expressions_are_not_columns() { + let sql = r#"CREATE VIEW "v" AS SELECT 1 FROM [u4 AS "materialize"."auction"."bids"] AS "b" JOIN [u3 AS "materialize"."auction"."auctions"] AS "a" ON "a"."id" + 0 = "b"."auction_id" AND "a"."seller"::[s46 AS "pg_catalog"."text"] = "b"."buyer"::[s46 AS "pg_catalog"."text"]"#; + assert_eq!(view_joins(sql).unwrap()["joins"], json!([])); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn using_joins_list_earlier_relations() { + let sql = r#"CREATE VIEW "v" AS SELECT "users"."name" FROM [u6 AS "materialize"."auction"."users"] JOIN [u2 AS "materialize"."auction"."accounts"] AS "a" USING ("org_id")"#; + assert_eq!( + view_joins(sql).unwrap()["using"], + json!([{"right_id": "u2", "column": "org_id", "candidates": ["u6"]}]) + ); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn outputs_follow_view_column_renames_and_skip_set_operations() { + let renamed = r#"CREATE VIEW "v" ("x", "y") AS SELECT 1, "s"."seller" FROM [u3 AS "materialize"."auction"."auctions"] AS "s""#; + assert_eq!(outputs(renamed), ["y<-u3.seller"]); + let union = r#"CREATE VIEW "v" AS SELECT "a"."id" FROM [u3 AS "materialize"."auction"."auctions"] AS "a" UNION ALL SELECT "b"."id" FROM [u4 AS "materialize"."auction"."bids"] AS "b""#; + assert!(outputs(union).is_empty()); + let single = r#"CREATE VIEW "v" AS SELECT "seller" FROM [u3 AS "materialize"."auction"."auctions"] GROUP BY "seller""#; + assert_eq!(outputs(single), ["seller<-u3.seller"]); + } + + #[mz_ore::test] + #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux` + fn other_statements_are_empty() { + let sql = r#"CREATE TABLE "materialize"."public"."t" ("a" [s20 AS "pg_catalog"."int4"])"#; + assert_eq!( + view_joins(sql).unwrap(), + json!({"joins": [], "using": [], "outputs": []}) + ); + } +} diff --git a/src/catalog/src/builtin.rs b/src/catalog/src/builtin.rs index aabc335507e34..475ab0821f42b 100644 --- a/src/catalog/src/builtin.rs +++ b/src/catalog/src/builtin.rs @@ -33,6 +33,8 @@ mod mz_internal; pub use mz_internal::*; mod mz_object_dependencies; pub use mz_object_dependencies::*; +mod mz_inferred_relationships; +pub use mz_inferred_relationships::*; mod mz_introspection; pub use mz_introspection::*; mod information_schema; @@ -1253,6 +1255,7 @@ pub static BUILTINS_STATIC: LazyLock>> = LazyLock::ne Builtin::MaterializedView(&MZ_METRIC_SINKS), Builtin::MaterializedView(&MZ_HISTORY_RETENTION_STRATEGIES), Builtin::MaterializedView(&MZ_MATERIALIZED_VIEWS), + Builtin::MaterializedView(&MZ_INFERRED_RELATIONSHIPS), Builtin::MaterializedView(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES), Builtin::MaterializedView(&MZ_NETWORK_POLICIES), Builtin::MaterializedView(&MZ_NETWORK_POLICY_RULES), @@ -1516,6 +1519,7 @@ pub static BUILTINS_STATIC: LazyLock>> = LazyLock::ne Builtin::Index(&MZ_OBJECT_LIFETIMES_IND), Builtin::Index(&MZ_OBJECT_HISTORY_IND), Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND), + Builtin::Index(&MZ_INFERRED_RELATIONSHIPS_IND), Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND), Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND), Builtin::Index(&MZ_OBJECT_GRAPH_EDGES_IND), diff --git a/src/catalog/src/builtin/mz_inferred_relationships.rs b/src/catalog/src/builtin/mz_inferred_relationships.rs new file mode 100644 index 0000000000000..ccd81b38bff29 --- /dev/null +++ b/src/catalog/src/builtin/mz_inferred_relationships.rs @@ -0,0 +1,274 @@ +// Copyright Materialize, Inc. and contributors. All rights reserved. +// +// Use of this software is governed by the Business Source License +// included in the LICENSE file. +// +// As of the Change Date specified in that file, in accordance with +// the Business Source License, use of this software will be governed +// by the Apache License, Version 2.0. + +//! The `mz_internal.mz_inferred_relationships` materialized view. + +use std::collections::BTreeMap; +use std::sync::LazyLock; + +use mz_pgrepr::oid; +use mz_repr::namespaces::MZ_INTERNAL_SCHEMA; +use mz_repr::{RelationDesc, SqlScalarType}; + +use super::{BuiltinIndex, BuiltinMaterializedView, PUBLIC_SELECT}; + +/// Relationships between user relations that their views' definitions imply, +/// with no declared keys. +/// +/// Evidence is of two kinds, both read by `parse_catalog_view_joins`: +/// +/// 1. A join: two relations' columns a view equates. The referenced side is +/// a column that alone keys an index, then a column named `id`, then the +/// side not named `*_id`. A join neither settles is kept undirected. +/// 2. A passed-through column: a view's output column that is an input +/// column unchanged. An output that passes a key references that key. +/// An output that passes any other column holds the same values as it, so +/// a reference either has, the other has too. This runs to a fixed point, +/// through views over views. +/// +/// The second is a claim about the columns' domain, not their data: a view +/// may filter, so its input column can hold values its output never shows. +pub static MZ_INFERRED_RELATIONSHIPS: LazyLock = LazyLock::new(|| { + BuiltinMaterializedView { + name: "mz_inferred_relationships", + schema: MZ_INTERNAL_SCHEMA, + oid: oid::MV_MZ_INFERRED_RELATIONSHIPS_OID, + desc: RelationDesc::builder() + .with_column("source_id", SqlScalarType::String.nullable(false)) + .with_column("source_column", SqlScalarType::String.nullable(false)) + .with_column("target_id", SqlScalarType::String.nullable(false)) + .with_column("target_column", SqlScalarType::String.nullable(false)) + .with_column("is_directed", SqlScalarType::Bool.nullable(false)) + .with_column( + "inferred_from", + SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false), + ) + .with_key(vec![0, 1, 2, 3]) + .finish(), + column_comments: BTreeMap::from_iter([ + ( + "source_id", + "The ID of the relation holding the referencing column. Corresponds to `mz_objects.id`.", + ), + ("source_column", "The referencing column."), + ( + "target_id", + "The ID of the relation holding the referenced column. Corresponds to `mz_objects.id`.", + ), + ("target_column", "The referenced column."), + ( + "is_directed", + "Whether a key decides which side references the other. When false, the two columns are only known to be joined, and their order is arbitrary.", + ), + ( + "inferred_from", + "The IDs of the views and materialized views whose definitions imply the relationship.", + ), + ]), + sql: " +IN CLUSTER mz_catalog_server +WITH ( + ASSERT NOT NULL source_id, + ASSERT NOT NULL source_column, + ASSERT NOT NULL target_id, + ASSERT NOT NULL target_column, + ASSERT NOT NULL is_directed, + ASSERT NOT NULL inferred_from +) AS +WITH + parsed AS ( + SELECT id AS view_id, mz_internal.parse_catalog_view_joins(create_sql) AS j + FROM ( + SELECT id, create_sql FROM mz_catalog.mz_views WHERE id LIKE 'u%' + UNION ALL + SELECT id, create_sql FROM mz_catalog.mz_materialized_views WHERE id LIKE 'u%' + ) + ), + user_columns AS ( + SELECT id, name FROM mz_catalog.mz_columns WHERE id LIKE 'u%' + ), + -- Columns that alone key an index. Indexes do not enforce uniqueness, so + -- this only hints at which side of a join is the key. + index_keys AS ( + SELECT DISTINCT i.on_id AS id, c.name + FROM mz_catalog.mz_indexes i + JOIN mz_catalog.mz_index_columns ic ON ic.index_id = i.id + JOIN mz_catalog.mz_columns c ON c.id = i.on_id AND c.position = ic.on_position + WHERE i.on_id LIKE 'u%' AND i.id IN ( + SELECT index_id FROM mz_catalog.mz_index_columns + GROUP BY index_id HAVING count(*) = 1 + ) + ), + using_owners AS ( + SELECT u.view_id, u.right_id, u.name, u.candidate + FROM ( + SELECT + view_id, + x.e->>'right_id' AS right_id, + x.e->>'column' AS name, + c.candidate + FROM parsed, + jsonb_array_elements(j->'using') AS x(e), + jsonb_array_elements_text(x.e->'candidates') AS c(candidate) + ) u + JOIN user_columns c ON c.id = u.candidate AND c.name = u.name + ), + -- Pairs of equated columns, the left side of a USING join being the one + -- earlier relation that has the column. + equated AS ( + SELECT + view_id, + p.e->>'left_id' AS a_id, + p.e->>'left_column' AS a_col, + p.e->>'right_id' AS b_id, + p.e->>'right_column' AS b_col + FROM parsed, jsonb_array_elements(j->'joins') AS p(e) + UNION ALL + SELECT view_id, min(candidate), name, right_id, name + FROM using_owners + GROUP BY view_id, right_id, name + HAVING count(DISTINCT candidate) = 1 + ), + scored AS ( + SELECT + e.*, + CASE WHEN ka.id IS NOT NULL THEN 2 WHEN e.a_col = 'id' THEN 1 ELSE 0 END + - CASE WHEN kb.id IS NOT NULL THEN 2 WHEN e.b_col = 'id' THEN 1 ELSE 0 END + AS a_over_b, + (e.b_col ~ '.+_id$')::int - (e.a_col ~ '.+_id$')::int AS a_by_name + FROM equated e + JOIN user_columns ca ON ca.id = e.a_id AND ca.name = e.a_col + JOIN user_columns cb ON cb.id = e.b_id AND cb.name = e.b_col + LEFT JOIN index_keys ka ON ka.id = e.a_id AND ka.name = e.a_col + LEFT JOIN index_keys kb ON kb.id = e.b_id AND kb.name = e.b_col + WHERE e.a_id <> e.b_id + ), + -- `a_first` is positive when `a` is the referenced side. + oriented AS ( + SELECT + view_id, a_id, a_col, b_id, b_col, + CASE WHEN a_over_b <> 0 THEN a_over_b ELSE a_by_name END AS a_first + FROM scored + ), + joins AS ( + SELECT + view_id, + CASE WHEN keep THEN b_id ELSE a_id END AS source_id, + CASE WHEN keep THEN b_col ELSE a_col END AS source_column, + CASE WHEN keep THEN a_id ELSE b_id END AS target_id, + CASE WHEN keep THEN a_col ELSE b_col END AS target_column, + a_first <> 0 AS is_directed + FROM ( + SELECT + *, + -- Undirected pairs are ordered by name so each appears once. + a_first > 0 OR (a_first = 0 AND a_id || '.' || a_col > b_id || '.' || b_col) AS keep + FROM oriented + ) + ), + passed AS ( + SELECT + view_id, + o.e->>'column' AS output_column, + o.e->>'source_id' AS source_id, + o.e->>'source_column' AS source_column + FROM parsed, jsonb_array_elements(j->'outputs') AS o(e) + ), + passed_keys AS ( + SELECT p.* + FROM passed p + JOIN user_columns c ON c.id = p.source_id AND c.name = p.source_column + WHERE p.source_column = 'id' OR EXISTS ( + SELECT 1 FROM index_keys k + WHERE k.id = p.source_id AND k.name = p.source_column + ) + ), + -- Passed columns that are not keys. A passed key references its source + -- directly, and propagating through it too would add every key it + -- reaches transitively, which grows with the square of a view stack's + -- depth (a stack of 300 views passing `id` gave 45,150 rows). + passed_references AS ( + SELECT p.* + FROM passed p + WHERE NOT EXISTS ( + SELECT 1 FROM passed_keys k + WHERE k.view_id = p.view_id AND k.output_column = p.output_column + ) + ), + directed AS ( + WITH MUTUALLY RECURSIVE + refs ( + view_id text, + source_id text, + source_column text, + target_id text, + target_column text + ) AS ( + SELECT view_id, source_id, source_column, target_id, target_column + FROM joins WHERE is_directed + UNION + SELECT view_id, view_id, output_column, source_id, source_column + FROM passed_keys + WHERE view_id <> source_id + UNION + SELECT p.view_id, p.view_id, p.output_column, r.target_id, r.target_column + FROM passed_references p + JOIN refs r ON r.source_id = p.source_id AND r.source_column = p.source_column + WHERE p.view_id <> r.target_id + UNION + SELECT p.view_id, p.source_id, p.source_column, r.target_id, r.target_column + FROM passed_references p + JOIN refs r ON r.source_id = p.view_id AND r.source_column = p.output_column + WHERE p.source_id <> r.target_id + ) + SELECT * FROM refs + ), + undirected AS ( + SELECT j.view_id, j.source_id, j.source_column, j.target_id, j.target_column + FROM joins j + WHERE NOT j.is_directed AND NOT EXISTS ( + SELECT 1 FROM directed d + WHERE ( + d.source_id = j.source_id AND d.source_column = j.source_column + AND d.target_id = j.target_id AND d.target_column = j.target_column + ) OR ( + d.source_id = j.target_id AND d.source_column = j.target_column + AND d.target_id = j.source_id AND d.target_column = j.source_column + ) + ) + ), + evidence AS ( + SELECT DISTINCT *, true AS is_directed FROM directed + UNION ALL + SELECT DISTINCT *, false AS is_directed FROM undirected + ) +SELECT + source_id, + source_column, + target_id, + target_column, + is_directed, + array_agg(view_id ORDER BY view_id) AS inferred_from +FROM evidence +WHERE source_id LIKE 'u%' AND target_id LIKE 'u%' +GROUP BY source_id, source_column, target_id, target_column, is_directed", + is_retained_metrics_object: false, + access: vec![PUBLIC_SELECT], + ontology: None, + } +}); + +pub const MZ_INFERRED_RELATIONSHIPS_IND: BuiltinIndex = BuiltinIndex { + name: "mz_inferred_relationships_ind", + schema: MZ_INTERNAL_SCHEMA, + oid: oid::INDEX_MZ_INFERRED_RELATIONSHIPS_IND_OID, + sql: "IN CLUSTER mz_catalog_server +ON mz_internal.mz_inferred_relationships (source_id)", + is_retained_metrics_object: false, +}; diff --git a/src/compute-types/tests/snapshots/func_registry.json b/src/compute-types/tests/snapshots/func_registry.json index df91c6acdbe99..ddbe9d85d7f1a 100644 --- a/src/compute-types/tests/snapshots/func_registry.json +++ b/src/compute-types/tests/snapshots/func_registry.json @@ -539,6 +539,7 @@ "parse_catalog_id": {"variant":"ParseCatalogId","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["Jsonb:NotNull"],"output_type":"String:NotNull","sqlfunc_signature":"fn(JsonbRef<'a>) -> Result"}, "parse_catalog_item_references": {"variant":"ParseCatalogItemReferences","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["String:NotNull"],"output_type":"Jsonb:NotNull","sqlfunc_signature":"fn(&'a str) -> Result"}, "parse_catalog_privileges": {"variant":"ParseCatalogPrivileges","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["Jsonb:NotNull"],"output_type":"Array(MzAclItem):NotNull","sqlfunc_signature":"fn(JsonbRef<'a>) -> Result, EvalError>"}, + "parse_catalog_view_joins": {"variant":"ParseCatalogViewJoins","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["String:NotNull"],"output_type":"Jsonb:NotNull","sqlfunc_signature":"fn(&'a str) -> Result"}, "parse_connection_details": {"variant":"ParseConnectionDetails","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["String:NotNull"],"output_type":"Jsonb:NotNull","sqlfunc_signature":"fn(&'a str) -> Result"}, "parse_kafka_source_details": {"variant":"ParseKafkaSourceDetails","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["String:NotNull"],"output_type":"Jsonb:NotNull","sqlfunc_signature":"fn(&'a str) -> Result"}, "parse_postgres_source_details": {"variant":"ParsePostgresSourceDetails","propagates_nulls":true,"introduces_nulls":false,"could_error":true,"preserves_uniqueness":false,"is_monotone":false,"is_eliminable_cast":false,"inverse":null,"input_types":["String:NotNull"],"output_type":"Jsonb:NotNull","sqlfunc_signature":"fn(&'a str) -> Result"}, diff --git a/src/compute-types/tests/snapshots/func_registry_digests.json b/src/compute-types/tests/snapshots/func_registry_digests.json index 89797e04dcaf8..e941a87bf3618 100644 --- a/src/compute-types/tests/snapshots/func_registry_digests.json +++ b/src/compute-types/tests/snapshots/func_registry_digests.json @@ -1,3 +1,3 @@ { - "1": "sha256:d45833c947e7a88ad2f320bdd42cadb243d09ed7dc8b5bad9114e06e349a4a07" + "1": "sha256:d548d834bd265332c54c5922c5832baf18628aee72324a93dc8a451e17cfe380" } diff --git a/src/compute-types/tests/snapshots/func_registry_source.json b/src/compute-types/tests/snapshots/func_registry_source.json index e5189db686535..3f7b55acce6ce 100644 --- a/src/compute-types/tests/snapshots/func_registry_source.json +++ b/src/compute-types/tests/snapshots/func_registry_source.json @@ -539,6 +539,7 @@ "parse_catalog_id": {"display":"parse_catalog_id","sqlfunc_decl":"#[sqlfunc] fn parse_catalog_id<'a>(a: JsonbRef<'a>) -> Result","body_fingerprint":"3df74fa5b95ad2a3"}, "parse_catalog_item_references": {"display":"parse_catalog_item_references","sqlfunc_decl":"#[sqlfunc] fn parse_catalog_item_references<'a>(a: &'a str) -> Result","body_fingerprint":"afac69531d801621"}, "parse_catalog_privileges": {"display":"parse_catalog_privileges","sqlfunc_decl":"#[sqlfunc] fn parse_catalog_privileges<'a>(a: JsonbRef<'a>) -> Result, EvalError>","body_fingerprint":"0189155db8d73f28"}, + "parse_catalog_view_joins": {"display":"parse_catalog_view_joins","sqlfunc_decl":"#[sqlfunc] fn parse_catalog_view_joins<'a>(a: &'a str) -> Result","body_fingerprint":"f23ae090959a87b8"}, "parse_connection_details": {"display":"parse_connection_details","sqlfunc_decl":"#[sqlfunc] fn parse_connection_details<'a>(a: &'a str) -> Result","body_fingerprint":"479b90a7cbe943f6"}, "parse_kafka_source_details": {"display":"parse_kafka_source_details","sqlfunc_decl":"#[sqlfunc] fn parse_kafka_source_details<'a>(a: &'a str) -> Result","body_fingerprint":"8717ae9a730e89a0"}, "parse_postgres_source_details": {"display":"parse_postgres_source_details","sqlfunc_decl":"#[sqlfunc] fn parse_postgres_source_details<'a>(a: &'a str) -> Result","body_fingerprint":"00a79828148946a7"}, diff --git a/src/compute-types/tests/snapshots/lir_v1.json b/src/compute-types/tests/snapshots/lir_v1.json index 2337b6e9ef0df..ff281e8e37f35 100644 --- a/src/compute-types/tests/snapshots/lir_v1.json +++ b/src/compute-types/tests/snapshots/lir_v1.json @@ -3102,6 +3102,7 @@ "ParseCatalogId": "UNITSTRUCT", "ParseCatalogItemReferences": "UNITSTRUCT", "ParseCatalogPrivileges": "UNITSTRUCT", + "ParseCatalogViewJoins": "UNITSTRUCT", "ParseConnectionDetails": "UNITSTRUCT", "ParseIdent": "UNITSTRUCT", "ParseKafkaSourceDetails": "UNITSTRUCT", @@ -5267,6 +5268,11 @@ "TYPENAME": "ParseCatalogPrivileges" } }, + "ParseCatalogViewJoins": { + "NEWTYPE": { + "TYPENAME": "ParseCatalogViewJoins" + } + }, "ParseConnectionDetails": { "NEWTYPE": { "TYPENAME": "ParseConnectionDetails" diff --git a/src/expr/src/scalar/func/impls/catalog.rs b/src/expr/src/scalar/func/impls/catalog.rs index a639394dfe195..7271517b4a95b 100644 --- a/src/expr/src/scalar/func/impls/catalog.rs +++ b/src/expr/src/scalar/func/impls/catalog.rs @@ -10,7 +10,7 @@ //! Scalar functions that decode durable catalog data for the builtin catalog //! views. The decoders live in `mz_catalog_decode`, documented there. -use mz_catalog_decode::{audit_log, create_sql, durable}; +use mz_catalog_decode::{audit_log, create_sql, durable, view_joins}; use mz_expr_derive::sqlfunc; use mz_repr::ArrayRustType; use mz_repr::adt::jsonb::{Jsonb, JsonbRef}; @@ -66,6 +66,11 @@ fn parse_catalog_item_references<'a>(a: &'a str) -> Result { .map_err(catalog_err) } +#[sqlfunc] +fn parse_catalog_view_joins<'a>(a: &'a str) -> Result { + view_joins::view_joins(a).map(to_jsonb).map_err(catalog_err) +} + #[sqlfunc] fn parse_postgres_source_details<'a>(a: &'a str) -> Result { create_sql::postgres_source_details(a) diff --git a/src/expr/src/scalar/func/unary.rs b/src/expr/src/scalar/func/unary.rs index 72090c729b7d9..de6dcc4eb4a4a 100644 --- a/src/expr/src/scalar/func/unary.rs +++ b/src/expr/src/scalar/func/unary.rs @@ -472,6 +472,7 @@ derive_unary!( ParseCatalogId, ParseCatalogItemReferences, ParseCatalogPrivileges, + ParseCatalogViewJoins, ParseConnectionDetails, ParseKafkaSourceDetails, ParsePostgresSourceDetails, diff --git a/src/pgrepr-consts/src/oid.rs b/src/pgrepr-consts/src/oid.rs index 3f26b5ecaf697..95fc0697bad10 100644 --- a/src/pgrepr-consts/src/oid.rs +++ b/src/pgrepr-consts/src/oid.rs @@ -847,3 +847,6 @@ pub const FUNC_LIST_GTE_OID: u32 = 17137; pub const FUNC_JQ_OID: u32 = 17138; pub const VIEW_MZ_BUILTIN_COLUMNS_OID: u32 = 17139; pub const VIEW_MZ_BUILTIN_INDEX_COLUMNS_OID: u32 = 17140; +pub const FUNC_PARSE_CATALOG_VIEW_JOINS_OID: u32 = 17141; +pub const MV_MZ_INFERRED_RELATIONSHIPS_OID: u32 = 17142; +pub const INDEX_MZ_INFERRED_RELATIONSHIPS_IND_OID: u32 = 17143; diff --git a/src/pgrepr-consts/src/regproc.rs b/src/pgrepr-consts/src/regproc.rs index 22e8be03c2ae2..dcd039765992a 100644 --- a/src/pgrepr-consts/src/regproc.rs +++ b/src/pgrepr-consts/src/regproc.rs @@ -693,6 +693,7 @@ pub const NAMES: &[(u32, &str)] = &[ (17131, "pg_catalog.max"), (17132, "pg_catalog.min"), (17138, "jq"), + (17141, "mz_internal.parse_catalog_view_joins"), // END GENERATED ]; diff --git a/src/sql/src/func.rs b/src/sql/src/func.rs index 44664f7ac5a0b..5b932c88284ed 100644 --- a/src/sql/src/func.rs +++ b/src/sql/src/func.rs @@ -5368,6 +5368,14 @@ pub static MZ_INTERNAL_BUILTINS: LazyLock> = LazyLo => SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)), oid::FUNC_PARSE_CATALOG_PRIVILEGES_OID; }, + "parse_catalog_view_joins" => Scalar { + params!(String) => Operation::unary(|ecx, create_sql| { + ecx.require_feature_flag(&vars::ENABLE_INFERRED_RELATIONSHIPS)?; + Ok(create_sql.call_unary(UnaryFunc::ParseCatalogViewJoins( + func::ParseCatalogViewJoins, + ))) + }) => Jsonb, oid::FUNC_PARSE_CATALOG_VIEW_JOINS_OID; + }, "parse_kafka_source_details" => Scalar { params!(String) => UnaryFunc::ParseKafkaSourceDetails( func::ParseKafkaSourceDetails, diff --git a/src/sql/src/session/vars/definitions.rs b/src/sql/src/session/vars/definitions.rs index 989fe6fa21666..669442b67573f 100644 --- a/src/sql/src/session/vars/definitions.rs +++ b/src/sql/src/session/vars/definitions.rs @@ -1936,6 +1936,12 @@ feature_flags!( default: false, enable_for_item_parsing: true, }, + { + name: enable_inferred_relationships, + desc: "inferring relationships between relations from view definitions", + default: false, + enable_for_item_parsing: true, + }, { name: enable_envelope_debezium_in_subscribe, desc: "`ENVELOPE DEBEZIUM (KEY (..))`", diff --git a/src/sql/system-parameters.json b/src/sql/system-parameters.json index 2472ad6571ab6..e7dd9894e5aa8 100644 --- a/src/sql/system-parameters.json +++ b/src/sql/system-parameters.json @@ -1183,6 +1183,15 @@ "userVisible": false, "dyncfg": false }, + { + "name": "enable_inferred_relationships", + "typeName": "boolean", + "default": "off", + "description": "Whether inferring relationships between relations from view definitions is allowed (Materialize).", + "scope": "environment", + "userVisible": false, + "dyncfg": false + }, { "name": "enable_internal_statement_logging", "typeName": "boolean", diff --git a/test/sqllogictest/autogenerated/mz_internal.slt b/test/sqllogictest/autogenerated/mz_internal.slt index f300cdd321c34..91c127bc0f056 100644 --- a/test/sqllogictest/autogenerated/mz_internal.slt +++ b/test/sqllogictest/autogenerated/mz_internal.slt @@ -303,6 +303,16 @@ hint text A␠suggestion␠to␠either␠change␠the␠object␠(e.g.␠creat details text Additional␠details␠on␠why␠the␠`hint`␠was␠proposed␠based␠on␠the␠dependencies␠of␠the␠object. referenced_object_ids list The␠IDs␠of␠objects␠referenced␠by␠`details`.␠Corresponds␠to␠mz_objects.id. +query TTT +SELECT name, type, comment FROM objects WHERE schema = 'mz_internal' AND object = 'mz_inferred_relationships' ORDER BY position +---- +source_id text The␠ID␠of␠the␠relation␠holding␠the␠referencing␠column.␠Corresponds␠to␠`mz_objects.id`. +source_column text The␠referencing␠column. +target_id text The␠ID␠of␠the␠relation␠holding␠the␠referenced␠column.␠Corresponds␠to␠`mz_objects.id`. +target_column text The␠referenced␠column. +is_directed boolean Whether␠a␠key␠decides␠which␠side␠references␠the␠other.␠When␠false,␠the␠two␠columns␠are␠only␠known␠to␠be␠joined,␠and␠their␠order␠is␠arbitrary. +inferred_from text[] The␠IDs␠of␠the␠views␠and␠materialized␠views␠whose␠definitions␠imply␠the␠relationship. + query TTT SELECT name, type, comment FROM objects WHERE schema = 'mz_internal' AND object = 'mz_materialization_dependencies' ORDER BY position ---- @@ -850,6 +860,7 @@ mz_global_frontiers mz_history_retention_strategies mz_hydration_statuses mz_index_advice +mz_inferred_relationships mz_internal_cluster_replicas mz_kafka_source_tables mz_license_keys diff --git a/test/sqllogictest/catalog_server_explain.slt b/test/sqllogictest/catalog_server_explain.slt index fa2a99c7230a8..09c593028143d 100644 --- a/test/sqllogictest/catalog_server_explain.slt +++ b/test/sqllogictest/catalog_server_explain.slt @@ -4949,7 +4949,7 @@ mz_catalog.mz_columns: Project: #6, #0..=#3, #7, #4, #5 Map: null →Arrange (#0{schema_name}, #1{relation_name}) - →Constant (1938 rows) + →Constant (1944 rows) →Arrange (#1{schema_name}, #2{name}) →Fused with Child Map/Filter/Project Project: #6, #4, #3 @@ -5092,7 +5092,7 @@ mz_catalog.mz_index_columns: Project: #3, #0, #1, #4, #2 Map: null →Arrange (#0{name}) - →Constant (95 rows) + →Constant (96 rows) →Arrange (#1{name}) →Fused with Child Map/Filter/Project Project: #4, #3 @@ -5162,7 +5162,7 @@ mz_catalog.mz_indexes: Project: #2, #0, #1, #3, #4, #7, #5, #6 Map: "s1" →Arrange (#1{name}) (#2{on_schema_name}, #3{on_name}) - →Constant (82 rows) + →Constant (83 rows) →Arrange (empty key) (#1{name}) →Fused with Child Map/Filter/Project Project: #4, #3 @@ -5362,7 +5362,7 @@ mz_catalog.mz_materialized_views: Project: #4, #0, #5, #1, #6, #2, #9, #8, #3, #7 Map: {=r/s1, s1=r/s1}, "s1" →Arrange (#1{schema_name}, #2{name}) - →Constant (51 rows) + →Constant (52 rows) →Arrange (empty key) (#0{schema_name}) (#0{schema_name}, #1{name}) →Fused with Child Map/Filter/Project Project: #4, #3, #5 @@ -5903,7 +5903,7 @@ mz_internal.mz_history_retention_strategies: Project: #3, #5 Map: ("s" || ((#4{data} -> "value") ->> "catalog_id")) →Arrange (#2{name}, #0{object_type}, #1{schema_name}) - →Constant (180 rows) + →Constant (182 rows) →Arrange (((#0{data} -> "key") ->> "object_name"), ((#0{data} -> "key") ->> "object_type"), ((#0{data} -> "key") ->> "schema_name")) →Fused with Child Map/Filter/Project Project: #0 @@ -6065,7 +6065,7 @@ mz_internal.mz_materialized_view_refresh_strategies: Project: #0..=#3, #3 Map: "on-commit", null, null →Arrange (#1{name}, #0{schema_name}) - →Constant (51 rows) + →Constant (52 rows) →Arrange (((#0{data} -> "key") ->> "object_name"), ((#0{data} -> "key") ->> "schema_name")) →Fused with Child Map/Filter/Project Project: #0 @@ -6249,7 +6249,7 @@ mz_internal.mz_object_dependencies: Project: #4..=#6, #2 Filter: case when (#7{ref_kind} = "func") then (#3{object_type} = "8") else case when (#7{ref_kind} = "type") then (#3{object_type} = "7") else ((#3{object_type} != "7") AND (#3{object_type} != "8")) end end →Arrange (#0{object_schema}..=#2{object_type}) (#3{ref_schema}, #4{ref_name}) - →Constant (1088 rows) + →Constant (1102 rows) →Arrange (#1{schema_name}..=#3{object_type}) →Fused with Child Map/Filter/Project Project: #5, #4, #2, #3 @@ -8815,7 +8815,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_columns"; ---- Explained Query (fast path): - →Constant (1938 rows) + →Constant (1944 rows) Target cluster: mz_catalog_server @@ -8825,7 +8825,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_index_columns"; ---- Explained Query (fast path): - →Constant (178 rows) + →Constant (179 rows) Target cluster: mz_catalog_server @@ -8835,7 +8835,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_indexes"; ---- Explained Query (fast path): - →Constant (82 rows) + →Constant (83 rows) Target cluster: mz_catalog_server @@ -8855,7 +8855,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_materialized_views"; ---- Explained Query (fast path): - →Constant (51 rows) + →Constant (52 rows) Target cluster: mz_catalog_server @@ -10836,7 +10836,7 @@ Explained Query: Project: #3, #4 Filter: case when (#2{ref_kind} = "func") then (#5{object_type} = "8") else case when (#2{ref_kind} = "type") then (#5{object_type} = "7") else ((#5{object_type} != "7") AND (#5{object_type} != "8")) end end →Unarranged Raw Stream - →Constant (1088 rows) + →Constant (1102 rows) →Arrange (#1{schema_name}..=#3{object_type}) →Fused with Child Map/Filter/Project Project: #5, #4, #2, #3 diff --git a/test/sqllogictest/information_schema_tables.slt b/test/sqllogictest/information_schema_tables.slt index 00fc60ceb506d..30ed7d5db19d7 100644 --- a/test/sqllogictest/information_schema_tables.slt +++ b/test/sqllogictest/information_schema_tables.slt @@ -441,6 +441,10 @@ mz_index_advice VIEW materialize mz_internal +mz_inferred_relationships +MATERIALIZED VIEW +materialize +mz_internal mz_internal_cluster_replicas MATERIALIZED VIEW materialize diff --git a/test/sqllogictest/mz_catalog_server_index_accounting.slt b/test/sqllogictest/mz_catalog_server_index_accounting.slt index 3ffd73b735c18..086a065d822ac 100644 --- a/test/sqllogictest/mz_catalog_server_index_accounting.slt +++ b/test/sqllogictest/mz_catalog_server_index_accounting.slt @@ -37,110 +37,111 @@ mz_arrangement_heap_capacity_raw_s2_primary_idx CREATE␠INDEX␠"mz_arrangemen mz_arrangement_heap_size_raw_s2_primary_idx CREATE␠INDEX␠"mz_arrangement_heap_size_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_arrangement_heap_size_raw"␠("operator_id",␠"worker_id") mz_arrangement_records_raw_s2_primary_idx CREATE␠INDEX␠"mz_arrangement_records_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_arrangement_records_raw"␠("operator_id",␠"worker_id") mz_arrangement_sharing_raw_s2_primary_idx CREATE␠INDEX␠"mz_arrangement_sharing_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_arrangement_sharing_raw"␠("operator_id",␠"worker_id") -mz_cluster_auto_scaling_strategies_ind CREATE␠INDEX␠"mz_cluster_auto_scaling_strategies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s528␠AS␠"mz_internal"."mz_cluster_auto_scaling_strategies"]␠("cluster_id") -mz_cluster_deployment_lineage_ind CREATE␠INDEX␠"mz_cluster_deployment_lineage_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s777␠AS␠"mz_internal"."mz_cluster_deployment_lineage"]␠("cluster_id") +mz_cluster_auto_scaling_strategies_ind CREATE␠INDEX␠"mz_cluster_auto_scaling_strategies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s529␠AS␠"mz_internal"."mz_cluster_auto_scaling_strategies"]␠("cluster_id") +mz_cluster_deployment_lineage_ind CREATE␠INDEX␠"mz_cluster_deployment_lineage_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s779␠AS␠"mz_internal"."mz_cluster_deployment_lineage"]␠("cluster_id") mz_cluster_prometheus_metrics_s2_primary_idx CREATE␠INDEX␠"mz_cluster_prometheus_metrics_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_cluster_prometheus_metrics"␠("process_id",␠"metric_name",␠"labels") -mz_cluster_reconfigurations_ind CREATE␠INDEX␠"mz_cluster_reconfigurations_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s527␠AS␠"mz_internal"."mz_cluster_reconfigurations"]␠("cluster_id") -mz_cluster_replica_frontiers_ind CREATE␠INDEX␠"mz_cluster_replica_frontiers_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s771␠AS␠"mz_catalog"."mz_cluster_replica_frontiers"]␠("object_id") -mz_cluster_replica_history_ind CREATE␠INDEX␠"mz_cluster_replica_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s626␠AS␠"mz_internal"."mz_cluster_replica_history"]␠("dropped_at") -mz_cluster_replica_metrics_history_ind CREATE␠INDEX␠"mz_cluster_replica_metrics_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s533␠AS␠"mz_internal"."mz_cluster_replica_metrics_history"]␠("replica_id") -mz_cluster_replica_metrics_ind CREATE␠INDEX␠"mz_cluster_replica_metrics_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s534␠AS␠"mz_internal"."mz_cluster_replica_metrics"]␠("replica_id") -mz_cluster_replica_name_history_ind CREATE␠INDEX␠"mz_cluster_replica_name_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s627␠AS␠"mz_internal"."mz_cluster_replica_name_history"]␠("id") +mz_cluster_reconfigurations_ind CREATE␠INDEX␠"mz_cluster_reconfigurations_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s528␠AS␠"mz_internal"."mz_cluster_reconfigurations"]␠("cluster_id") +mz_cluster_replica_frontiers_ind CREATE␠INDEX␠"mz_cluster_replica_frontiers_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s773␠AS␠"mz_catalog"."mz_cluster_replica_frontiers"]␠("object_id") +mz_cluster_replica_history_ind CREATE␠INDEX␠"mz_cluster_replica_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s628␠AS␠"mz_internal"."mz_cluster_replica_history"]␠("dropped_at") +mz_cluster_replica_metrics_history_ind CREATE␠INDEX␠"mz_cluster_replica_metrics_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s534␠AS␠"mz_internal"."mz_cluster_replica_metrics_history"]␠("replica_id") +mz_cluster_replica_metrics_ind CREATE␠INDEX␠"mz_cluster_replica_metrics_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s535␠AS␠"mz_internal"."mz_cluster_replica_metrics"]␠("replica_id") +mz_cluster_replica_name_history_ind CREATE␠INDEX␠"mz_cluster_replica_name_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s629␠AS␠"mz_internal"."mz_cluster_replica_name_history"]␠("id") mz_cluster_replica_resource_usage_s2_primary_idx CREATE␠INDEX␠"mz_cluster_replica_resource_usage_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_cluster_replica_resource_usage"␠("process_id",␠"source",␠"metric") -mz_cluster_replica_size_internal_ind CREATE␠INDEX␠"mz_cluster_replica_size_internal_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s523␠AS␠"mz_internal"."mz_cluster_replica_size_internal"]␠("size") -mz_cluster_replica_sizes_ind CREATE␠INDEX␠"mz_cluster_replica_sizes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s522␠AS␠"mz_catalog"."mz_cluster_replica_sizes"]␠("size") -mz_cluster_replica_status_history_ind CREATE␠INDEX␠"mz_cluster_replica_status_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s535␠AS␠"mz_internal"."mz_cluster_replica_status_history"]␠("replica_id") -mz_cluster_replica_statuses_ind CREATE␠INDEX␠"mz_cluster_replica_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s536␠AS␠"mz_internal"."mz_cluster_replica_statuses"]␠("replica_id") -mz_cluster_replicas_ind CREATE␠INDEX␠"mz_cluster_replicas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s532␠AS␠"mz_catalog"."mz_cluster_replicas"]␠("id") -mz_clusters_ind CREATE␠INDEX␠"mz_clusters_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s524␠AS␠"mz_catalog"."mz_clusters"]␠("id") -mz_columns_ind CREATE␠INDEX␠"mz_columns_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s495␠AS␠"mz_catalog"."mz_columns"]␠("name") -mz_comments_ind CREATE␠INDEX␠"mz_comments_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s551␠AS␠"mz_internal"."mz_comments"]␠("id") +mz_cluster_replica_size_internal_ind CREATE␠INDEX␠"mz_cluster_replica_size_internal_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s524␠AS␠"mz_internal"."mz_cluster_replica_size_internal"]␠("size") +mz_cluster_replica_sizes_ind CREATE␠INDEX␠"mz_cluster_replica_sizes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s523␠AS␠"mz_catalog"."mz_cluster_replica_sizes"]␠("size") +mz_cluster_replica_status_history_ind CREATE␠INDEX␠"mz_cluster_replica_status_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s536␠AS␠"mz_internal"."mz_cluster_replica_status_history"]␠("replica_id") +mz_cluster_replica_statuses_ind CREATE␠INDEX␠"mz_cluster_replica_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s537␠AS␠"mz_internal"."mz_cluster_replica_statuses"]␠("replica_id") +mz_cluster_replicas_ind CREATE␠INDEX␠"mz_cluster_replicas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s533␠AS␠"mz_catalog"."mz_cluster_replicas"]␠("id") +mz_clusters_ind CREATE␠INDEX␠"mz_clusters_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s525␠AS␠"mz_catalog"."mz_clusters"]␠("id") +mz_columns_ind CREATE␠INDEX␠"mz_columns_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s496␠AS␠"mz_catalog"."mz_columns"]␠("name") +mz_comments_ind CREATE␠INDEX␠"mz_comments_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s552␠AS␠"mz_internal"."mz_comments"]␠("id") mz_compute_dataflow_global_ids_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_dataflow_global_ids_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_dataflow_global_ids_per_worker"␠("id",␠"worker_id",␠"global_id") -mz_compute_dependencies_ind CREATE␠INDEX␠"mz_compute_dependencies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s752␠AS␠"mz_internal"."mz_compute_dependencies"]␠("dependency_id") +mz_compute_dependencies_ind CREATE␠INDEX␠"mz_compute_dependencies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s754␠AS␠"mz_internal"."mz_compute_dependencies"]␠("dependency_id") mz_compute_error_counts_raw_s2_primary_idx CREATE␠INDEX␠"mz_compute_error_counts_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_error_counts_raw"␠("export_id",␠"worker_id") mz_compute_exports_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_exports_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_exports_per_worker"␠("export_id",␠"worker_id") mz_compute_frontiers_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_frontiers_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_frontiers_per_worker"␠("export_id",␠"worker_id") -mz_compute_hydration_times_ind CREATE␠INDEX␠"mz_compute_hydration_times_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s762␠AS␠"mz_internal"."mz_compute_hydration_times"]␠("replica_id") +mz_compute_hydration_times_ind CREATE␠INDEX␠"mz_compute_hydration_times_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s764␠AS␠"mz_internal"."mz_compute_hydration_times"]␠("replica_id") mz_compute_hydration_times_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_hydration_times_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_hydration_times_per_worker"␠("export_id",␠"worker_id") mz_compute_import_frontiers_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_import_frontiers_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_import_frontiers_per_worker"␠("export_id",␠"import_id",␠"worker_id") mz_compute_lir_mapping_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_lir_mapping_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_lir_mapping_per_worker"␠("global_id",␠"lir_id",␠"worker_id") mz_compute_operator_durations_histogram_raw_s2_primary_idx CREATE␠INDEX␠"mz_compute_operator_durations_histogram_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_operator_durations_histogram_raw"␠("id",␠"worker_id",␠"duration_ns") mz_compute_operator_hydration_statuses_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_compute_operator_hydration_statuses_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_compute_operator_hydration_statuses_per_worker"␠("export_id",␠"lir_id",␠"worker_id") -mz_connections_ind CREATE␠INDEX␠"mz_connections_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s530␠AS␠"mz_catalog"."mz_connections"]␠("schema_id") -mz_console_cluster_utilization_overview_24h_ind CREATE␠INDEX␠"mz_console_cluster_utilization_overview_24h_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s758␠AS␠"mz_internal"."mz_console_cluster_utilization_overview_24h"]␠("cluster_id") -mz_console_cluster_utilization_overview_3h_ind CREATE␠INDEX␠"mz_console_cluster_utilization_overview_3h_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s757␠AS␠"mz_internal"."mz_console_cluster_utilization_overview_3h"]␠("cluster_id") -mz_console_cluster_utilization_overview_ind CREATE␠INDEX␠"mz_console_cluster_utilization_overview_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s756␠AS␠"mz_internal"."mz_console_cluster_utilization_overview"]␠("cluster_id") -mz_databases_ind CREATE␠INDEX␠"mz_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s493␠AS␠"mz_catalog"."mz_databases"]␠("name") +mz_connections_ind CREATE␠INDEX␠"mz_connections_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s531␠AS␠"mz_catalog"."mz_connections"]␠("schema_id") +mz_console_cluster_utilization_overview_24h_ind CREATE␠INDEX␠"mz_console_cluster_utilization_overview_24h_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s760␠AS␠"mz_internal"."mz_console_cluster_utilization_overview_24h"]␠("cluster_id") +mz_console_cluster_utilization_overview_3h_ind CREATE␠INDEX␠"mz_console_cluster_utilization_overview_3h_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s759␠AS␠"mz_internal"."mz_console_cluster_utilization_overview_3h"]␠("cluster_id") +mz_console_cluster_utilization_overview_ind CREATE␠INDEX␠"mz_console_cluster_utilization_overview_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s758␠AS␠"mz_internal"."mz_console_cluster_utilization_overview"]␠("cluster_id") +mz_databases_ind CREATE␠INDEX␠"mz_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s494␠AS␠"mz_catalog"."mz_databases"]␠("name") mz_dataflow_addresses_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_dataflow_addresses_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_dataflow_addresses_per_worker"␠("id",␠"worker_id") mz_dataflow_channels_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_dataflow_channels_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_dataflow_channels_per_worker"␠("id",␠"worker_id") mz_dataflow_operator_reachability_raw_s2_primary_idx CREATE␠INDEX␠"mz_dataflow_operator_reachability_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_dataflow_operator_reachability_raw"␠("id",␠"worker_id",␠"source",␠"port",␠"update_type",␠"time") mz_dataflow_operators_per_worker_s2_primary_idx CREATE␠INDEX␠"mz_dataflow_operators_per_worker_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_dataflow_operators_per_worker"␠("id",␠"worker_id") -mz_frontiers_ind CREATE␠INDEX␠"mz_frontiers_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s743␠AS␠"mz_internal"."mz_frontiers"]␠("object_id") -mz_hydration_statuses_ind CREATE␠INDEX␠"mz_hydration_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s773␠AS␠"mz_internal"."mz_hydration_statuses"]␠("object_id",␠"replica_id") -mz_indexes_ind CREATE␠INDEX␠"mz_indexes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s496␠AS␠"mz_catalog"."mz_indexes"]␠("id") -mz_kafka_sources_ind CREATE␠INDEX␠"mz_kafka_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s489␠AS␠"mz_catalog"."mz_kafka_sources"]␠("id") -mz_materialized_views_ind CREATE␠INDEX␠"mz_materialized_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s555␠AS␠"mz_catalog"."mz_materialized_views"]␠("id") +mz_frontiers_ind CREATE␠INDEX␠"mz_frontiers_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s745␠AS␠"mz_internal"."mz_frontiers"]␠("object_id") +mz_hydration_statuses_ind CREATE␠INDEX␠"mz_hydration_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s775␠AS␠"mz_internal"."mz_hydration_statuses"]␠("object_id",␠"replica_id") +mz_indexes_ind CREATE␠INDEX␠"mz_indexes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s497␠AS␠"mz_catalog"."mz_indexes"]␠("id") +mz_inferred_relationships_ind CREATE␠INDEX␠"mz_inferred_relationships_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s557␠AS␠"mz_internal"."mz_inferred_relationships"]␠("source_id") +mz_kafka_sources_ind CREATE␠INDEX␠"mz_kafka_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s490␠AS␠"mz_catalog"."mz_kafka_sources"]␠("id") +mz_materialized_views_ind CREATE␠INDEX␠"mz_materialized_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s556␠AS␠"mz_catalog"."mz_materialized_views"]␠("id") mz_message_batch_counts_received_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_batch_counts_received_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_message_batch_counts_received_raw"␠("channel_id",␠"from_worker_id",␠"to_worker_id") mz_message_batch_counts_sent_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_batch_counts_sent_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_message_batch_counts_sent_raw"␠("channel_id",␠"from_worker_id",␠"to_worker_id") mz_message_counts_received_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_counts_received_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_message_counts_received_raw"␠("channel_id",␠"from_worker_id",␠"to_worker_id") mz_message_counts_sent_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_counts_sent_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_message_counts_sent_raw"␠("channel_id",␠"from_worker_id",␠"to_worker_id") -mz_metric_sinks_ind CREATE␠INDEX␠"mz_metric_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s553␠AS␠"mz_internal"."mz_metric_sinks"]␠("id") -mz_notices_ind CREATE␠INDEX␠"mz_notices_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s851␠AS␠"mz_internal"."mz_notices"]␠("id") -mz_object_arrangement_size_history_object_ind CREATE␠INDEX␠"mz_object_arrangement_size_history_object_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s765␠AS␠"mz_internal"."mz_object_arrangement_size_history"]␠("object_id") -mz_object_arrangement_size_history_ts_ind CREATE␠INDEX␠"mz_object_arrangement_size_history_ts_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s765␠AS␠"mz_internal"."mz_object_arrangement_size_history"]␠("collection_timestamp") -mz_object_arrangement_sizes_ind CREATE␠INDEX␠"mz_object_arrangement_sizes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s763␠AS␠"mz_internal"."mz_object_arrangement_sizes"]␠("replica_id") -mz_object_dependencies_ind CREATE␠INDEX␠"mz_object_dependencies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s491␠AS␠"mz_internal"."mz_object_dependencies"]␠("object_id") -mz_object_graph_edges_ind CREATE␠INDEX␠"mz_object_graph_edges_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s754␠AS␠"mz_internal"."mz_object_graph_edges"]␠("object_id") -mz_object_history_ind CREATE␠INDEX␠"mz_object_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s566␠AS␠"mz_internal"."mz_object_history"]␠("id") -mz_object_lifetimes_ind CREATE␠INDEX␠"mz_object_lifetimes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s567␠AS␠"mz_internal"."mz_object_lifetimes"]␠("id") -mz_object_transitive_dependencies_ind CREATE␠INDEX␠"mz_object_transitive_dependencies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s583␠AS␠"mz_internal"."mz_object_transitive_dependencies"]␠("object_id") -mz_objects_ind CREATE␠INDEX␠"mz_objects_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s563␠AS␠"mz_catalog"."mz_objects"]␠("schema_id") +mz_metric_sinks_ind CREATE␠INDEX␠"mz_metric_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s554␠AS␠"mz_internal"."mz_metric_sinks"]␠("id") +mz_notices_ind CREATE␠INDEX␠"mz_notices_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s854␠AS␠"mz_internal"."mz_notices"]␠("id") +mz_object_arrangement_size_history_object_ind CREATE␠INDEX␠"mz_object_arrangement_size_history_object_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s767␠AS␠"mz_internal"."mz_object_arrangement_size_history"]␠("object_id") +mz_object_arrangement_size_history_ts_ind CREATE␠INDEX␠"mz_object_arrangement_size_history_ts_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s767␠AS␠"mz_internal"."mz_object_arrangement_size_history"]␠("collection_timestamp") +mz_object_arrangement_sizes_ind CREATE␠INDEX␠"mz_object_arrangement_sizes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s765␠AS␠"mz_internal"."mz_object_arrangement_sizes"]␠("replica_id") +mz_object_dependencies_ind CREATE␠INDEX␠"mz_object_dependencies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s492␠AS␠"mz_internal"."mz_object_dependencies"]␠("object_id") +mz_object_graph_edges_ind CREATE␠INDEX␠"mz_object_graph_edges_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s756␠AS␠"mz_internal"."mz_object_graph_edges"]␠("object_id") +mz_object_history_ind CREATE␠INDEX␠"mz_object_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s568␠AS␠"mz_internal"."mz_object_history"]␠("id") +mz_object_lifetimes_ind CREATE␠INDEX␠"mz_object_lifetimes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s569␠AS␠"mz_internal"."mz_object_lifetimes"]␠("id") +mz_object_transitive_dependencies_ind CREATE␠INDEX␠"mz_object_transitive_dependencies_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s585␠AS␠"mz_internal"."mz_object_transitive_dependencies"]␠("object_id") +mz_objects_ind CREATE␠INDEX␠"mz_objects_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s565␠AS␠"mz_catalog"."mz_objects"]␠("schema_id") mz_peek_durations_histogram_raw_s2_primary_idx CREATE␠INDEX␠"mz_peek_durations_histogram_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_peek_durations_histogram_raw"␠("worker_id",␠"type",␠"duration_ns") -mz_recent_activity_log_thinned_ind CREATE␠INDEX␠"mz_recent_activity_log_thinned_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s727␠AS␠"mz_internal"."mz_recent_activity_log_thinned"]␠("sql_hash") -mz_recent_sql_text_ind CREATE␠INDEX␠"mz_recent_sql_text_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s723␠AS␠"mz_internal"."mz_recent_sql_text"]␠("sql_hash") -mz_recent_storage_usage_ind CREATE␠INDEX␠"mz_recent_storage_usage_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s842␠AS␠"mz_catalog"."mz_recent_storage_usage"]␠("object_id") -mz_roles_ind CREATE␠INDEX␠"mz_roles_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s514␠AS␠"mz_catalog"."mz_roles"]␠("id") +mz_recent_activity_log_thinned_ind CREATE␠INDEX␠"mz_recent_activity_log_thinned_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s729␠AS␠"mz_internal"."mz_recent_activity_log_thinned"]␠("sql_hash") +mz_recent_sql_text_ind CREATE␠INDEX␠"mz_recent_sql_text_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s725␠AS␠"mz_internal"."mz_recent_sql_text"]␠("sql_hash") +mz_recent_storage_usage_ind CREATE␠INDEX␠"mz_recent_storage_usage_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s845␠AS␠"mz_catalog"."mz_recent_storage_usage"]␠("object_id") +mz_roles_ind CREATE␠INDEX␠"mz_roles_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s515␠AS␠"mz_catalog"."mz_roles"]␠("id") mz_scheduling_elapsed_raw_s2_primary_idx CREATE␠INDEX␠"mz_scheduling_elapsed_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_scheduling_elapsed_raw"␠("id",␠"worker_id") mz_scheduling_parks_histogram_raw_s2_primary_idx CREATE␠INDEX␠"mz_scheduling_parks_histogram_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_scheduling_parks_histogram_raw"␠("worker_id",␠"slept_for_ns",␠"requested_ns") -mz_schemas_ind CREATE␠INDEX␠"mz_schemas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s494␠AS␠"mz_catalog"."mz_schemas"]␠("database_id") -mz_secrets_ind CREATE␠INDEX␠"mz_secrets_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s529␠AS␠"mz_catalog"."mz_secrets"]␠("name") -mz_show_all_objects_ind CREATE␠INDEX␠"mz_show_all_objects_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s611␠AS␠"mz_internal"."mz_show_all_objects"]␠("schema_id") -mz_show_cluster_replicas_ind CREATE␠INDEX␠"mz_show_cluster_replicas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s775␠AS␠"mz_internal"."mz_show_cluster_replicas"]␠("cluster") -mz_show_clusters_ind CREATE␠INDEX␠"mz_show_clusters_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s613␠AS␠"mz_internal"."mz_show_clusters"]␠("name") -mz_show_columns_ind CREATE␠INDEX␠"mz_show_columns_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s612␠AS␠"mz_internal"."mz_show_columns"]␠("id") -mz_show_connections_ind CREATE␠INDEX␠"mz_show_connections_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s621␠AS␠"mz_internal"."mz_show_connections"]␠("schema_id") -mz_show_databases_ind CREATE␠INDEX␠"mz_show_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s615␠AS␠"mz_internal"."mz_show_databases"]␠("name") -mz_show_indexes_ind CREATE␠INDEX␠"mz_show_indexes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s625␠AS␠"mz_internal"."mz_show_indexes"]␠("schema_id") -mz_show_materialized_views_ind CREATE␠INDEX␠"mz_show_materialized_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s624␠AS␠"mz_internal"."mz_show_materialized_views"]␠("schema_id") -mz_show_roles_ind CREATE␠INDEX␠"mz_show_roles_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s620␠AS␠"mz_internal"."mz_show_roles"]␠("name") -mz_show_schemas_ind CREATE␠INDEX␠"mz_show_schemas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s616␠AS␠"mz_internal"."mz_show_schemas"]␠("database_id") -mz_show_secrets_ind CREATE␠INDEX␠"mz_show_secrets_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s614␠AS␠"mz_internal"."mz_show_secrets"]␠("schema_id") -mz_show_sinks_ind CREATE␠INDEX␠"mz_show_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s623␠AS␠"mz_internal"."mz_show_sinks"]␠("schema_id") -mz_show_sources_ind CREATE␠INDEX␠"mz_show_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s622␠AS␠"mz_internal"."mz_show_sources"]␠("schema_id") -mz_show_tables_ind CREATE␠INDEX␠"mz_show_tables_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s617␠AS␠"mz_internal"."mz_show_tables"]␠("schema_id") -mz_show_types_ind CREATE␠INDEX␠"mz_show_types_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s619␠AS␠"mz_internal"."mz_show_types"]␠("schema_id") -mz_show_views_ind CREATE␠INDEX␠"mz_show_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s618␠AS␠"mz_internal"."mz_show_views"]␠("schema_id") -mz_sink_statistics_ind CREATE␠INDEX␠"mz_sink_statistics_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s740␠AS␠"mz_internal"."mz_sink_statistics"]␠("id",␠"replica_id") -mz_sink_status_history_ind CREATE␠INDEX␠"mz_sink_status_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s712␠AS␠"mz_internal"."mz_sink_status_history"]␠("sink_id") -mz_sink_statuses_ind CREATE␠INDEX␠"mz_sink_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s713␠AS␠"mz_internal"."mz_sink_statuses"]␠("id") -mz_sinks_ind CREATE␠INDEX␠"mz_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s506␠AS␠"mz_catalog"."mz_sinks"]␠("id") -mz_source_statistics_ind CREATE␠INDEX␠"mz_source_statistics_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s738␠AS␠"mz_internal"."mz_source_statistics"]␠("id",␠"replica_id") -mz_source_statistics_with_history_ind CREATE␠INDEX␠"mz_source_statistics_with_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s736␠AS␠"mz_internal"."mz_source_statistics_with_history"]␠("id",␠"replica_id") -mz_source_status_history_ind CREATE␠INDEX␠"mz_source_status_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s714␠AS␠"mz_internal"."mz_source_status_history"]␠("source_id") -mz_source_statuses_ind CREATE␠INDEX␠"mz_source_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s731␠AS␠"mz_internal"."mz_source_statuses"]␠("id") -mz_sources_ind CREATE␠INDEX␠"mz_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s499␠AS␠"mz_catalog"."mz_sources"]␠("id") -mz_tables_ind CREATE␠INDEX␠"mz_tables_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s498␠AS␠"mz_catalog"."mz_tables"]␠("schema_id") -mz_types_ind CREATE␠INDEX␠"mz_types_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s508␠AS␠"mz_catalog"."mz_types"]␠("schema_id") -mz_views_ind CREATE␠INDEX␠"mz_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s507␠AS␠"mz_catalog"."mz_views"]␠("schema_id") -mz_wallclock_global_lag_recent_history_ind CREATE␠INDEX␠"mz_wallclock_global_lag_recent_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s747␠AS␠"mz_internal"."mz_wallclock_global_lag_recent_history"]␠("object_id") -mz_webhook_sources_ind CREATE␠INDEX␠"mz_webhook_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s552␠AS␠"mz_internal"."mz_webhook_sources"]␠("id") -pg_attrdef_all_databases_ind CREATE␠INDEX␠"pg_attrdef_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s652␠AS␠"mz_internal"."pg_attrdef_all_databases"]␠("oid",␠"adrelid",␠"adnum",␠"adbin",␠"adsrc") -pg_attribute_all_databases_ind CREATE␠INDEX␠"pg_attribute_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s645␠AS␠"mz_internal"."pg_attribute_all_databases"]␠("attrelid") -pg_authid_core_ind CREATE␠INDEX␠"pg_authid_core_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s662␠AS␠"mz_internal"."pg_authid_core"]␠("rolname") -pg_class_all_databases_ind CREATE␠INDEX␠"pg_class_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s633␠AS␠"mz_internal"."pg_class_all_databases"]␠("relname") -pg_description_all_databases_ind CREATE␠INDEX␠"pg_description_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s642␠AS␠"mz_internal"."pg_description_all_databases"]␠("objoid",␠"classoid",␠"objsubid",␠"description",␠"oid_database_name",␠"class_database_name") -pg_namespace_all_databases_ind CREATE␠INDEX␠"pg_namespace_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s630␠AS␠"mz_internal"."pg_namespace_all_databases"]␠("nspname") -pg_type_all_databases_ind CREATE␠INDEX␠"pg_type_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s639␠AS␠"mz_internal"."pg_type_all_databases"]␠("oid") +mz_schemas_ind CREATE␠INDEX␠"mz_schemas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s495␠AS␠"mz_catalog"."mz_schemas"]␠("database_id") +mz_secrets_ind CREATE␠INDEX␠"mz_secrets_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s530␠AS␠"mz_catalog"."mz_secrets"]␠("name") +mz_show_all_objects_ind CREATE␠INDEX␠"mz_show_all_objects_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s613␠AS␠"mz_internal"."mz_show_all_objects"]␠("schema_id") +mz_show_cluster_replicas_ind CREATE␠INDEX␠"mz_show_cluster_replicas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s777␠AS␠"mz_internal"."mz_show_cluster_replicas"]␠("cluster") +mz_show_clusters_ind CREATE␠INDEX␠"mz_show_clusters_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s615␠AS␠"mz_internal"."mz_show_clusters"]␠("name") +mz_show_columns_ind CREATE␠INDEX␠"mz_show_columns_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s614␠AS␠"mz_internal"."mz_show_columns"]␠("id") +mz_show_connections_ind CREATE␠INDEX␠"mz_show_connections_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s623␠AS␠"mz_internal"."mz_show_connections"]␠("schema_id") +mz_show_databases_ind CREATE␠INDEX␠"mz_show_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s617␠AS␠"mz_internal"."mz_show_databases"]␠("name") +mz_show_indexes_ind CREATE␠INDEX␠"mz_show_indexes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s627␠AS␠"mz_internal"."mz_show_indexes"]␠("schema_id") +mz_show_materialized_views_ind CREATE␠INDEX␠"mz_show_materialized_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s626␠AS␠"mz_internal"."mz_show_materialized_views"]␠("schema_id") +mz_show_roles_ind CREATE␠INDEX␠"mz_show_roles_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s622␠AS␠"mz_internal"."mz_show_roles"]␠("name") +mz_show_schemas_ind CREATE␠INDEX␠"mz_show_schemas_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s618␠AS␠"mz_internal"."mz_show_schemas"]␠("database_id") +mz_show_secrets_ind CREATE␠INDEX␠"mz_show_secrets_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s616␠AS␠"mz_internal"."mz_show_secrets"]␠("schema_id") +mz_show_sinks_ind CREATE␠INDEX␠"mz_show_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s625␠AS␠"mz_internal"."mz_show_sinks"]␠("schema_id") +mz_show_sources_ind CREATE␠INDEX␠"mz_show_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s624␠AS␠"mz_internal"."mz_show_sources"]␠("schema_id") +mz_show_tables_ind CREATE␠INDEX␠"mz_show_tables_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s619␠AS␠"mz_internal"."mz_show_tables"]␠("schema_id") +mz_show_types_ind CREATE␠INDEX␠"mz_show_types_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s621␠AS␠"mz_internal"."mz_show_types"]␠("schema_id") +mz_show_views_ind CREATE␠INDEX␠"mz_show_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s620␠AS␠"mz_internal"."mz_show_views"]␠("schema_id") +mz_sink_statistics_ind CREATE␠INDEX␠"mz_sink_statistics_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s742␠AS␠"mz_internal"."mz_sink_statistics"]␠("id",␠"replica_id") +mz_sink_status_history_ind CREATE␠INDEX␠"mz_sink_status_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s714␠AS␠"mz_internal"."mz_sink_status_history"]␠("sink_id") +mz_sink_statuses_ind CREATE␠INDEX␠"mz_sink_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s715␠AS␠"mz_internal"."mz_sink_statuses"]␠("id") +mz_sinks_ind CREATE␠INDEX␠"mz_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s507␠AS␠"mz_catalog"."mz_sinks"]␠("id") +mz_source_statistics_ind CREATE␠INDEX␠"mz_source_statistics_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s740␠AS␠"mz_internal"."mz_source_statistics"]␠("id",␠"replica_id") +mz_source_statistics_with_history_ind CREATE␠INDEX␠"mz_source_statistics_with_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s738␠AS␠"mz_internal"."mz_source_statistics_with_history"]␠("id",␠"replica_id") +mz_source_status_history_ind CREATE␠INDEX␠"mz_source_status_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s716␠AS␠"mz_internal"."mz_source_status_history"]␠("source_id") +mz_source_statuses_ind CREATE␠INDEX␠"mz_source_statuses_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s733␠AS␠"mz_internal"."mz_source_statuses"]␠("id") +mz_sources_ind CREATE␠INDEX␠"mz_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s500␠AS␠"mz_catalog"."mz_sources"]␠("id") +mz_tables_ind CREATE␠INDEX␠"mz_tables_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s499␠AS␠"mz_catalog"."mz_tables"]␠("schema_id") +mz_types_ind CREATE␠INDEX␠"mz_types_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s509␠AS␠"mz_catalog"."mz_types"]␠("schema_id") +mz_views_ind CREATE␠INDEX␠"mz_views_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s508␠AS␠"mz_catalog"."mz_views"]␠("schema_id") +mz_wallclock_global_lag_recent_history_ind CREATE␠INDEX␠"mz_wallclock_global_lag_recent_history_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s749␠AS␠"mz_internal"."mz_wallclock_global_lag_recent_history"]␠("object_id") +mz_webhook_sources_ind CREATE␠INDEX␠"mz_webhook_sources_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s553␠AS␠"mz_internal"."mz_webhook_sources"]␠("id") +pg_attrdef_all_databases_ind CREATE␠INDEX␠"pg_attrdef_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s654␠AS␠"mz_internal"."pg_attrdef_all_databases"]␠("oid",␠"adrelid",␠"adnum",␠"adbin",␠"adsrc") +pg_attribute_all_databases_ind CREATE␠INDEX␠"pg_attribute_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s647␠AS␠"mz_internal"."pg_attribute_all_databases"]␠("attrelid") +pg_authid_core_ind CREATE␠INDEX␠"pg_authid_core_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s664␠AS␠"mz_internal"."pg_authid_core"]␠("rolname") +pg_class_all_databases_ind CREATE␠INDEX␠"pg_class_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s635␠AS␠"mz_internal"."pg_class_all_databases"]␠("relname") +pg_description_all_databases_ind CREATE␠INDEX␠"pg_description_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s644␠AS␠"mz_internal"."pg_description_all_databases"]␠("objoid",␠"classoid",␠"objsubid",␠"description",␠"oid_database_name",␠"class_database_name") +pg_namespace_all_databases_ind CREATE␠INDEX␠"pg_namespace_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s632␠AS␠"mz_internal"."pg_namespace_all_databases"]␠("nspname") +pg_type_all_databases_ind CREATE␠INDEX␠"pg_type_all_databases_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s641␠AS␠"mz_internal"."pg_type_all_databases"]␠("oid") # Record all transitive dependencies (tables, sources, views, mvs) of indexes on # the mz_catalog_server cluster. @@ -545,6 +546,12 @@ mz_indexes oid mz_indexes on_id mz_indexes owner_id mz_indexes redacted_create_sql +mz_inferred_relationships inferred_from +mz_inferred_relationships is_directed +mz_inferred_relationships source_column +mz_inferred_relationships source_id +mz_inferred_relationships target_column +mz_inferred_relationships target_id mz_kafka_sources group_id_prefix mz_kafka_sources id mz_kafka_sources topic diff --git a/test/sqllogictest/mz_inferred_relationships.slt b/test/sqllogictest/mz_inferred_relationships.slt new file mode 100644 index 0000000000000..35f4e2df07e15 --- /dev/null +++ b/test/sqllogictest/mz_inferred_relationships.slt @@ -0,0 +1,158 @@ +# Copyright Materialize, Inc. and contributors. All rights reserved. +# +# Use of this software is governed by the Business Source License +# included in the LICENSE file at the root of this repository. +# +# As of the Change Date specified in that file, in accordance with +# the Business Source License, use of this software will be governed +# by the Apache License, Version 2.0. + +# Tests for mz_internal.mz_inferred_relationships and the function it reads +# view definitions with, mz_internal.parse_catalog_view_joins. + +mode cockroach + +reset-server + +simple conn=mz_system,user=mz_system +ALTER SYSTEM SET enable_inferred_relationships = on +---- +COMPLETE 0 + +statement ok +CREATE TABLE organizations (id int, name text) + +statement ok +CREATE TABLE users (id int, org_id int, name text) + +statement ok +CREATE TABLE accounts (id int, org_id int, balance int) + +statement ok +CREATE TABLE auctions (id int, seller int, item text) + +statement ok +CREATE TABLE bids (id int, buyer int, auction_id int, amount int) + +# Joins `bids.auction_id` to `auctions.id`, and passes `auctions.id`, +# `bids.id`, `bids.buyer` and `auctions.seller` through. +statement ok +CREATE MATERIALIZED VIEW winning_bids AS + SELECT DISTINCT ON (a.id) b.id AS bid_id, a.id AS auction_id, b.buyer, a.seller + FROM auctions a JOIN bids b ON a.id = b.auction_id + ORDER BY a.id, b.amount DESC + +statement ok +CREATE VIEW org_spend AS + SELECT o.id AS org_id, o.name + FROM organizations o + JOIN users u ON u.org_id = o.id + JOIN winning_bids w ON w.buyer = u.id + +statement ok +CREATE VIEW seller_performance AS + SELECT u.id AS seller_id, count(*) AS sold + FROM users u JOIN winning_bids w ON w.seller = u.id + GROUP BY u.id + +# Neither column is a key, so the relationship stays undirected. +statement ok +CREATE VIEW user_accounts AS + SELECT users.name, a.balance FROM users JOIN accounts a USING (org_id) + +# Nothing here is attributable: a CTE, an expression, and an alias bound to +# two relations. +statement ok +CREATE VIEW opaque AS + WITH x AS (SELECT seller FROM auctions) + SELECT u.name FROM x, users u WHERE u.id = x.seller + UNION ALL + SELECT a.item FROM auctions a JOIN bids b ON a.id + 0 = b.auction_id + UNION ALL + SELECT a.item FROM auctions a JOIN (SELECT a.id FROM bids a) s ON s.id = a.id + +query TTTTB +SELECT s.name, r.source_column, t.name, r.target_column, r.is_directed +FROM mz_internal.mz_inferred_relationships r +JOIN mz_objects s ON s.id = r.source_id +JOIN mz_objects t ON t.id = r.target_id +ORDER BY 1, 2, 3, 4 +---- +auctions seller users id true +bids auction_id auctions id true +bids buyer users id true +org_spend org_id organizations id true +seller_performance seller_id users id true +users org_id accounts org_id false +users org_id organizations id true +winning_bids auction_id auctions id true +winning_bids bid_id bids id true +winning_bids buyer users id true +winning_bids seller users id true + +# Evidence names the views that imply each relationship. +query TT +SELECT r.source_column, v.name +FROM mz_internal.mz_inferred_relationships r +JOIN mz_objects s ON s.id = r.source_id +CROSS JOIN unnest(r.inferred_from) AS e(id) +JOIN mz_objects v ON v.id = e.id +WHERE s.name = 'bids' AND r.source_column = 'buyer' +---- +buyer winning_bids + +# A column that alone keys an index is the referenced side. +statement ok +CREATE TABLE products (sku text, name text) + +statement ok +CREATE TABLE order_lines (sku text, quantity int) + +statement ok +CREATE INDEX products_sku ON products (sku) + +statement ok +CREATE VIEW order_products AS + SELECT p.name, o.quantity FROM order_lines o JOIN products p ON p.sku = o.sku + +query TTTTB +SELECT s.name, r.source_column, t.name, r.target_column, r.is_directed +FROM mz_internal.mz_inferred_relationships r +JOIN mz_objects s ON s.id = r.source_id +JOIN mz_objects t ON t.id = r.target_id +WHERE s.name = 'order_lines' +---- +order_lines sku products sku true + +# Dropping the view retracts what it implied. +statement ok +DROP VIEW order_products + +query I +SELECT count(*) +FROM mz_internal.mz_inferred_relationships r +JOIN mz_objects s ON s.id = r.source_id +WHERE s.name = 'order_lines' +---- +0 + +query T +SELECT mz_internal.parse_catalog_view_joins(create_sql)->'outputs' +FROM mz_views WHERE name = 'seller_performance' +---- +[{"column":"seller_id","source_column":"id","source_id":"u2"}] + +simple conn=mz_system,user=mz_system +ALTER SYSTEM SET enable_inferred_relationships = off +---- +COMPLETE 0 + +query error inferring relationships between relations from view definitions is not available +SELECT mz_internal.parse_catalog_view_joins(create_sql) FROM mz_views + +# The builtin is maintained regardless, it does not call the function at +# query time. +query B +SELECT count(*) > 0 FROM mz_internal.mz_inferred_relationships +---- +true diff --git a/test/sqllogictest/oid.slt b/test/sqllogictest/oid.slt index 68a72efe3a2b6..9a0e7c7e7752b 100644 --- a/test/sqllogictest/oid.slt +++ b/test/sqllogictest/oid.slt @@ -1267,3 +1267,6 @@ SELECT oid, name FROM mz_objects WHERE id LIKE 's%' AND oid < 20000 ORDER BY oid 17138 jq 17139 mz_builtin_columns 17140 mz_builtin_index_columns +17141 parse_catalog_view_joins +17142 mz_inferred_relationships +17143 mz_inferred_relationships_ind From d8e56ab5ab0ffb003fe7daf3988ba34e5d5e9a86 Mon Sep 17 00:00:00 2001 From: jubrad Date: Mon, 16 Nov 2026 19:31:52 -0600 Subject: [PATCH 2/4] catalog: keep mz_inferred_relationships to direct edges Drop the WITH MUTUALLY RECURSIVE fixpoint. Every row now comes from a single view's definition, with a new `kind` column: `join` for columns a view equates, `key` for a key passed through, and `same_values` for any other column passed through. Relationships across several views are the paths through these rows. Maintaining the fixpoint was nearly all of the view's cost. Replacing 300 views with 3,000 present cost 1.66 ms of catalog server CPU per view with it and 0.68 ms without, against 0.57 ms for mz_object_dependencies, and hydration no longer outlasts mz_views. Paths lose nothing: on the auction demo, every relationship the fixpoint derived is connected, and so is every resolvable row of a hand-written ontology table. Also drops the column existence joins, since the planner validated every column a persisted definition names, and the pass that dropped undirected duplicates, since direction depends only on the two columns. Co-Authored-By: Claude Opus 5.5 --- .../content/sql/system-catalog/mz_internal.md | 34 ++--- .../src/builtin/mz_inferred_relationships.rs | 117 ++++++------------ .../autogenerated/mz_internal.slt | 1 + test/sqllogictest/catalog_server_explain.slt | 8 +- .../mz_catalog_server_index_accounting.slt | 1 + .../mz_inferred_relationships.slt | 41 +++--- 6 files changed, 85 insertions(+), 117 deletions(-) diff --git a/doc/user/content/sql/system-catalog/mz_internal.md b/doc/user/content/sql/system-catalog/mz_internal.md index 1172407ae36ba..ef97484741374 100644 --- a/doc/user/content/sql/system-catalog/mz_internal.md +++ b/doc/user/content/sql/system-catalog/mz_internal.md @@ -540,24 +540,28 @@ deploying the changes to production. The `mz_inferred_relationships` view describes relationships between user relations that the definitions of views and materialized views imply, without -declared keys. A view that joins two relations on a pair of columns implies a -relationship between them. A view that passes a key column through, as in -`SELECT o.id AS org_id`, implies that its output column references that key. +declared keys. Each row comes from a single view's definition: -The referenced side of a join is a column that alone keys an index, then a -column named `id`, then the side not named `*_id`. A relationship that none of -these settle is undirected. Relationships implied by passed-through columns -describe the columns' domain, not their data: a view may filter, so its input -column can hold values that its output never shows. +- A `join`: the view joins the two columns. The referenced side is a column + that alone keys an index, then a column named `id`, then the side not named + `*_id`. A join that none of these settle is undirected. +- A `key`: the view passes a key through unchanged, as in + `SELECT o.id AS org_id`, so its output column references that key. +- `same_values`: the view passes any other column through unchanged. + +Relationships across several views are the paths through these rows. A +`same_values` row describes the columns' domain, not their data: a view may +filter, so its input column can hold values that its output never shows. -| Field | Type | Meaning | -| --------------- | ----------- | -------- | -| `source_id` | [`text`] | The ID of the relation holding the referencing column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | -| `source_column` | [`text`] | The referencing column. | -| `target_id` | [`text`] | The ID of the relation holding the referenced column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | -| `target_column` | [`text`] | The referenced column. | -| `is_directed` | [`boolean`] | Whether a key decides which side references the other. When false, the two columns are only known to be joined, and their order is arbitrary. | +| Field | Type | Meaning | +| --------------- | -------------- | -------- | +| `source_id` | [`text`] | The ID of the relation holding the referencing column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | +| `source_column` | [`text`] | The referencing column. | +| `target_id` | [`text`] | The ID of the relation holding the referenced column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | +| `target_column` | [`text`] | The referenced column. | +| `kind` | [`text`] | `join` when a view joins the two columns, `key` when a view passes the target key through as the source column, and `same_values` when a view passes any other target column through as the source column. | +| `is_directed` | [`boolean`] | Whether a key decides which side references the other. When false, the two columns are only known to be joined, and their order is arbitrary. | | `inferred_from` | [`text array`] | The IDs of the views and materialized views whose definitions imply the relationship. | ## `mz_materialization_dependencies` diff --git a/src/catalog/src/builtin/mz_inferred_relationships.rs b/src/catalog/src/builtin/mz_inferred_relationships.rs index ccd81b38bff29..5f50d08be6b01 100644 --- a/src/catalog/src/builtin/mz_inferred_relationships.rs +++ b/src/catalog/src/builtin/mz_inferred_relationships.rs @@ -21,19 +21,22 @@ use super::{BuiltinIndex, BuiltinMaterializedView, PUBLIC_SELECT}; /// Relationships between user relations that their views' definitions imply, /// with no declared keys. /// -/// Evidence is of two kinds, both read by `parse_catalog_view_joins`: +/// Every row comes from a single view's definition, read by +/// `parse_catalog_view_joins`, so the view stays linear in the number of +/// views: /// -/// 1. A join: two relations' columns a view equates. The referenced side is -/// a column that alone keys an index, then a column named `id`, then the -/// side not named `*_id`. A join neither settles is kept undirected. -/// 2. A passed-through column: a view's output column that is an input -/// column unchanged. An output that passes a key references that key. -/// An output that passes any other column holds the same values as it, so -/// a reference either has, the other has too. This runs to a fixed point, -/// through views over views. +/// - `join`: two relations' columns a view equates. The referenced side is a +/// column that alone keys an index, then a column named `id`, then the side +/// not named `*_id`. A join neither settles is undirected. +/// - `key`: a view's output column that is an input key unchanged, which +/// references that key. +/// - `same_values`: a view's output column that is any other input column +/// unchanged. /// -/// The second is a claim about the columns' domain, not their data: a view -/// may filter, so its input column can hold values its output never shows. +/// Relationships across several views follow by chaining rows. Deriving them +/// here was measured at about three times the maintenance cost of +/// `mz_object_dependencies` per replaced view, nearly all of it the +/// fixpoint, for no information the chained rows lack. pub static MZ_INFERRED_RELATIONSHIPS: LazyLock = LazyLock::new(|| { BuiltinMaterializedView { name: "mz_inferred_relationships", @@ -44,12 +47,13 @@ pub static MZ_INFERRED_RELATIONSHIPS: LazyLock = LazyLo .with_column("source_column", SqlScalarType::String.nullable(false)) .with_column("target_id", SqlScalarType::String.nullable(false)) .with_column("target_column", SqlScalarType::String.nullable(false)) + .with_column("kind", SqlScalarType::String.nullable(false)) .with_column("is_directed", SqlScalarType::Bool.nullable(false)) .with_column( "inferred_from", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false), ) - .with_key(vec![0, 1, 2, 3]) + .with_key(vec![0, 1, 2, 3, 4]) .finish(), column_comments: BTreeMap::from_iter([ ( @@ -62,6 +66,10 @@ pub static MZ_INFERRED_RELATIONSHIPS: LazyLock = LazyLo "The ID of the relation holding the referenced column. Corresponds to `mz_objects.id`.", ), ("target_column", "The referenced column."), + ( + "kind", + "`join` when a view joins the two columns, `key` when a view passes the target key through as the source column, and `same_values` when a view passes any other target column through as the source column.", + ), ( "is_directed", "Whether a key decides which side references the other. When false, the two columns are only known to be joined, and their order is arbitrary.", @@ -78,6 +86,7 @@ WITH ( ASSERT NOT NULL source_column, ASSERT NOT NULL target_id, ASSERT NOT NULL target_column, + ASSERT NOT NULL kind, ASSERT NOT NULL is_directed, ASSERT NOT NULL inferred_from ) AS @@ -143,8 +152,6 @@ WITH AS a_over_b, (e.b_col ~ '.+_id$')::int - (e.a_col ~ '.+_id$')::int AS a_by_name FROM equated e - JOIN user_columns ca ON ca.id = e.a_id AND ca.name = e.a_col - JOIN user_columns cb ON cb.id = e.b_id AND cb.name = e.b_col LEFT JOIN index_keys ka ON ka.id = e.a_id AND ka.name = e.a_col LEFT JOIN index_keys kb ON kb.id = e.b_id AND kb.name = e.b_col WHERE e.a_id <> e.b_id @@ -180,84 +187,36 @@ WITH o.e->>'source_column' AS source_column FROM parsed, jsonb_array_elements(j->'outputs') AS o(e) ), - passed_keys AS ( - SELECT p.* - FROM passed p - JOIN user_columns c ON c.id = p.source_id AND c.name = p.source_column - WHERE p.source_column = 'id' OR EXISTS ( - SELECT 1 FROM index_keys k - WHERE k.id = p.source_id AND k.name = p.source_column - ) - ), - -- Passed columns that are not keys. A passed key references its source - -- directly, and propagating through it too would add every key it - -- reaches transitively, which grows with the square of a view stack's - -- depth (a stack of 300 views passing `id` gave 45,150 rows). - passed_references AS ( - SELECT p.* + passed_columns AS ( + SELECT + p.*, + p.source_column = 'id' OR k.id IS NOT NULL AS is_key FROM passed p - WHERE NOT EXISTS ( - SELECT 1 FROM passed_keys k - WHERE k.view_id = p.view_id AND k.output_column = p.output_column - ) - ), - directed AS ( - WITH MUTUALLY RECURSIVE - refs ( - view_id text, - source_id text, - source_column text, - target_id text, - target_column text - ) AS ( - SELECT view_id, source_id, source_column, target_id, target_column - FROM joins WHERE is_directed - UNION - SELECT view_id, view_id, output_column, source_id, source_column - FROM passed_keys - WHERE view_id <> source_id - UNION - SELECT p.view_id, p.view_id, p.output_column, r.target_id, r.target_column - FROM passed_references p - JOIN refs r ON r.source_id = p.source_id AND r.source_column = p.source_column - WHERE p.view_id <> r.target_id - UNION - SELECT p.view_id, p.source_id, p.source_column, r.target_id, r.target_column - FROM passed_references p - JOIN refs r ON r.source_id = p.view_id AND r.source_column = p.output_column - WHERE p.source_id <> r.target_id - ) - SELECT * FROM refs - ), - undirected AS ( - SELECT j.view_id, j.source_id, j.source_column, j.target_id, j.target_column - FROM joins j - WHERE NOT j.is_directed AND NOT EXISTS ( - SELECT 1 FROM directed d - WHERE ( - d.source_id = j.source_id AND d.source_column = j.source_column - AND d.target_id = j.target_id AND d.target_column = j.target_column - ) OR ( - d.source_id = j.target_id AND d.source_column = j.target_column - AND d.target_id = j.source_id AND d.target_column = j.source_column - ) - ) + LEFT JOIN index_keys k ON k.id = p.source_id AND k.name = p.source_column + WHERE p.view_id <> p.source_id ), + -- Direction depends only on the two columns, so a pair of columns is + -- directed in every view that joins it or in none, and appears once. evidence AS ( - SELECT DISTINCT *, true AS is_directed FROM directed + SELECT view_id, source_id, source_column, target_id, target_column, + 'join' AS kind, is_directed + FROM joins UNION ALL - SELECT DISTINCT *, false AS is_directed FROM undirected + SELECT view_id, view_id, output_column, source_id, source_column, + CASE WHEN is_key THEN 'key' ELSE 'same_values' END, true + FROM passed_columns ) SELECT source_id, source_column, target_id, target_column, + kind, is_directed, array_agg(view_id ORDER BY view_id) AS inferred_from -FROM evidence +FROM (SELECT DISTINCT * FROM evidence) WHERE source_id LIKE 'u%' AND target_id LIKE 'u%' -GROUP BY source_id, source_column, target_id, target_column, is_directed", +GROUP BY source_id, source_column, target_id, target_column, kind, is_directed", is_retained_metrics_object: false, access: vec![PUBLIC_SELECT], ontology: None, diff --git a/test/sqllogictest/autogenerated/mz_internal.slt b/test/sqllogictest/autogenerated/mz_internal.slt index 91c127bc0f056..35785b743c3bf 100644 --- a/test/sqllogictest/autogenerated/mz_internal.slt +++ b/test/sqllogictest/autogenerated/mz_internal.slt @@ -310,6 +310,7 @@ source_id text The␠ID␠of␠the␠relation␠holding␠the␠referencing␠ source_column text The␠referencing␠column. target_id text The␠ID␠of␠the␠relation␠holding␠the␠referenced␠column.␠Corresponds␠to␠`mz_objects.id`. target_column text The␠referenced␠column. +kind text `join`␠when␠a␠view␠joins␠the␠two␠columns,␠`key`␠when␠a␠view␠passes␠the␠target␠key␠through␠as␠the␠source␠column,␠and␠`same_values`␠when␠a␠view␠passes␠any␠other␠target␠column␠through␠as␠the␠source␠column. is_directed boolean Whether␠a␠key␠decides␠which␠side␠references␠the␠other.␠When␠false,␠the␠two␠columns␠are␠only␠known␠to␠be␠joined,␠and␠their␠order␠is␠arbitrary. inferred_from text[] The␠IDs␠of␠the␠views␠and␠materialized␠views␠whose␠definitions␠imply␠the␠relationship. diff --git a/test/sqllogictest/catalog_server_explain.slt b/test/sqllogictest/catalog_server_explain.slt index 09c593028143d..79aef15c5b9eb 100644 --- a/test/sqllogictest/catalog_server_explain.slt +++ b/test/sqllogictest/catalog_server_explain.slt @@ -4949,7 +4949,7 @@ mz_catalog.mz_columns: Project: #6, #0..=#3, #7, #4, #5 Map: null →Arrange (#0{schema_name}, #1{relation_name}) - →Constant (1944 rows) + →Constant (1945 rows) →Arrange (#1{schema_name}, #2{name}) →Fused with Child Map/Filter/Project Project: #6, #4, #3 @@ -6249,7 +6249,7 @@ mz_internal.mz_object_dependencies: Project: #4..=#6, #2 Filter: case when (#7{ref_kind} = "func") then (#3{object_type} = "8") else case when (#7{ref_kind} = "type") then (#3{object_type} = "7") else ((#3{object_type} != "7") AND (#3{object_type} != "8")) end end →Arrange (#0{object_schema}..=#2{object_type}) (#3{ref_schema}, #4{ref_name}) - →Constant (1102 rows) + →Constant (1101 rows) →Arrange (#1{schema_name}..=#3{object_type}) →Fused with Child Map/Filter/Project Project: #5, #4, #2, #3 @@ -8815,7 +8815,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_columns"; ---- Explained Query (fast path): - →Constant (1944 rows) + →Constant (1945 rows) Target cluster: mz_catalog_server @@ -10836,7 +10836,7 @@ Explained Query: Project: #3, #4 Filter: case when (#2{ref_kind} = "func") then (#5{object_type} = "8") else case when (#2{ref_kind} = "type") then (#5{object_type} = "7") else ((#5{object_type} != "7") AND (#5{object_type} != "8")) end end →Unarranged Raw Stream - →Constant (1102 rows) + →Constant (1101 rows) →Arrange (#1{schema_name}..=#3{object_type}) →Fused with Child Map/Filter/Project Project: #5, #4, #2, #3 diff --git a/test/sqllogictest/mz_catalog_server_index_accounting.slt b/test/sqllogictest/mz_catalog_server_index_accounting.slt index 086a065d822ac..86bb7a163f711 100644 --- a/test/sqllogictest/mz_catalog_server_index_accounting.slt +++ b/test/sqllogictest/mz_catalog_server_index_accounting.slt @@ -548,6 +548,7 @@ mz_indexes owner_id mz_indexes redacted_create_sql mz_inferred_relationships inferred_from mz_inferred_relationships is_directed +mz_inferred_relationships kind mz_inferred_relationships source_column mz_inferred_relationships source_id mz_inferred_relationships target_column diff --git a/test/sqllogictest/mz_inferred_relationships.slt b/test/sqllogictest/mz_inferred_relationships.slt index 35f4e2df07e15..8f8ee30ae9688 100644 --- a/test/sqllogictest/mz_inferred_relationships.slt +++ b/test/sqllogictest/mz_inferred_relationships.slt @@ -71,24 +71,27 @@ CREATE VIEW opaque AS UNION ALL SELECT a.item FROM auctions a JOIN (SELECT a.id FROM bids a) s ON s.id = a.id -query TTTTB -SELECT s.name, r.source_column, t.name, r.target_column, r.is_directed +query TTTTTB +SELECT r.kind, s.name, r.source_column, t.name, r.target_column, r.is_directed FROM mz_internal.mz_inferred_relationships r JOIN mz_objects s ON s.id = r.source_id JOIN mz_objects t ON t.id = r.target_id -ORDER BY 1, 2, 3, 4 +ORDER BY 1, 2, 3, 4, 5 ---- -auctions seller users id true -bids auction_id auctions id true -bids buyer users id true -org_spend org_id organizations id true -seller_performance seller_id users id true -users org_id accounts org_id false -users org_id organizations id true -winning_bids auction_id auctions id true -winning_bids bid_id bids id true -winning_bids buyer users id true -winning_bids seller users id true +join bids auction_id auctions id true +join users org_id accounts org_id false +join users org_id organizations id true +join winning_bids buyer users id true +join winning_bids seller users id true +key org_spend org_id organizations id true +key seller_performance seller_id users id true +key winning_bids auction_id auctions id true +key winning_bids bid_id bids id true +same_values org_spend name organizations name true +same_values user_accounts balance accounts balance true +same_values user_accounts name users name true +same_values winning_bids buyer bids buyer true +same_values winning_bids seller auctions seller true # Evidence names the views that imply each relationship. query TT @@ -97,9 +100,9 @@ FROM mz_internal.mz_inferred_relationships r JOIN mz_objects s ON s.id = r.source_id CROSS JOIN unnest(r.inferred_from) AS e(id) JOIN mz_objects v ON v.id = e.id -WHERE s.name = 'bids' AND r.source_column = 'buyer' +WHERE s.name = 'winning_bids' AND r.source_column = 'buyer' AND r.kind = 'join' ---- -buyer winning_bids +buyer org_spend # A column that alone keys an index is the referenced side. statement ok @@ -115,14 +118,14 @@ statement ok CREATE VIEW order_products AS SELECT p.name, o.quantity FROM order_lines o JOIN products p ON p.sku = o.sku -query TTTTB -SELECT s.name, r.source_column, t.name, r.target_column, r.is_directed +query TTTTTB +SELECT r.kind, s.name, r.source_column, t.name, r.target_column, r.is_directed FROM mz_internal.mz_inferred_relationships r JOIN mz_objects s ON s.id = r.source_id JOIN mz_objects t ON t.id = r.target_id WHERE s.name = 'order_lines' ---- -order_lines sku products sku true +join order_lines sku products sku true # Dropping the view retracts what it implied. statement ok From 9d45827693c73b248276b32539c01a9baef66b1d Mon Sep 17 00:00:00 2001 From: jubrad Date: Mon, 16 Nov 2026 21:28:22 -0600 Subject: [PATCH 3/4] catalog: add mz_mcp_relationships, and drop the inference flag Add mz_internal.mz_mcp_relationships, a builtin view that lists the relationships between relations the current role can read, shaped like an ontology table (table_name, columns, referenced_table, referenced_columns), so agents can find how to join two relations without one. It is on the restrict_to_user_objects allow-list, and like mz_mcp_data_products lists only relations the role holds SELECT on. Besides the join and key rows of mz_inferred_relationships, it lists derived references: a column holding the same values as a referencing column, through a chain of views passing it, references the same key, so fct_orders.customer_id references customers.id even when only an intermediate view joins them. The chains are walked on read, by pointer doubling over the same_values rows. Maintaining them in the materialized view instead measured 3 to 5.5 times its cost per replaced view; on read the view takes about 300 ms with 4,000 views. Also drop the enable_inferred_relationships flag. Builtins are created regardless of flags, so it gated only the parse function, not the cost. Co-Authored-By: Claude Opus 5.5 --- .../content/sql/system-catalog/mz_internal.md | 23 +++ misc/python/materialize/mzcompose/__init__.py | 3 - src/catalog/src/builtin.rs | 1 + .../src/builtin/mz_inferred_relationships.rs | 141 +++++++++++++++++- src/pgrepr-consts/src/oid.rs | 1 + src/sql/src/func.rs | 8 +- src/sql/src/rbac.rs | 3 + src/sql/src/session/vars/definitions.rs | 6 - src/sql/system-parameters.json | 9 -- .../autogenerated/mz_internal.slt | 11 ++ test/sqllogictest/catalog_server_explain.slt | 12 +- .../information_schema_tables.slt | 4 + .../mz_catalog_server_index_accounting.slt | 2 +- .../mz_inferred_relationships.slt | 56 +++++-- test/sqllogictest/oid.slt | 1 + 15 files changed, 236 insertions(+), 45 deletions(-) diff --git a/doc/user/content/sql/system-catalog/mz_internal.md b/doc/user/content/sql/system-catalog/mz_internal.md index ef97484741374..961554de70bbb 100644 --- a/doc/user/content/sql/system-catalog/mz_internal.md +++ b/doc/user/content/sql/system-catalog/mz_internal.md @@ -933,6 +933,29 @@ subsource or table and the corresponding upstream PostgreSQL table being ingeste | `schema_name` | [`text`] | The schema of the upstream table being ingested. | | `table_name` | [`text`] | The name of the upstream table being ingested. | +## `mz_mcp_relationships` + +The `mz_mcp_relationships` view lists the relationships between relations +that the current role can read, shaped like an +[ontology table](/transform-data/patterns/ontology/), so agents can look up +how to join two relations without one. It lists the `join` and `key` rows of +[`mz_inferred_relationships`](#mz_inferred_relationships), and `derived` +references: a column that holds the same values as a referencing column, +through a chain of views passing it, references the same key. + +The view lists only relations the role holds `SELECT` on, and sessions with +`restrict_to_user_objects` can read it. + + +| Field | Type | Meaning | +| -------------------- | -------------- | -------- | +| `table_name` | [`text`] | Fully qualified name of the relation holding the referencing columns. | +| `columns` | [`text array`] | The referencing columns. | +| `referenced_table` | [`text`] | Fully qualified name of the relation holding the referenced columns. | +| `referenced_columns` | [`text array`] | The referenced columns, paired by position with `columns`. | +| `kind` | [`text`] | `join` when a view joins the columns, `key` when a view passes the referenced key through, and `derived` when the referencing column holds the same values as a column that references the key. | +| `is_directed` | [`boolean`] | Whether a key decides which side references the other. When false, the columns are only known to be joined. | + ## `mz_mysql_source_tables` The `mz_mysql_source_tables` table contains the mapping between each Materialize diff --git a/misc/python/materialize/mzcompose/__init__.py b/misc/python/materialize/mzcompose/__init__.py index d876950786f1d..b576d064895bf 100644 --- a/misc/python/materialize/mzcompose/__init__.py +++ b/misc/python/materialize/mzcompose/__init__.py @@ -340,9 +340,6 @@ def get_variable_system_parameters( # On by default so CI exercises the jq function, which is off in # production while it earns trust. VariableSystemParameter("enable_jq", "true", ["true", "false"]), - VariableSystemParameter( - "enable_inferred_relationships", "true", ["true", "false"] - ), # On by default so CI exercises the columnar merge batcher, which is # off in production while it earns trust. VariableSystemParameter( diff --git a/src/catalog/src/builtin.rs b/src/catalog/src/builtin.rs index 475ab0821f42b..5dff7284a2d25 100644 --- a/src/catalog/src/builtin.rs +++ b/src/catalog/src/builtin.rs @@ -1548,6 +1548,7 @@ pub static BUILTINS_STATIC: LazyLock>> = LazyLock::ne Builtin::Connection(&MZ_ANALYTICS), Builtin::View(&MZ_INDEX_ADVICE), Builtin::View(&MZ_MCP_DATA_PRODUCTS), + Builtin::View(&MZ_MCP_RELATIONSHIPS), Builtin::View(&MZ_MCP_DATA_PRODUCT_DETAILS), Builtin::Table(&MZ_OBJECT_HYDRATION_HISTORY), Builtin::Table(&MZ_REPLICA_HYDRATION_HISTORY), diff --git a/src/catalog/src/builtin/mz_inferred_relationships.rs b/src/catalog/src/builtin/mz_inferred_relationships.rs index 5f50d08be6b01..517bbfc876c79 100644 --- a/src/catalog/src/builtin/mz_inferred_relationships.rs +++ b/src/catalog/src/builtin/mz_inferred_relationships.rs @@ -16,7 +16,7 @@ use mz_pgrepr::oid; use mz_repr::namespaces::MZ_INTERNAL_SCHEMA; use mz_repr::{RelationDesc, SqlScalarType}; -use super::{BuiltinIndex, BuiltinMaterializedView, PUBLIC_SELECT}; +use super::{BuiltinIndex, BuiltinMaterializedView, BuiltinView, PUBLIC_SELECT}; /// Relationships between user relations that their views' definitions imply, /// with no declared keys. @@ -231,3 +231,142 @@ pub const MZ_INFERRED_RELATIONSHIPS_IND: BuiltinIndex = BuiltinIndex { ON mz_internal.mz_inferred_relationships (source_id)", is_retained_metrics_object: false, }; + +/// The relationships between relations the session's role can read, shaped +/// like an ontology table (`/docs/transform-data/patterns/ontology/`), for +/// agents. +/// +/// Besides the `join` and `key` rows of `mz_inferred_relationships`, it lists +/// `derived` references: a column holding the same values as a referencing +/// column, through a chain of views passing it, references the same key. The +/// chains are walked here, on read, rather than maintained in +/// `mz_inferred_relationships`. Maintaining them was measured at 3 to 5.5 +/// times that view's cost per replaced view on a one-worker catalog server, +/// against about 150 ms per read here with 4,000 views. +/// +/// Rows are limited to relations the role holds SELECT on, so the view can be +/// read from a session with `restrict_to_user_objects` without describing +/// relations the role cannot see. +pub static MZ_MCP_RELATIONSHIPS: LazyLock = LazyLock::new(|| BuiltinView { + name: "mz_mcp_relationships", + schema: MZ_INTERNAL_SCHEMA, + oid: oid::VIEW_MZ_MCP_RELATIONSHIPS_OID, + desc: RelationDesc::builder() + .with_column("table_name", SqlScalarType::String.nullable(false)) + .with_column( + "columns", + SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false), + ) + .with_column("referenced_table", SqlScalarType::String.nullable(false)) + .with_column( + "referenced_columns", + SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false), + ) + .with_column("kind", SqlScalarType::String.nullable(false)) + .with_column("is_directed", SqlScalarType::Bool.nullable(false)) + .finish(), + column_comments: BTreeMap::from_iter([ + ( + "table_name", + "Fully qualified name of the relation holding the referencing columns.", + ), + ("columns", "The referencing columns."), + ( + "referenced_table", + "Fully qualified name of the relation holding the referenced columns.", + ), + ( + "referenced_columns", + "The referenced columns, paired by position with `columns`.", + ), + ( + "kind", + "`join` when a view joins the columns, `key` when a view passes the referenced key through, and `derived` when the referencing column holds the same values as a column that references the key.", + ), + ( + "is_directed", + "Whether a key decides which side references the other. When false, the columns are only known to be joined.", + ), + ]), + sql: r#" +WITH MUTUALLY RECURSIVE + -- Each passed-through column's root, by pointer doubling: a pointer jumps + -- to where the pointer it lands on points. + pointers (child_id text, child_column text, root_id text, root_column text) AS ( + SELECT + s.child_id, + s.child_column, + COALESCE(jump.root_id, up.target_id, s.at_id), + COALESCE(jump.root_column, up.target_column, s.at_column) + FROM ( + SELECT + e.source_id AS child_id, + e.source_column AS child_column, + COALESCE(p.root_id, e.target_id) AS at_id, + COALESCE(p.root_column, e.target_column) AS at_column + FROM mz_internal.mz_inferred_relationships e + LEFT JOIN pointers p + ON p.child_id = e.source_id AND p.child_column = e.source_column + WHERE e.kind = 'same_values' + ) s + LEFT JOIN pointers jump + ON jump.child_id = s.at_id AND jump.child_column = s.at_column + LEFT JOIN mz_internal.mz_inferred_relationships up + ON up.kind = 'same_values' + AND up.source_id = s.at_id AND up.source_column = s.at_column + ), + members (id text, name text, root_id text, root_column text) AS ( + SELECT child_id, child_column, root_id, root_column FROM pointers + UNION + SELECT root_id, root_column, root_id, root_column FROM pointers + ) +SELECT + src.qualified_name AS table_name, + ARRAY[r.source_column] AS columns, + tgt.qualified_name AS referenced_table, + ARRAY[r.target_column] AS referenced_columns, + r.kind, + r.is_directed +FROM ( + SELECT source_id, source_column, target_id, target_column, kind, is_directed + FROM mz_internal.mz_inferred_relationships + WHERE kind IN ('join', 'key') + UNION ALL + SELECT DISTINCT m2.id, m2.name, r.target_id, r.target_column, 'derived', true + FROM mz_internal.mz_inferred_relationships r + JOIN members m1 ON m1.id = r.source_id AND m1.name = r.source_column + JOIN members m2 ON m2.root_id = m1.root_id AND m2.root_column = m1.root_column + WHERE r.kind IN ('join', 'key') AND r.is_directed + AND NOT (m2.id = r.source_id AND m2.name = r.source_column) + AND m2.id <> r.target_id + AND NOT EXISTS ( + SELECT 1 FROM mz_internal.mz_inferred_relationships d + WHERE d.kind IN ('join', 'key') + AND d.source_id = m2.id AND d.source_column = m2.name + AND d.target_id = r.target_id AND d.target_column = r.target_column + ) +) r +JOIN ( + SELECT DISTINCT + o.id, + '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS qualified_name + FROM mz_internal.mz_show_my_object_privileges op + JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type + JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id + JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id + WHERE op.privilege_type = 'SELECT' +) src ON src.id = r.source_id +JOIN ( + SELECT DISTINCT + o.id, + '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS qualified_name + FROM mz_internal.mz_show_my_object_privileges op + JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type + JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id + JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id + WHERE op.privilege_type = 'SELECT' +) tgt ON tgt.id = r.target_id +"#, + access: vec![PUBLIC_SELECT], + ontology: None, +}); diff --git a/src/pgrepr-consts/src/oid.rs b/src/pgrepr-consts/src/oid.rs index 95fc0697bad10..35c0411038236 100644 --- a/src/pgrepr-consts/src/oid.rs +++ b/src/pgrepr-consts/src/oid.rs @@ -850,3 +850,4 @@ pub const VIEW_MZ_BUILTIN_INDEX_COLUMNS_OID: u32 = 17140; pub const FUNC_PARSE_CATALOG_VIEW_JOINS_OID: u32 = 17141; pub const MV_MZ_INFERRED_RELATIONSHIPS_OID: u32 = 17142; pub const INDEX_MZ_INFERRED_RELATIONSHIPS_IND_OID: u32 = 17143; +pub const VIEW_MZ_MCP_RELATIONSHIPS_OID: u32 = 17144; diff --git a/src/sql/src/func.rs b/src/sql/src/func.rs index 5b932c88284ed..a77593bdb76fa 100644 --- a/src/sql/src/func.rs +++ b/src/sql/src/func.rs @@ -5369,12 +5369,8 @@ pub static MZ_INTERNAL_BUILTINS: LazyLock> = LazyLo oid::FUNC_PARSE_CATALOG_PRIVILEGES_OID; }, "parse_catalog_view_joins" => Scalar { - params!(String) => Operation::unary(|ecx, create_sql| { - ecx.require_feature_flag(&vars::ENABLE_INFERRED_RELATIONSHIPS)?; - Ok(create_sql.call_unary(UnaryFunc::ParseCatalogViewJoins( - func::ParseCatalogViewJoins, - ))) - }) => Jsonb, oid::FUNC_PARSE_CATALOG_VIEW_JOINS_OID; + params!(String) => UnaryFunc::ParseCatalogViewJoins(func::ParseCatalogViewJoins) + => Jsonb, oid::FUNC_PARSE_CATALOG_VIEW_JOINS_OID; }, "parse_kafka_source_details" => Scalar { params!(String) => UnaryFunc::ParseKafkaSourceDetails( diff --git a/src/sql/src/rbac.rs b/src/sql/src/rbac.rs index 5f6014bb3cfc5..1ecf6144a83f8 100644 --- a/src/sql/src/rbac.rs +++ b/src/sql/src/rbac.rs @@ -113,6 +113,8 @@ pub static EMPTY_ITEM_USAGE: LazyLock> = LazyLock::new /// /// The `mz_mcp_data_product*` views are how the MCP agent endpoint /// discovers data products; blocking them defeats the isolation model. +/// `mz_mcp_relationships` is how it discovers joins between them, and like +/// them lists only relations the role holds privileges on. /// `mz_show_my_cluster_privileges` is referenced by those views to null the /// advertised cluster unless the role has USAGE on it (it uses /// `mz_session_role_memberships()` rather than a `has_cluster_privilege` @@ -123,6 +125,7 @@ static RESTRICT_TO_USER_OBJECTS_ALLOWED_OIDS: LazyLock> = LazyLock btreeset! { oid::VIEW_MZ_MCP_DATA_PRODUCTS_OID, oid::VIEW_MZ_MCP_DATA_PRODUCT_DETAILS_OID, + oid::VIEW_MZ_MCP_RELATIONSHIPS_OID, oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID, } }); diff --git a/src/sql/src/session/vars/definitions.rs b/src/sql/src/session/vars/definitions.rs index 669442b67573f..989fe6fa21666 100644 --- a/src/sql/src/session/vars/definitions.rs +++ b/src/sql/src/session/vars/definitions.rs @@ -1936,12 +1936,6 @@ feature_flags!( default: false, enable_for_item_parsing: true, }, - { - name: enable_inferred_relationships, - desc: "inferring relationships between relations from view definitions", - default: false, - enable_for_item_parsing: true, - }, { name: enable_envelope_debezium_in_subscribe, desc: "`ENVELOPE DEBEZIUM (KEY (..))`", diff --git a/src/sql/system-parameters.json b/src/sql/system-parameters.json index e7dd9894e5aa8..2472ad6571ab6 100644 --- a/src/sql/system-parameters.json +++ b/src/sql/system-parameters.json @@ -1183,15 +1183,6 @@ "userVisible": false, "dyncfg": false }, - { - "name": "enable_inferred_relationships", - "typeName": "boolean", - "default": "off", - "description": "Whether inferring relationships between relations from view definitions is allowed (Materialize).", - "scope": "environment", - "userVisible": false, - "dyncfg": false - }, { "name": "enable_internal_statement_logging", "typeName": "boolean", diff --git a/test/sqllogictest/autogenerated/mz_internal.slt b/test/sqllogictest/autogenerated/mz_internal.slt index 35785b743c3bf..78480848d37a6 100644 --- a/test/sqllogictest/autogenerated/mz_internal.slt +++ b/test/sqllogictest/autogenerated/mz_internal.slt @@ -474,6 +474,16 @@ id text The␠ID␠of␠the␠subsource␠or␠table.␠Corresponds␠to␠`mz schema_name text The␠schema␠of␠the␠upstream␠table␠being␠ingested. table_name text The␠name␠of␠the␠upstream␠table␠being␠ingested. +query TTT +SELECT name, type, comment FROM objects WHERE schema = 'mz_internal' AND object = 'mz_mcp_relationships' ORDER BY position +---- +table_name text Fully␠qualified␠name␠of␠the␠relation␠holding␠the␠referencing␠columns. +columns text[] The␠referencing␠columns. +referenced_table text Fully␠qualified␠name␠of␠the␠relation␠holding␠the␠referenced␠columns. +referenced_columns text[] The␠referenced␠columns,␠paired␠by␠position␠with␠`columns`. +kind text `join`␠when␠a␠view␠joins␠the␠columns,␠`key`␠when␠a␠view␠passes␠the␠referenced␠key␠through,␠and␠`derived`␠when␠the␠referencing␠column␠holds␠the␠same␠values␠as␠a␠column␠that␠references␠the␠key. +is_directed boolean Whether␠a␠key␠decides␠which␠side␠references␠the␠other.␠When␠false,␠the␠columns␠are␠only␠known␠to␠be␠joined. + query TTT SELECT name, type, comment FROM objects WHERE schema = 'mz_internal' AND object = 'mz_mysql_source_tables' ORDER BY position ---- @@ -871,6 +881,7 @@ mz_materialized_view_refresh_strategies mz_materialized_view_refreshes mz_mcp_data_product_details mz_mcp_data_products +mz_mcp_relationships mz_metric_sinks mz_mysql_source_tables mz_network_policies diff --git a/test/sqllogictest/catalog_server_explain.slt b/test/sqllogictest/catalog_server_explain.slt index 79aef15c5b9eb..fec558685288a 100644 --- a/test/sqllogictest/catalog_server_explain.slt +++ b/test/sqllogictest/catalog_server_explain.slt @@ -4949,7 +4949,7 @@ mz_catalog.mz_columns: Project: #6, #0..=#3, #7, #4, #5 Map: null →Arrange (#0{schema_name}, #1{relation_name}) - →Constant (1945 rows) + →Constant (1951 rows) →Arrange (#1{schema_name}, #2{name}) →Fused with Child Map/Filter/Project Project: #6, #4, #3 @@ -5762,7 +5762,7 @@ mz_catalog.mz_views: Project: #5, #0, #6, #1, #2, #8, #3, #4, #7 Map: "s1" →Arrange (#1{schema_name}, #2{name}) - →Constant (198 rows) + →Constant (199 rows) →Arrange (#0{schema_name}) (#0{schema_name}, #1{name}) →Fused with Child Map/Filter/Project Project: #5, #4, #6 @@ -6249,7 +6249,7 @@ mz_internal.mz_object_dependencies: Project: #4..=#6, #2 Filter: case when (#7{ref_kind} = "func") then (#3{object_type} = "8") else case when (#7{ref_kind} = "type") then (#3{object_type} = "7") else ((#3{object_type} != "7") AND (#3{object_type} != "8")) end end →Arrange (#0{object_schema}..=#2{object_type}) (#3{ref_schema}, #4{ref_name}) - →Constant (1101 rows) + →Constant (1107 rows) →Arrange (#1{schema_name}..=#3{object_type}) →Fused with Child Map/Filter/Project Project: #5, #4, #2, #3 @@ -8815,7 +8815,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_columns"; ---- Explained Query (fast path): - →Constant (1945 rows) + →Constant (1951 rows) Target cluster: mz_catalog_server @@ -8885,7 +8885,7 @@ query T multiline EXPLAIN SELECT * FROM "mz_internal"."mz_builtin_views"; ---- Explained Query (fast path): - →Constant (198 rows) + →Constant (199 rows) Target cluster: mz_catalog_server @@ -10836,7 +10836,7 @@ Explained Query: Project: #3, #4 Filter: case when (#2{ref_kind} = "func") then (#5{object_type} = "8") else case when (#2{ref_kind} = "type") then (#5{object_type} = "7") else ((#5{object_type} != "7") AND (#5{object_type} != "8")) end end →Unarranged Raw Stream - →Constant (1101 rows) + →Constant (1107 rows) →Arrange (#1{schema_name}..=#3{object_type}) →Fused with Child Map/Filter/Project Project: #5, #4, #2, #3 diff --git a/test/sqllogictest/information_schema_tables.slt b/test/sqllogictest/information_schema_tables.slt index 30ed7d5db19d7..0c228131dd1f7 100644 --- a/test/sqllogictest/information_schema_tables.slt +++ b/test/sqllogictest/information_schema_tables.slt @@ -481,6 +481,10 @@ mz_mcp_data_products VIEW materialize mz_internal +mz_mcp_relationships +VIEW +materialize +mz_internal mz_metric_sinks MATERIALIZED VIEW materialize diff --git a/test/sqllogictest/mz_catalog_server_index_accounting.slt b/test/sqllogictest/mz_catalog_server_index_accounting.slt index 86bb7a163f711..b08b507df07d8 100644 --- a/test/sqllogictest/mz_catalog_server_index_accounting.slt +++ b/test/sqllogictest/mz_catalog_server_index_accounting.slt @@ -86,7 +86,7 @@ mz_message_batch_counts_sent_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_ba mz_message_counts_received_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_counts_received_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_message_counts_received_raw"␠("channel_id",␠"from_worker_id",␠"to_worker_id") mz_message_counts_sent_raw_s2_primary_idx CREATE␠INDEX␠"mz_message_counts_sent_raw_s2_primary_idx"␠IN␠CLUSTER␠[s2]␠ON␠"mz_introspection"."mz_message_counts_sent_raw"␠("channel_id",␠"from_worker_id",␠"to_worker_id") mz_metric_sinks_ind CREATE␠INDEX␠"mz_metric_sinks_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s554␠AS␠"mz_internal"."mz_metric_sinks"]␠("id") -mz_notices_ind CREATE␠INDEX␠"mz_notices_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s854␠AS␠"mz_internal"."mz_notices"]␠("id") +mz_notices_ind CREATE␠INDEX␠"mz_notices_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s855␠AS␠"mz_internal"."mz_notices"]␠("id") mz_object_arrangement_size_history_object_ind CREATE␠INDEX␠"mz_object_arrangement_size_history_object_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s767␠AS␠"mz_internal"."mz_object_arrangement_size_history"]␠("object_id") mz_object_arrangement_size_history_ts_ind CREATE␠INDEX␠"mz_object_arrangement_size_history_ts_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s767␠AS␠"mz_internal"."mz_object_arrangement_size_history"]␠("collection_timestamp") mz_object_arrangement_sizes_ind CREATE␠INDEX␠"mz_object_arrangement_sizes_ind"␠IN␠CLUSTER␠[s2]␠ON␠[s765␠AS␠"mz_internal"."mz_object_arrangement_sizes"]␠("replica_id") diff --git a/test/sqllogictest/mz_inferred_relationships.slt b/test/sqllogictest/mz_inferred_relationships.slt index 8f8ee30ae9688..66f8c10bcb362 100644 --- a/test/sqllogictest/mz_inferred_relationships.slt +++ b/test/sqllogictest/mz_inferred_relationships.slt @@ -14,11 +14,6 @@ mode cockroach reset-server -simple conn=mz_system,user=mz_system -ALTER SYSTEM SET enable_inferred_relationships = on ----- -COMPLETE 0 - statement ok CREATE TABLE organizations (id int, name text) @@ -145,17 +140,52 @@ FROM mz_views WHERE name = 'seller_performance' ---- [{"column":"seller_id","source_column":"id","source_id":"u2"}] +# mz_mcp_relationships lists references shaped like an ontology table, +# including those derived through columns views pass through: +# winning_bids.buyer passes bids.buyer and joins users.id, so bids.buyer +# references users.id too. +query TTTTT +SELECT table_name, columns::text, referenced_table, referenced_columns::text, kind +FROM mz_internal.mz_mcp_relationships +WHERE kind = 'derived' +ORDER BY 1, 2 +---- +"materialize"."public"."auctions" {seller} "materialize"."public"."users" {id} derived +"materialize"."public"."bids" {buyer} "materialize"."public"."users" {id} derived + +# A session restricted to user objects reads it, and sees only the relations +# its role can read: here users and winning_bids, not bids or auctions. +simple conn=mz_system,user=mz_system +CREATE ROLE agent LOGIN +---- +COMPLETE 0 + simple conn=mz_system,user=mz_system -ALTER SYSTEM SET enable_inferred_relationships = off +GRANT USAGE ON SCHEMA materialize.public TO agent ---- COMPLETE 0 -query error inferring relationships between relations from view definitions is not available -SELECT mz_internal.parse_catalog_view_joins(create_sql) FROM mz_views +simple conn=mz_system,user=mz_system +GRANT SELECT ON materialize.public.users, materialize.public.winning_bids TO agent +---- +COMPLETE 0 + +simple conn=mz_system,user=mz_system +ALTER ROLE agent SET restrict_to_user_objects = true +---- +COMPLETE 0 + +simple conn=agent,user=agent +SELECT table_name, columns::text, referenced_table, referenced_columns::text, kind +FROM mz_internal.mz_mcp_relationships +ORDER BY 1, 2 +---- +"materialize"."public"."winning_bids",{buyer},"materialize"."public"."users",{id},join +"materialize"."public"."winning_bids",{seller},"materialize"."public"."users",{id},join +COMPLETE 2 -# The builtin is maintained regardless, it does not call the function at -# query time. -query B -SELECT count(*) > 0 FROM mz_internal.mz_inferred_relationships +simple conn=agent,user=agent +SELECT count(*) FROM mz_internal.mz_inferred_relationships ---- -true +db error: ERROR: access to system object mz_inferred_relationships is restricted +DETAIL: Access to system catalog objects is restricted for this role. Contact your administrator if you need access. diff --git a/test/sqllogictest/oid.slt b/test/sqllogictest/oid.slt index 9a0e7c7e7752b..60ea7cd3cd827 100644 --- a/test/sqllogictest/oid.slt +++ b/test/sqllogictest/oid.slt @@ -1270,3 +1270,4 @@ SELECT oid, name FROM mz_objects WHERE id LIKE 's%' AND oid < 20000 ORDER BY oid 17141 parse_catalog_view_joins 17142 mz_inferred_relationships 17143 mz_inferred_relationships_ind +17144 mz_mcp_relationships From f91233e30146e8530ff562988ba4d441fe7e82fd Mon Sep 17 00:00:00 2001 From: jubrad Date: Tue, 17 Nov 2026 11:46:44 -0600 Subject: [PATCH 4/4] catalog: rename the same_values relationship kind to passthrough A passed-through column is not a relationship. It is the link mz_mcp_relationships follows to derive references, so name it for what it records and document that agents should read mz_mcp_relationships. Co-Authored-By: Claude Opus 5.5 --- doc/user/content/sql/system-catalog/mz_internal.md | 11 ++++++----- .../src/builtin/mz_inferred_relationships.rs | 14 ++++++++------ test/sqllogictest/autogenerated/mz_internal.slt | 2 +- test/sqllogictest/mz_inferred_relationships.slt | 10 +++++----- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/doc/user/content/sql/system-catalog/mz_internal.md b/doc/user/content/sql/system-catalog/mz_internal.md index 961554de70bbb..72642e15a1392 100644 --- a/doc/user/content/sql/system-catalog/mz_internal.md +++ b/doc/user/content/sql/system-catalog/mz_internal.md @@ -547,11 +547,12 @@ declared keys. Each row comes from a single view's definition: `*_id`. A join that none of these settle is undirected. - A `key`: the view passes a key through unchanged, as in `SELECT o.id AS org_id`, so its output column references that key. -- `same_values`: the view passes any other column through unchanged. +- `passthrough`: the view passes any other column through unchanged. -Relationships across several views are the paths through these rows. A -`same_values` row describes the columns' domain, not their data: a view may -filter, so its input column can hold values that its output never shows. +A `passthrough` row is not a relationship. It says the two columns share a +domain, not their data: a view may filter, so its input column can hold +values that its output never shows. [`mz_mcp_relationships`](#mz_mcp_relationships) +follows these rows to derive references across views. | Field | Type | Meaning | @@ -560,7 +561,7 @@ filter, so its input column can hold values that its output never shows. | `source_column` | [`text`] | The referencing column. | | `target_id` | [`text`] | The ID of the relation holding the referenced column. Corresponds to [`mz_objects.id`](../mz_catalog/#mz_objects). | | `target_column` | [`text`] | The referenced column. | -| `kind` | [`text`] | `join` when a view joins the two columns, `key` when a view passes the target key through as the source column, and `same_values` when a view passes any other target column through as the source column. | +| `kind` | [`text`] | `join` when a view joins the two columns, `key` when a view passes the target key through as the source column, and `passthrough` when a view passes any other target column through as the source column, which relates nothing by itself. | | `is_directed` | [`boolean`] | Whether a key decides which side references the other. When false, the two columns are only known to be joined, and their order is arbitrary. | | `inferred_from` | [`text array`] | The IDs of the views and materialized views whose definitions imply the relationship. | diff --git a/src/catalog/src/builtin/mz_inferred_relationships.rs b/src/catalog/src/builtin/mz_inferred_relationships.rs index 517bbfc876c79..3d4a7e8a9f2be 100644 --- a/src/catalog/src/builtin/mz_inferred_relationships.rs +++ b/src/catalog/src/builtin/mz_inferred_relationships.rs @@ -30,8 +30,10 @@ use super::{BuiltinIndex, BuiltinMaterializedView, BuiltinView, PUBLIC_SELECT}; /// not named `*_id`. A join neither settles is undirected. /// - `key`: a view's output column that is an input key unchanged, which /// references that key. -/// - `same_values`: a view's output column that is any other input column -/// unchanged. +/// - `passthrough`: a view's output column that is any other input column +/// unchanged. The two share a domain, not necessarily data, since the view +/// may filter, so this is no relationship by itself. `mz_mcp_relationships` +/// follows these rows to derive references. /// /// Relationships across several views follow by chaining rows. Deriving them /// here was measured at about three times the maintenance cost of @@ -68,7 +70,7 @@ pub static MZ_INFERRED_RELATIONSHIPS: LazyLock = LazyLo ("target_column", "The referenced column."), ( "kind", - "`join` when a view joins the two columns, `key` when a view passes the target key through as the source column, and `same_values` when a view passes any other target column through as the source column.", + "`join` when a view joins the two columns, `key` when a view passes the target key through as the source column, and `passthrough` when a view passes any other target column through as the source column, which relates nothing by itself.", ), ( "is_directed", @@ -203,7 +205,7 @@ WITH FROM joins UNION ALL SELECT view_id, view_id, output_column, source_id, source_column, - CASE WHEN is_key THEN 'key' ELSE 'same_values' END, true + CASE WHEN is_key THEN 'key' ELSE 'passthrough' END, true FROM passed_columns ) SELECT @@ -307,12 +309,12 @@ WITH MUTUALLY RECURSIVE FROM mz_internal.mz_inferred_relationships e LEFT JOIN pointers p ON p.child_id = e.source_id AND p.child_column = e.source_column - WHERE e.kind = 'same_values' + WHERE e.kind = 'passthrough' ) s LEFT JOIN pointers jump ON jump.child_id = s.at_id AND jump.child_column = s.at_column LEFT JOIN mz_internal.mz_inferred_relationships up - ON up.kind = 'same_values' + ON up.kind = 'passthrough' AND up.source_id = s.at_id AND up.source_column = s.at_column ), members (id text, name text, root_id text, root_column text) AS ( diff --git a/test/sqllogictest/autogenerated/mz_internal.slt b/test/sqllogictest/autogenerated/mz_internal.slt index 78480848d37a6..33f2cb08e06c6 100644 --- a/test/sqllogictest/autogenerated/mz_internal.slt +++ b/test/sqllogictest/autogenerated/mz_internal.slt @@ -310,7 +310,7 @@ source_id text The␠ID␠of␠the␠relation␠holding␠the␠referencing␠ source_column text The␠referencing␠column. target_id text The␠ID␠of␠the␠relation␠holding␠the␠referenced␠column.␠Corresponds␠to␠`mz_objects.id`. target_column text The␠referenced␠column. -kind text `join`␠when␠a␠view␠joins␠the␠two␠columns,␠`key`␠when␠a␠view␠passes␠the␠target␠key␠through␠as␠the␠source␠column,␠and␠`same_values`␠when␠a␠view␠passes␠any␠other␠target␠column␠through␠as␠the␠source␠column. +kind text `join`␠when␠a␠view␠joins␠the␠two␠columns,␠`key`␠when␠a␠view␠passes␠the␠target␠key␠through␠as␠the␠source␠column,␠and␠`passthrough`␠when␠a␠view␠passes␠any␠other␠target␠column␠through␠as␠the␠source␠column,␠which␠relates␠nothing␠by␠itself. is_directed boolean Whether␠a␠key␠decides␠which␠side␠references␠the␠other.␠When␠false,␠the␠two␠columns␠are␠only␠known␠to␠be␠joined,␠and␠their␠order␠is␠arbitrary. inferred_from text[] The␠IDs␠of␠the␠views␠and␠materialized␠views␠whose␠definitions␠imply␠the␠relationship. diff --git a/test/sqllogictest/mz_inferred_relationships.slt b/test/sqllogictest/mz_inferred_relationships.slt index 66f8c10bcb362..925a34de42cd7 100644 --- a/test/sqllogictest/mz_inferred_relationships.slt +++ b/test/sqllogictest/mz_inferred_relationships.slt @@ -82,11 +82,11 @@ key org_spend org_id organizations id true key seller_performance seller_id users id true key winning_bids auction_id auctions id true key winning_bids bid_id bids id true -same_values org_spend name organizations name true -same_values user_accounts balance accounts balance true -same_values user_accounts name users name true -same_values winning_bids buyer bids buyer true -same_values winning_bids seller auctions seller true +passthrough org_spend name organizations name true +passthrough user_accounts balance accounts balance true +passthrough user_accounts name users name true +passthrough winning_bids buyer bids buyer true +passthrough winning_bids seller auctions seller true # Evidence names the views that imply each relationship. query TT