Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(database-sql): prefer the selected database for table names (#7615)
Wolf Mermelstein071eb17f8afb
diff --git a/apps/web/src/lib/core/database-sql/generated/types.ts b/apps/web/src/lib/core/database-sql/generated/types.tsindex c77e50b424..9c9e079a0b 100644--- a/apps/web/src/lib/core/database-sql/generated/types.ts+++ b/apps/web/src/lib/core/database-sql/generated/types.ts@@ -60,6 +60,8 @@ export type CardPosition = {export type Catalog = {/** The visible tables. */tables: Table[];+ /** The database whose tables win when an unqualified name matches several. */+ scope?: DatabaseId | null;};/**diff --git a/crates/database_sql/AGENTS.md b/crates/database_sql/AGENTS.mdindex e69fbca610..bfcb4d21fa 100644--- a/crates/database_sql/AGENTS.md+++ b/crates/database_sql/AGENTS.md@@ -56,6 +56,9 @@ uses the wasm build directly).- The grammar is the contract: a statement this crate rejects must never reach`databases`' ops API some other way.+- Preserve `Catalog.scope` through the browser wire boundary; it gives the selected+ database precedence for unqualified table names without hiding qualified joins.+## Related- Skill: `database-core` · Rules: `.agents/rules/rust/architecture.md`diff --git a/crates/database_sql/examples/repl.rs b/crates/database_sql/examples/repl.rsindex 6df16b9133..728a65fb35 100644--- a/crates/database_sql/examples/repl.rs+++ b/crates/database_sql/examples/repl.rs@@ -46,6 +46,7 @@ const RENEWAL: Uuid = Uuid::from_u128(0x34);fn catalog() -> Catalog {Catalog {+ scope: None,tables: vec![Table {id: TableId::from_uuid(DEALS),database_id: DatabaseId::from_uuid(CRM),diff --git a/crates/database_sql/fixtures/catalogs/scoped.json b/crates/database_sql/fixtures/catalogs/scoped.jsonindex 011e7d3f58..f3928e59b7 100644--- a/crates/database_sql/fixtures/catalogs/scoped.json+++ b/crates/database_sql/fixtures/catalogs/scoped.json@@ -1,5 +1,6 @@{"catalog": {+ "scope": "01990000-0000-7000-8000-0000000cdb01","tables": [{"columns": [diff --git a/crates/database_sql/src/catalog.rs b/crates/database_sql/src/catalog.rsindex f33c17b0eb..5c3c41dfd1 100644--- a/crates/database_sql/src/catalog.rs+++ b/crates/database_sql/src/catalog.rs@@ -24,6 +24,9 @@ pub use schema::{pub struct Catalog {/// The visible tables.pub tables: Vec<Table>,+ /// The database whose tables win when an unqualified name matches several.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub scope: Option<DatabaseId>,}/// One table and its columns, in display order.diff --git a/crates/database_sql/src/catalog/schema.rs b/crates/database_sql/src/catalog/schema.rsindex 62f3d0be07..a9704113ea 100644--- a/crates/database_sql/src/catalog/schema.rs+++ b/crates/database_sql/src/catalog/schema.rs@@ -142,10 +142,11 @@ impl ColumnSchema {}}-/// The catalog a statement run from `scope` names tables in. A table of-/// another database whose database and table names both match one of the-/// scoped database's, case-insensitively as the engine matches, is left out:-/// the scoped table wins instead of the statement being ambiguous.+/// The catalog a statement run from `scope` names tables in. Scoped tables+/// take precedence for unqualified names. A table of another database whose+/// database and table names both match one of the scoped database's,+/// case-insensitively as the engine matches, is left out: the scoped table+/// also wins when the statement qualifies that name.pub fn build(schema: &Schema, scope: Option<DatabaseId>) -> Catalog {let qualified = |database: &str, table: &str| (database.to_lowercase(), table.to_lowercase());let scoped: Vec<(String, String)> = schema@@ -194,5 +195,5 @@ pub fn build(schema: &Schema, scope: Option<DatabaseId>) -> Catalog {}).filter(|table| !scoped.contains(&qualified(&table.database, &table.name))),);- Catalog { tables }+ Catalog { tables, scope }}diff --git a/crates/database_sql/src/catalog/schema/test.rs b/crates/database_sql/src/catalog/schema/test.rsindex 2604d86056..6696bd6e02 100644--- a/crates/database_sql/src/catalog/schema/test.rs+++ b/crates/database_sql/src/catalog/schema/test.rs@@ -2,6 +2,8 @@//! browser's tests map a database detail onto each fixture's schema, so the//! two sides build the same catalog from the same databases.+mod scopes;+use serde_json::Value;use super::*;diff --git a/crates/database_sql/src/catalog/schema/test/scopes.rs b/crates/database_sql/src/catalog/schema/test/scopes.rsnew file mode 100644index 0000000000..a01add6624--- /dev/null+++ b/crates/database_sql/src/catalog/schema/test/scopes.rs@@ -0,0 +1,107 @@+//! A selected database takes precedence without hiding qualified tables.++use super::*;+use crate::resolve::{Query, ResolveError};+use crate::{CompileError, compile};++fn schema() -> Schema {+ let mut schema: Schema = serde_json::from_value(fixture("scoped")["schema"].clone()).unwrap();+ schema.databases[1].name = "Archive".into();+ schema.databases[1].tables[0].name = "Contacts".into();+ schema+}++#[test]+fn unqualified_reads_prefer_the_selected_database_after_a_wire_round_trip() {+ let schema = schema();+ for database in &schema.databases {+ let catalog = build(&schema, Some(database.id));+ let catalog = serde_json::from_value(serde_json::to_value(catalog).unwrap()).unwrap();+ let Query::Select(select) = compile(&catalog, "SELECT row_id FROM Contacts").unwrap()+ else {+ panic!("a select");+ };+ let expected = database+ .tables+ .iter()+ .find(|table| table.name == "Contacts")+ .unwrap();+ assert_eq!(select.relations[0].table, expected.id);+ }+}++#[test]+fn the_selected_database_wins_over_an_exact_spelling_in_another_database() {+ let mut schema = schema();+ schema.databases[1].tables[0].name = "contacts".into();+ let catalog = build(&schema, Some(schema.databases[1].id));+ let Query::Select(select) = compile(&catalog, "SELECT row_id FROM Contacts").unwrap() else {+ panic!("a select");+ };+ assert_eq!(select.relations[0].table, schema.databases[1].tables[0].id);+}++#[test]+fn unqualified_writes_prefer_the_selected_database() {+ let schema = schema();+ let catalog = build(&schema, Some(schema.databases[1].id));+ for sql in [+ "INSERT INTO Contacts (Email) VALUES ('[email protected]')",+ "UPDATE Contacts SET Email = '[email protected]' WHERE Email IS NOT NULL",+ "DELETE FROM Contacts WHERE Email IS NOT NULL",+ "ALTER TABLE Contacts ALTER COLUMN Email TYPE TEXT",+ ] {+ let table = match compile(&catalog, sql).unwrap() {+ Query::Insert(query) => query.table,+ Query::Update(query) => query.table,+ Query::Delete(query) => query.table,+ Query::AlterColumnType(query) => query.table,+ Query::Select(_) => panic!("a write"),+ };+ assert_eq!(table, schema.databases[1].tables[0].id, "{sql}");+ }+}++#[test]+fn qualified_joins_keep_both_databases_available() {+ let schema = schema();+ let catalog = build(&schema, Some(schema.databases[0].id));+ let Query::Select(select) = compile(+ &catalog,+ "SELECT a.row_id, b.row_id FROM CRM.Contacts a \+ JOIN Archive.Contacts b ON a.row_id = b.row_id",+ )+ .unwrap() else {+ panic!("a select");+ };+ assert_eq!(+ select+ .relations+ .iter()+ .map(|relation| relation.table)+ .collect::<Vec<_>>(),+ vec![+ schema.databases[0].tables[1].id,+ schema.databases[1].tables[0].id+ ]+ );+}++#[test]+fn unscoped_duplicates_remain_ambiguous() {+ let catalog = build(&schema(), None);+ assert!(matches!(+ compile(&catalog, "SELECT row_id FROM Contacts"),+ Err(CompileError::Resolve(ResolveError::AmbiguousTable { .. }))+ ));+}++#[test]+fn a_unique_name_outside_the_selected_database_still_resolves() {+ let schema = schema();+ let catalog = build(&schema, Some(schema.databases[0].id));+ let Query::Select(select) = compile(&catalog, "SELECT row_id FROM Leads").unwrap() else {+ panic!("a select");+ };+ assert_eq!(select.relations[0].table, schema.databases[1].tables[1].id);+}diff --git a/crates/database_sql/src/engine/test/transcripts.rs b/crates/database_sql/src/engine/test/transcripts.rsindex b8727ab120..0e9bd66969 100644--- a/crates/database_sql/src/engine/test/transcripts.rs+++ b/crates/database_sql/src/engine/test/transcripts.rs@@ -56,6 +56,7 @@ const ANA: RowId = RowId::from_uuid(Uuid::from_u128(0x01990000_0000_7000_8000_00/// the catalog from a database's detail.fn crm() -> Catalog {Catalog {+ scope: None,tables: vec![Table {id: DEALS,diff --git a/crates/database_sql/src/resolve/names.rs b/crates/database_sql/src/resolve/names.rsindex 963f811089..a8b0b127d5 100644--- a/crates/database_sql/src/resolve/names.rs+++ b/crates/database_sql/src/resolve/names.rs@@ -52,7 +52,7 @@ pub fn table<'catalog>(catalog: &'catalog Catalog,name: &TableName,) -> Result<&'catalog Table, ResolveError> {- let matches: Vec<&Table> = catalog+ let mut matches: Vec<&Table> = catalog.tables.iter().filter(|table| {@@ -63,6 +63,12 @@ pub fn table<'catalog>(.is_none_or(|database| same(&table.database, &database.0))}).collect();+ if name.database.is_none()+ && let Some(scope) = catalog.scope+ && matches.iter().any(|table| table.database_id == scope)+ {+ matches.retain(|table| table.database_id == scope);+ }// Names match case-insensitively, but when that is ambiguous the exact// spelling decides: `Test.Table 1` and `test.Table 1` are different tables.let exact: Vec<&Table> = matchesdiff --git a/crates/database_sql/src/resolve/test.rs b/crates/database_sql/src/resolve/test.rsindex 6dbcbb2e19..4bea4436dc 100644--- a/crates/database_sql/src/resolve/test.rs+++ b/crates/database_sql/src/resolve/test.rs@@ -226,6 +226,7 @@ fn star_expands_and_every_column_kind_types_its_literal() {assert_eq!(resolve(&Catalog {+ scope: None,tables: catalog().tables.into_iter().take(2).collect(),},parse(sql).unwrap()@@ -854,6 +855,7 @@ fn exact_case_resolves_a_case_insensitive_collision() {}],};let catalog = Catalog {+ scope: None,tables: vec![table(1, "Test"), table(2, "test")],};let Query::Select(select) = compile(&catalog, "SELECT * FROM test.\"Table 1\"").unwrap() else {diff --git a/crates/database_sql/src/test_support.rs b/crates/database_sql/src/test_support.rsindex 30d4a942cb..94d31df487 100644--- a/crates/database_sql/src/test_support.rs+++ b/crates/database_sql/src/test_support.rs@@ -38,6 +38,7 @@ pub const LOW: OptionId = OptionId::from_uuid(Uuid::from_u128(0x42));/// assigned and a deal linked, and the platform `macro.people`.pub fn catalog() -> Catalog {Catalog {+ scope: None,tables: vec![Table {id: DEALS,@@ -240,6 +241,7 @@ pub const FEATURE: OptionId = OptionId::from_uuid(Uuid::from_u128(0x75));/// and a query (which names definitions) can be told apart.pub fn issues_catalog() -> Catalog {Catalog {+ scope: None,tables: vec![Table {id: ISSUES,database_id: WORK,diff --git a/crates/databases/src/domain/service/storage/query.rs b/crates/databases/src/domain/service/storage/query.rsindex a8e6475fce..b51b2f2eee 100644--- a/crates/databases/src/domain/service/storage/query.rs+++ b/crates/databases/src/domain/service/storage/query.rs@@ -52,6 +52,7 @@ pub(super) fn rows(request: &StorageRowsQuery,) -> Result<Vec<RowId>, DatabaseError> {let catalog = Catalog {+ scope: None,tables: vec![engine_table(entry, "")],};let query = if request.row_ids.is_some() {diff --git a/docs/agent-guide/databases.md b/docs/agent-guide/databases.mdindex 6271800a3b..11cb9a090a 100644--- a/docs/agent-guide/databases.md+++ b/docs/agent-guide/databases.md@@ -368,6 +368,9 @@ not at all. New tables, columns and options carry ids the client mints, solater ops of the same batch can name them. Agents and MCP write SQL,which the same engine turns into those ops on the server, and their schematools send the same ops.+When databases share a table name, a selected database takes precedence for+unqualified table names. Database-qualified names still select that database;+without a selection, duplicate table names are ambiguous.Rows keep the table's order unless the view sorts them. After each of your ownedits the grid reads its rows again, and another viewer's edit reaches an opengrid or answer within a moment through the gateway's table-changed message; a