diff --git a/crates/barsql-sql/src/algebra.rs b/crates/barsql-sql/src/algebra.rs new file mode 100644 index 0000000..bfb565d --- /dev/null +++ b/crates/barsql-sql/src/algebra.rs @@ -0,0 +1,477 @@ +use std::cell::Cell; +use std::collections::HashMap; +use std::ops::Range; +use std::rc::Rc; + +use barsql_core::SqlDialect; + +use crate::select::{ + Alias, Cte, Expr, ExprKind, FromItem, Ident, JoinKind, ParseError, Query, Select, SelectItem, SetExpr, SetOp, + TableFactor, Top, parse_query, +}; + +// One operator of a query in relational algebra, with what it works on below it. A table has no symbol and no +// children. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AlgebraNode { + pub symbol: &'static str, + pub detail: String, + pub children: Vec, + // What a projection, a grouping or a sort lists, one by one, or the columns a rename names. + pub items: Vec, + // The bytes of the statement this operator comes from. + pub span: Option>, + // The table a leaf reads. + pub table: Option, + // How many rows a VALUES leaf has. + pub rows: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Item { + // The alias, else the expression as written. + pub label: String, + pub expr: String, + pub source: Source, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Source { + Column { qualifier: Option, name: String }, + // `*`, or `t.*`. + Wildcard(Option), + // A function's lowercased name. + Call(String), + Expr, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TableRef { + // As written, quotes and all. + pub name: String, + // Unquoted, with an empty schema for T-SQL's db..t. + pub parts: Vec, + pub alias: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AlgebraError { + // Not a lone SELECT, or a statement that doesn't return rows. + NotQuery, + // The byte where the statement stops making sense. + Syntax(usize), +} + +// A CTE in scope, with its tree once that's built. +#[derive(Clone)] +struct Named { + name: String, + columns: Vec, + node: Option>, + size: usize, +} + +type Ctes = HashMap; + +// Cap on nodes copied by inlining CTEs. +const MAX_INLINED: usize = 4000; + +impl AlgebraNode { + fn new(symbol: &'static str, detail: impl Into, children: Vec) -> Self { + Self { symbol, detail: detail.into(), children, items: vec![], span: None, table: None, rows: None } + } + + fn items(mut self, items: Vec) -> Self { + self.items = items; + self + } + + fn span(mut self, span: Option>) -> Self { + self.span = span; + self + } + + fn size(&self) -> usize { + 1 + self.children.iter().map(Self::size).sum::() + } +} + +fn list<'a>(texts: impl IntoIterator) -> String { + texts.into_iter().collect::>().join(", ") +} + +fn spans(spans: impl IntoIterator>) -> Option> { + spans.into_iter().reduce(|a, b| a.start.min(b.start)..a.end.max(b.end)) +} + +fn values(idents: &[Ident]) -> Vec { + idents.iter().map(|ident| ident.value.clone()).collect() +} + +// The query as a tree, from the tables at the leaves to the last operator at the root: ⋈ joins, σ filters, γ groups, +// π projects, δ removes duplicates, τ sorts. A CTE is inlined where it's used. +pub fn algebra(sql: &str, dialect: SqlDialect) -> Result { + let query = parse_query(sql, dialect).map_err(|error| match error { + ParseError::NotQuery => AlgebraError::NotQuery, + ParseError::Syntax { at, .. } => AlgebraError::Syntax(at), + })?; + Ok(Builder { sql, inlined: Cell::new(0) }.query(&query, &Ctes::new())) +} + +struct Builder<'a> { + sql: &'a str, + inlined: Cell, +} + +impl Builder<'_> { + fn query(&self, query: &Query, outer: &Ctes) -> AlgebraNode { + let mut ctes = outer.clone(); + let named = |cte: &Cte, node: Option| Named { + name: cte.name.value.clone(), + columns: values(&cte.columns), + size: node.as_ref().map_or(0, AlgebraNode::size), + node: node.map(Rc::new), + }; + // WITH RECURSIVE: every CTE is in scope from the start. + if query.recursive { + for cte in &query.ctes { + ctes.insert(cte.name.value.to_lowercase(), named(cte, None)); + } + } + for cte in &query.ctes { + let node = self.query(&cte.query, &ctes); + ctes.insert(cte.name.value.to_lowercase(), named(cte, Some(node))); + } + // A lone SELECT's TOP picks rows after the sort, as LIMIT does. + let (mut root, top) = match &query.body { + SetExpr::Select(select) => (self.select(select, &ctes), select.top.as_ref()), + body => (self.set_expr(body, &ctes), None), + }; + if !query.order_by.is_empty() { + let keys = &query.order_by; + let items = keys + .iter() + .map(|key| Item { label: key.text.clone(), ..item_of(&key.expr, key.text.clone()) }) + .collect(); + root = AlgebraNode::new("τ", list(keys.iter().map(|key| key.text.as_str())), vec![root]) + .items(items) + .span(spans(keys.iter().map(|key| key.span.clone()))); + } + if let Some(by) = &query.limit_by { + let offset = by.offset.as_ref().map_or(String::new(), |offset| format!(" OFFSET {}", offset.text)); + let detail = format!("{}{offset} BY {}", by.count.text, list(by.by.iter().map(|e| e.text.as_str()))); + let span = spans([&by.count].into_iter().chain(&by.offset).chain(&by.by).map(|e| e.span.clone())); + root = AlgebraNode::new("limit", detail, vec![root]).span(span); + } + if let Some(top) = top { + root = top_node(top, root); + } + if let Some(limit) = &query.limit { + let mut parts: Vec = limit + .count + .iter() + .map(|count| count.text.clone()) + .chain(limit.offset.iter().map(|offset| format!("OFFSET {}", offset.text))) + .collect(); + if limit.with_ties { + parts.push("WITH TIES".into()); + } + if !parts.is_empty() { + let span = spans(limit.count.iter().chain(&limit.offset).map(|e| e.span.clone())); + root = AlgebraNode::new("limit", parts.join(" "), vec![root]).span(span); + } + } + root + } + + fn set_expr(&self, body: &SetExpr, ctes: &Ctes) -> AlgebraNode { + match body { + SetExpr::Select(select) => { + let node = self.select(select, ctes); + match &select.top { + Some(top) => top_node(top, node), + None => node, + } + } + SetExpr::Query(query) => self.query(query, ctes), + SetExpr::SetOp { op, all, left, right, span } => { + let symbol = match op { + SetOp::Union => "∪", + SetOp::Intersect => "∩", + SetOp::Except => "−", + }; + let detail = if *all { "ALL" } else { "" }; + let children = vec![self.set_expr(left, ctes), self.set_expr(right, ctes)]; + AlgebraNode::new(symbol, detail, children).span(Some(span.clone())) + } + SetExpr::Values { rows, span } => { + let mut leaf = AlgebraNode::new("", "VALUES", vec![]).span(Some(span.clone())); + leaf.rows = Some(rows.len()); + leaf + } + } + } + + fn select(&self, select: &Select, ctes: &Ctes) -> AlgebraNode { + let mut root = match select.from.split_first() { + Some((first, rest)) => rest.iter().fold(self.joins(first, ctes), |left, item| { + let span = first.span.start..item.span.end; + AlgebraNode::new("×", "", vec![left, self.joins(item, ctes)]).span(Some(span)) + }), + None => AlgebraNode::new("", "()", vec![]).span(Some(select.span.clone())), + }; + for filter in [&select.prewhere, &select.filter].into_iter().flatten() { + root = selection(filter, root); + } + if let Some(group) = &select.group_by { + let mut detail = + if group.all { "ALL".to_string() } else { list(group.keys.iter().map(|k| k.text.as_str())) }; + for modifier in &group.modifiers { + detail += &format!(" WITH {modifier}"); + } + let items = group.keys.iter().map(|key| item_of(key, key.text.clone())).collect(); + root = AlgebraNode::new("γ", detail, vec![root]).items(items).span(Some(group.span.clone())); + } + if let Some(having) = &select.having { + root = selection(having, root); + } + let items = select.items.iter().map(select_item).collect(); + let span = spans(select.items.iter().map(|item| item.span.clone())); + root = AlgebraNode::new("π", list(select.items.iter().map(|item| item.text.as_str())), vec![root]) + .items(items) + .span(span); + if let Some(qualify) = &select.qualify { + root = selection(qualify, root); + } + if let Some(distinct) = &select.distinct { + let detail = match distinct.on.is_empty() { + true => String::new(), + false => format!("ON ({})", list(distinct.on.iter().map(|e| e.text.as_str()))), + }; + root = AlgebraNode::new("δ", detail, vec![root]).span(Some(distinct.span.clone())); + } + root + } + + fn joins(&self, item: &FromItem, ctes: &Ctes) -> AlgebraNode { + item.joins.iter().fold(self.factor(&item.factor, ctes), |left, join| { + let kind = match join.kind { + JoinKind::Inner => "", + JoinKind::Left => "LEFT", + JoinKind::Right => "RIGHT", + JoinKind::Full => "FULL", + JoinKind::Cross => "CROSS", + JoinKind::Semi => "SEMI", + JoinKind::Anti => "ANTI", + JoinKind::CrossApply => "CROSS APPLY", + JoinKind::OuterApply => "OUTER APPLY", + JoinKind::Array => "ARRAY", + JoinKind::LeftArray => "LEFT ARRAY", + }; + let on = match (&join.on, join.using.is_empty()) { + (Some(on), _) => format!("ON {}", on.text), + (None, false) => format!("USING ({})", list(join.using.iter().map(|c| c.value.as_str()))), + (None, true) if join.natural => "NATURAL".into(), + (None, true) => String::new(), + }; + let detail = [kind, on.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" "); + let right = self.factor(&join.factor, ctes); + AlgebraNode::new("⋈", detail, vec![left, right]).span(Some(join.span.clone())) + }) + } + + fn factor(&self, factor: &TableFactor, ctes: &Ctes) -> AlgebraNode { + let span = Some(factor.span()); + match factor { + TableFactor::Table { name, alias, .. } => { + let written = match (name.first(), name.last()) { + (Some(first), Some(last)) => self.sql[first.span.start..last.span.end].to_string(), + _ => String::new(), + }; + let cte = match name.as_slice() { + [one] => ctes.get(&one.value.to_lowercase()), + _ => None, + }; + if let Some(cte) = cte { + return self.inline(cte, &written, alias.as_ref(), span); + } + let mut leaf = leaf(&written, alias.as_ref(), span); + let alias = alias.as_ref().map(|alias| alias.name.value.clone()); + leaf.table = Some(TableRef { name: written, parts: values(name), alias }); + leaf + } + TableFactor::Derived { query, alias, .. } => renamed(self.query(query, ctes), alias.as_ref(), span), + TableFactor::Nested { item, alias, .. } => renamed(self.joins(item, ctes), alias.as_ref(), span), + TableFactor::Function { call, alias, .. } => leaf(&call.text, alias.as_ref(), span), + TableFactor::Arrays { text, .. } => AlgebraNode::new("", text.clone(), vec![]).span(span), + } + } + + // A CTE's tree renamed for this use, or a leaf while unbuilt. + fn inline(&self, cte: &Named, written: &str, alias: Option<&Alias>, span: Option>) -> AlgebraNode { + let inlined = self.inlined.get() + cte.size; + let Some(node) = cte.node.as_ref().filter(|_| inlined <= MAX_INLINED) else { + return leaf(written, alias, span); + }; + self.inlined.set(inlined); + let (name, columns) = match alias { + Some(alias) if !alias.columns.is_empty() => (alias.name.value.clone(), values(&alias.columns)), + Some(alias) => (alias.name.value.clone(), cte.columns.clone()), + None => (cte.name.clone(), cte.columns.clone()), + }; + rename(AlgebraNode::clone(node), name, columns, span) + } +} + +fn leaf(text: &str, alias: Option<&Alias>, span: Option>) -> AlgebraNode { + let detail = match alias { + Some(alias) => format!("{text} {}", alias.name.value), + None => text.to_string(), + }; + AlgebraNode::new("", detail, vec![]).span(span) +} + +fn top_node(top: &Top, input: AlgebraNode) -> AlgebraNode { + let mut detail = top.count.text.clone(); + if top.percent { + detail += " PERCENT"; + } + if top.with_ties { + detail += " WITH TIES"; + } + AlgebraNode::new("limit", detail, vec![input]).span(Some(top.span.clone())) +} + +fn selection(filter: &Expr, input: AlgebraNode) -> AlgebraNode { + AlgebraNode::new("σ", filter.text.clone(), vec![input]).items(conjuncts(filter)).span(Some(filter.span.clone())) +} + +// ρ names a subquery or CTE, and its columns. +fn rename(inner: AlgebraNode, name: String, columns: Vec, span: Option>) -> AlgebraNode { + let items = + columns.into_iter().map(|column| Item { label: column.clone(), expr: column, source: Source::Expr }).collect(); + AlgebraNode::new("ρ", name, vec![inner]).items(items).span(span) +} + +fn renamed(inner: AlgebraNode, alias: Option<&Alias>, span: Option>) -> AlgebraNode { + match alias { + Some(alias) => rename(inner, alias.name.value.clone(), values(&alias.columns), span), + None => inner, + } +} + +fn source_of(expr: &Expr) -> Source { + let joined = |parts: &[Ident]| { + (!parts.is_empty()).then(|| parts.iter().map(|part| part.value.as_str()).collect::>().join(".")) + }; + match &expr.kind { + ExprKind::Column { qualifier, name } => { + Source::Column { qualifier: joined(qualifier), name: name.value.clone() } + } + ExprKind::Wildcard(qualifier) => Source::Wildcard(joined(qualifier)), + ExprKind::Call { name, .. } => Source::Call(name.last().map(|n| n.value.to_lowercase()).unwrap_or_default()), + // `count(*) OVER w` or `sum(x)::int` types as the call. + ExprKind::Other => { + let name = expr.text.split_once('(').map_or("", |(name, _)| name.trim_end()); + match !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') { + true => Source::Call(name.to_lowercase()), + false => Source::Expr, + } + } + _ => Source::Expr, + } +} + +// The conditions a predicate requires together: `a AND b AND c` as three. +fn conjuncts(expr: &Expr) -> Vec { + match &expr.kind { + ExprKind::And(terms) => terms.iter().map(|term| item_of(term, term.text.clone())).collect(), + _ => vec![item_of(expr, expr.text.clone())], + } +} + +fn item_of(expr: &Expr, text: String) -> Item { + Item { label: expr.text.clone(), expr: text, source: source_of(expr) } +} + +fn select_item(item: &SelectItem) -> Item { + match &item.alias { + Some(alias) => Item { label: alias.value.clone(), ..item_of(&item.expr, item.expr.text.clone()) }, + None => item_of(&item.expr, item.expr.text.clone()), + } +} + +// A table's columns as (name, type) pairs. +pub type TableColumns = Vec<(String, String)>; + +// A column that leaves an operator. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Column { + // The table or alias it comes from, empty for a computed one. + pub table: String, + pub name: String, + pub data_type: String, +} + +// The columns `node` puts out; `lookup` gives a table's (name, type) pairs. +pub fn columns(node: &AlgebraNode, lookup: &dyn Fn(&TableRef) -> Option) -> Vec { + let child = |ix: usize| node.children.get(ix).map(|child| columns(child, lookup)).unwrap_or_default(); + match node.symbol { + "" => { + let Some(table) = &node.table else { return vec![] }; + let shown = table.alias.clone().or_else(|| table.parts.last().cloned()).unwrap_or_default(); + lookup(table) + .unwrap_or_default() + .into_iter() + .map(|(name, data_type)| Column { table: shown.clone(), name, data_type }) + .collect() + } + "ρ" => child(0) + .into_iter() + .enumerate() + .map(|(ix, column)| Column { + table: node.detail.clone(), + name: node.items.get(ix).map_or(column.name, |item| item.label.clone()), + data_type: column.data_type, + }) + .collect(), + "π" | "γ" => project(&node.items, &child(0)), + "⋈" | "×" => { + let mut out = child(0); + out.extend(child(1)); + out + } + _ => child(0), + } +} + +fn project(items: &[Item], input: &[Column]) -> Vec { + let mut out = vec![]; + for item in items { + match &item.source { + Source::Wildcard(qualifier) => out.extend( + input.iter().filter(|c| qualifier.as_ref().is_none_or(|q| c.table.eq_ignore_ascii_case(q))).cloned(), + ), + Source::Column { qualifier, name } => { + let found = input.iter().find(|c| { + c.name.eq_ignore_ascii_case(name) + && qualifier.as_ref().is_none_or(|q| c.table.eq_ignore_ascii_case(q)) + }); + // Without an alias it keeps the column's own name, not the `t.name` it was written as. + let shown = if item.label == item.expr { name.clone() } else { item.label.clone() }; + out.push(Column { + table: found.map(|c| c.table.clone()).unwrap_or_default(), + name: shown, + data_type: found.map(|c| c.data_type.clone()).unwrap_or_default(), + }); + } + Source::Call(_) | Source::Expr => { + let numeric = + matches!(&item.source, Source::Call(f) if matches!(f.as_str(), "count" | "sum" | "avg" | "round")); + let data_type = if numeric { "number" } else { "" }.into(); + out.push(Column { table: String::new(), name: item.label.clone(), data_type }); + } + } + } + out +} diff --git a/crates/barsql-sql/src/enum_values.rs b/crates/barsql-sql/src/enum_values.rs index 5eb8169..76a4596 100644 --- a/crates/barsql-sql/src/enum_values.rs +++ b/crates/barsql-sql/src/enum_values.rs @@ -304,7 +304,7 @@ impl<'t, 'a> Parser<'t, 'a> { } // The text of a string literal: 'it''s', N'x' and, where backslashes escape, 'it\'s'. -fn unquote(literal: &str, backslash_escapes: bool) -> String { +pub(crate) fn unquote(literal: &str, backslash_escapes: bool) -> String { let literal = literal.strip_prefix(['N', 'n']).unwrap_or(literal); let mut chars = literal.chars(); let Some(quote) = chars.next() else { return String::new() }; diff --git a/crates/barsql-sql/src/lang/tokens.rs b/crates/barsql-sql/src/lang/tokens.rs index f4a273b..94ee5fd 100644 --- a/crates/barsql-sql/src/lang/tokens.rs +++ b/crates/barsql-sql/src/lang/tokens.rs @@ -88,7 +88,10 @@ fn is_ident_char(c: u8, rules: &LexRules) -> bool { // $tag$ delimiters are ops, so dollar-quoted bodies stay tokenized and completion works inside them. pub fn tokenize<'a>(text: &'a str, driver: Option<&DriverType>) -> Vec> { - let rules = LexRules::for_driver(driver); + tokenize_with(text, LexRules::for_driver(driver)) +} + +pub fn tokenize_with(text: &str, rules: LexRules) -> Vec> { let b = text.as_bytes(); let len = b.len(); let mut tokens = Vec::new(); diff --git a/crates/barsql-sql/src/lib.rs b/crates/barsql-sql/src/lib.rs index dc01184..4b13539 100644 --- a/crates/barsql-sql/src/lib.rs +++ b/crates/barsql-sql/src/lib.rs @@ -1,3 +1,4 @@ +pub mod algebra; pub mod alter; pub mod ddl; pub mod dialect; @@ -13,6 +14,7 @@ mod plan_showplan; pub mod quote; pub mod readonly; pub mod schema_diff; +pub mod select; pub mod select_source; pub mod split; pub mod sql_text; @@ -20,6 +22,7 @@ pub mod structure; pub mod system_views; pub mod type_name; +pub use algebra::{AlgebraError, AlgebraNode, Column, Item, Source, TableColumns, TableRef, algebra, columns}; pub use dialect::Dialect; pub use explain::{ ExplainStrategy, PlanRequest, SHOWPLAN_COLUMN, ServerVersion, build_explain, build_explain_sql, diff --git a/crates/barsql-sql/src/select.rs b/crates/barsql-sql/src/select.rs new file mode 100644 index 0000000..51a6262 --- /dev/null +++ b/crates/barsql-sql/src/select.rs @@ -0,0 +1,1794 @@ +use std::ops::Range; + +use barsql_core::SqlDialect; + +use crate::enum_values::unquote; +use crate::lang::tokens::{Token, TokenKind, tokenize_with}; +use crate::lex::LexRules; +use crate::lex::prim::dollar_quoted_end; + +// A query read down to its clauses, its expressions kept as written and tagged by shape. + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Query { + pub ctes: Vec, + pub recursive: bool, + pub body: SetExpr, + pub order_by: Vec, + // ClickHouse's LIMIT n BY columns. + pub limit_by: Option, + pub limit: Option, + pub span: Range, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cte { + pub name: Ident, + pub columns: Vec, + pub query: Query, + pub span: Range, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SetExpr { + Select(Box { + let start = self.pos; + self.pos += 1; + let distinct_start = self.pos; + let mut distinct = None; + if self.eat_kw("distinct") || (self.dialect == SqlDialect::MySql && self.eat_kw("distinctrow")) { + let mut on = vec![]; + if self.kw("on") && self.punct_at(1, "(") { + self.pos += 2; + on = self.exprs(Ctx::Item)?; + self.expect_punct(")")?; + } + distinct = Some(Distinct { on, span: self.span(distinct_start) }); + } else { + self.eat_kw("all"); + } + let top = if self.dialect == SqlDialect::TSql && self.kw("top") { Some(self.top()?) } else { None }; + while self.dialect == SqlDialect::MySql && self.word().is_some_and(|w| MYSQL_MODIFIERS.contains(&w.as_str())) { + self.pos += 1; + } + let mut items = vec![]; + if !self.kw("from") { + items.push(self.select_item()?); + while self.eat_punct(",") { + items.push(self.select_item()?); + } + } + if self.eat_kw("into") { + self.skip_clause(); + } + let mut from = vec![]; + if self.eat_kw("from") { + from.push(self.joined()?); + while self.eat_punct(",") { + from.push(self.joined()?); + } + } + let prewhere = self.filter("prewhere")?; + let filter = self.filter("where")?; + let group_by = if self.eat_kws(&["group", "by"]) { Some(self.group_by()?) } else { None }; + let having = self.filter("having")?; + if self.eat_kw("window") { + loop { + self.ident("a window name")?; + self.expect_kw("as")?; + self.skip_parens()?; + if !self.eat_punct(",") { + break; + } + } + } + let qualify = self.filter("qualify")?; + Ok(Select { distinct, top, items, from, prewhere, filter, group_by, having, qualify, span: self.span(start) }) + } + + fn filter(&mut self, word: &str) -> Parsed> { + if self.eat_kw(word) { Ok(Some(self.expr(Ctx::Filter)?)) } else { Ok(None) } + } + + fn top(&mut self) -> Parsed { + let start = self.pos; + self.pos += 1; + let count = if self.eat_punct("(") { + let count = self.expr(Ctx::Item)?; + self.expect_punct(")")?; + count + } else { + if !self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Number | TokenKind::Ident)) { + return Err(self.error("a row count")); + } + self.pos += 1; + self.build(self.pos - 1..self.pos) + }; + let percent = self.eat_kw("percent"); + let with_ties = self.eat_kws(&["with", "ties"]); + Ok(Top { count, percent, with_ties, span: self.span(start) }) + } + + fn select_item(&mut self) -> Parsed { + let item = self.scan(Ctx::Item)?; + let (lo, hi) = (item.start, item.end); + if self.tokens[hi - 1].is_keyword("as") { + return Err(self.error("an alias")); + } + let tokens = &self.tokens; + let strings = matches!(self.dialect, SqlDialect::TSql | SqlDialect::MySql); + let named = |end: usize| { + let unit = end >= lo + 3 + && tokens[end - 3].is_keyword("interval") + && matches!(tokens[end - 2].kind, TokenKind::Number | TokenKind::String); + end >= lo + 2 && !unit && bare_alias(&tokens[end - 2], &tokens[end - 1], strings) + }; + let (expr, alias, bare) = if self.dialect == SqlDialect::TSql + && hi - lo >= 3 + && tokens[lo].is_ident_like() + && is_op(&tokens[lo + 1], "=") + { + (lo + 2..hi, Some(lo), false) + } else if hi - lo >= 3 + && tokens[hi - 2].is_keyword("as") + && (tokens[hi - 1].is_ident_like() || tokens[hi - 1].kind == TokenKind::String) + { + (lo..hi - 2, Some(hi - 1), false) + } else if named(hi) { + (lo..hi - 1, Some(hi - 1), true) + } else { + (lo..hi, None, false) + }; + // `a b c` is two items missing their comma, not `a b` named c. + if bare && named(expr.end) { + let at = tokens.get(expr.end).map_or(self.len, |t| t.start); + return Err(ParseError::Syntax { expected: "a comma", at }); + } + Ok(SelectItem { + expr: self.build(expr), + alias: alias.map(|ix| to_ident(&self.tokens[ix])), + text: self.text(item.clone()), + span: self.tokens[lo].start..self.tokens[hi - 1].end, + }) + } + + // SELECT INTO's target, or a closing clause that leaves the rows alone. + fn skip_clause(&mut self) { + self.skip_until(|this, token| token.is_punct(";") || this.stops(Ctx::Item)); + } + + // Skips to a top-level token `stop` takes, or a closer. + fn skip_until(&mut self, stop: impl Fn(&Self, &Token) -> bool) { + let mut depth = 0usize; + while let Some(token) = self.peek() { + if depth == 0 && (closes(token) || stop(self, token)) { + break; + } + depth = depth.saturating_add_signed(nesting(token)); + self.pos += 1; + } + } + + fn joined(&mut self) -> Parsed { + let start = self.pos; + let factor = self.factor()?; + let mut joins: Vec = vec![]; + loop { + if let Some((words, kind, natural)) = self.join_words() { + self.pos += words; + joins.push(self.join(kind, natural)?); + continue; + } + // `a JOIN b JOIN c ON … ON …`: the second ON joins `b JOIN c` as one table. + let open = joins.iter().rposition(Join::awaits_condition); + let Some(open) = open.filter(|_| self.kw("on") || self.kw("using")) else { break }; + let mut inner = joins.split_off(open); + let outer = inner.remove(0); + let span = outer.factor.span().start..inner.last().map_or(outer.span.end, |join| join.span.end); + let item = FromItem { factor: outer.factor, joins: inner, span: span.clone() }; + let factor = TableFactor::Nested { item: Box::new(item), alias: None, span }; + let (on, using) = self.condition()?; + let span = outer.span.start..self.tokens[self.pos - 1].end; + joins.push(Join { kind: outer.kind, natural: false, factor, on, using, span }); + } + Ok(FromItem { factor, joins, span: self.span(start) }) + } + + // How many join keywords start here, the kind of join and whether it's NATURAL. + fn join_words(&self) -> Option<(usize, JoinKind, bool)> { + // After an operator these words are columns, except JOIN. + if self.after_dot() || (self.prev().is_some_and(wants_operand) && !self.kw("join")) { + return None; + } + let mut words: Vec<&str> = vec![]; + for token in self.tokens.iter().skip(self.pos).take(6) { + if token.kind != TokenKind::Ident { + return None; + } + let word = token.lower.as_str(); + match word { + "join" => {} + "straight_join" if words.is_empty() => {} + "apply" if matches!(words.as_slice(), ["cross"] | ["outer"]) => {} + "natural" | "inner" | "left" | "right" | "full" | "outer" | "cross" | "semi" | "anti" | "any" + | "all" | "asof" | "global" | "array" => { + words.push(word); + continue; + } + "loop" | "hash" | "merge" | "remote" if !words.is_empty() => { + words.push(word); + continue; + } + _ => return None, + } + let has = |w: &str| words.contains(&w); + let kind = match () { + _ if word == "apply" && has("outer") => JoinKind::OuterApply, + _ if word == "apply" => JoinKind::CrossApply, + _ if has("array") && has("left") => JoinKind::LeftArray, + _ if has("array") => JoinKind::Array, + _ if has("semi") => JoinKind::Semi, + _ if has("anti") => JoinKind::Anti, + _ if has("left") => JoinKind::Left, + _ if has("right") => JoinKind::Right, + _ if has("full") => JoinKind::Full, + _ if has("cross") => JoinKind::Cross, + _ => JoinKind::Inner, + }; + return Some((words.len() + 1, kind, has("natural"))); + } + None + } + + fn join(&mut self, kind: JoinKind, natural: bool) -> Parsed { + let start = self.pos; + let factor = match kind { + JoinKind::Array | JoinKind::LeftArray => { + loop { + self.scan(Ctx::Join)?; + if !self.eat_punct(",") { + break; + } + } + TableFactor::Arrays { text: self.text(start..self.pos), span: self.span(start) } + } + _ => self.factor()?, + }; + let (on, using) = self.condition()?; + Ok(Join { kind, natural, factor, on, using, span: self.span(start) }) + } + + fn condition(&mut self) -> Parsed<(Option, Vec)> { + if self.eat_kw("on") { + return Ok((Some(self.expr(Ctx::Join)?), vec![])); + } + let using = match self.eat_kw("using") { + true if self.punct("(") => self.ident_list()?, + true => vec![self.ident("a column name")?], + false => vec![], + }; + Ok((None, using)) + } + + fn factor(&mut self) -> Parsed { + let start = self.pos; + let lateral = self.eat_kw("lateral"); + if self.punct("(") { + let derived = self.holds_query(self.pos) && !self.joins_inside(self.pos); + self.pos += 1; + if derived { + let query = Box::new(self.query()?); + self.expect_punct(")")?; + let alias = self.alias()?; + self.table_hints()?; + return Ok(TableFactor::Derived { lateral, query, alias, span: self.span(start) }); + } + let item = Box::new(self.joined()?); + self.expect_punct(")")?; + let alias = self.alias()?; + return Ok(TableFactor::Nested { item, alias, span: self.span(start) }); + } + if self.dialect == SqlDialect::Postgres && self.kw("only") && self.at(1).is_some_and(Token::is_ident_like) { + self.pos += 1; + } + if self.word().is_some_and(|w| NOT_NAMES.contains(&w.as_str())) { + return Err(self.error("a table name")); + } + let name_start = self.pos; + let mut name = vec![self.ident("a table name")?]; + while self.eat_punct(".") { + // T-SQL's db..table leaves out the schema. + if self.punct(".") { + let at = self.tokens[self.pos].start; + name.push(Ident { value: String::new(), quoted: false, span: at..at }); + self.pos += 1; + } + name.push(self.ident("a name")?); + } + if self.punct("(") { + self.skip_parens()?; + let call = self.build(name_start..self.pos); + self.eat_kws(&["with", "ordinality"]); + if self.dialect == SqlDialect::TSql && self.kw("with") && self.punct_at(1, "(") { + self.pos += 1; + self.skip_parens()?; + } + let alias = self.alias()?; + self.table_hints()?; + return Ok(TableFactor::Function { call, alias, span: self.span(start) }); + } + self.table_hints()?; + let alias = self.alias()?; + self.table_hints()?; + Ok(TableFactor::Table { name, alias, span: self.span(start) }) + } + + // Hints and samples after a table's name, which don't change the shape of its rows. + fn table_hints(&mut self) -> Parsed<()> { + while let Some(word) = self.word() { + match (self.dialect, word.as_str()) { + (SqlDialect::ClickHouse, "final") => self.pos += 1, + (SqlDialect::ClickHouse, "sample") => { + self.pos += 1; + self.sample_size(); + if self.eat_kw("offset") { + self.sample_size(); + } + } + (_, "tablesample") => { + self.pos += 1; + self.ident("a sampling method")?; + self.skip_parens()?; + if self.eat_kw("repeatable") { + self.skip_parens()?; + } + } + (SqlDialect::MySql, "partition") if self.punct_at(1, "(") => { + self.pos += 1; + self.skip_parens()?; + } + (SqlDialect::MySql, "use" | "force" | "ignore") if self.kw_at(1, "index") || self.kw_at(1, "key") => { + self.pos += 2; + if self.eat_kw("for") && !self.eat_kw("join") && !self.eat_kws(&["order", "by"]) { + self.eat_kws(&["group", "by"]); + } + self.skip_parens()?; + } + (SqlDialect::Sqlite, "indexed") if self.kw_at(1, "by") => { + self.pos += 2; + self.ident("an index name")?; + } + (SqlDialect::Sqlite, "not") if self.kw_at(1, "indexed") => self.pos += 2, + (SqlDialect::TSql, "with") if self.punct_at(1, "(") => { + self.pos += 1; + self.skip_parens()?; + } + (SqlDialect::TSql, "pivot" | "unpivot") if self.punct_at(1, "(") => { + self.pos += 1; + self.skip_parens()?; + self.alias()?; + } + (_, "for") if self.kw_at(1, "system_time") => { + self.pos += 2; + self.system_time()?; + } + _ => break, + } + } + Ok(()) + } + + fn sample_size(&mut self) { + while self.peek().is_some_and(|t| t.kind == TokenKind::Number || is_op(t, "/")) { + self.pos += 1; + } + } + + fn system_time(&mut self) -> Parsed<()> { + if self.eat_kws(&["as", "of"]) { + return self.skip_value(); + } + if self.eat_kw("from") || self.eat_kw("between") { + self.skip_value()?; + if !self.eat_kw("to") { + self.expect_kw("and")?; + } + return self.skip_value(); + } + if self.eat_kws(&["contained", "in"]) { + return self.skip_parens(); + } + self.expect_kw("all") + } + + fn skip_value(&mut self) -> Parsed<()> { + if self.peek().is_some_and(Token::is_ident_like) && self.punct_at(1, "(") { + self.pos += 1; + } + if self.punct("(") { + return self.skip_parens(); + } + if self.peek().is_none_or(|t| t.kind == TokenKind::Punct) { + return Err(self.error("a value")); + } + self.pos += 1; + Ok(()) + } + + fn alias(&mut self) -> Parsed> { + let explicit = self.eat_kw("as"); + let usable = self.peek().is_some_and(|t| match t.kind { + TokenKind::Quoted => true, + TokenKind::Ident => explicit || !RESERVED.contains(&t.lower.as_str()), + _ => false, + }); + if !usable { + return if explicit { Err(self.error("an alias")) } else { Ok(None) }; + } + let name = self.ident("an alias")?; + let columns = if self.punct("(") { self.ident_list()? } else { vec![] }; + Ok(Some(Alias { name, columns })) + } + + fn group_by(&mut self) -> Parsed { + let start = self.pos; + let all = self.kw("all") + && self.at(1).is_none_or(|t| match t.kind { + TokenKind::Punct => t.text == ";" || t.text == ")", + TokenKind::Ident => matches!( + t.lower.as_str(), + "having" + | "order" + | "limit" + | "window" + | "qualify" + | "union" + | "intersect" + | "except" + | "with" + | "settings" + | "format" + | "offset" + | "fetch" + ), + _ => false, + }); + let keys = if all { + self.pos += 1; + vec![] + } else { + if !self.eat_kw("distinct") { + self.eat_kw("all"); + } + self.exprs(Ctx::Group)? + }; + let mut modifiers = vec![]; + while self.kw("with") && ["rollup", "cube", "totals"].iter().any(|w| self.kw_at(1, w)) { + modifiers.push(self.at(1).map(|t| t.text.to_uppercase()).unwrap_or_default()); + self.pos += 2; + } + Ok(GroupBy { keys, all, modifiers, span: self.span(start) }) + } + + fn order_keys(&mut self) -> Parsed> { + let mut keys = vec![]; + loop { + let start = self.pos; + let expr = self.expr(Ctx::Order)?; + let desc = self.eat_kw("desc"); + if !desc { + self.eat_kw("asc"); + } + if self.kw("nulls") && (self.kw_at(1, "first") || self.kw_at(1, "last")) { + self.pos += 2; + } + if self.eat_kws(&["with", "fill"]) { + while self.eat_kw("from") || self.eat_kw("to") || self.eat_kw("step") { + self.scan(Ctx::Limit)?; + } + } + keys.push(OrderKey { expr, desc, text: self.text(start..self.pos), span: self.span(start) }); + if !self.eat_punct(",") { + return Ok(keys); + } + } + } + + fn tail(&mut self, tail: &mut Tail) -> Parsed<()> { + loop { + if self.eat_kws(&["order", "by"]) { + tail.order_by = self.order_keys()?; + } else if self.eat_kw("limit") { + if self.eat_kw("all") { + continue; + } + let first = self.expr(Ctx::Limit)?; + let (mut offset, count) = + if self.eat_punct(",") { (Some(first), self.expr(Ctx::Limit)?) } else { (None, first) }; + if offset.is_none() && self.eat_kw("offset") { + offset = Some(self.expr(Ctx::Limit)?); + } + if self.eat_kw("by") { + tail.limit_by = Some(LimitBy { count, offset, by: self.exprs(Ctx::Item)? }); + continue; + } + let limit = tail.limit.get_or_insert_with(Limit::default); + limit.count = Some(count); + if offset.is_some() { + limit.offset = offset; + } + limit.with_ties |= self.eat_kws(&["with", "ties"]); + } else if self.eat_kw("offset") { + let offset = self.expr(Ctx::Limit)?; + if !self.eat_kw("rows") { + self.eat_kw("row"); + } + tail.limit.get_or_insert_with(Limit::default).offset = Some(offset); + } else if self.eat_kw("fetch") { + if !self.eat_kw("first") && !self.eat_kw("next") { + return Err(self.error("FIRST or NEXT")); + } + let count = if self.kw("row") || self.kw("rows") { + let word = &self.tokens[self.pos - 1]; + Expr { text: "1".into(), kind: ExprKind::Value, span: word.start..word.end } + } else { + self.expr(Ctx::Limit)? + }; + if !self.eat_kw("rows") && !self.eat_kw("row") { + return Err(self.error("ROWS")); + } + let with_ties = self.eat_kws(&["with", "ties"]); + if !with_ties && !self.eat_kw("only") { + return Err(self.error("ONLY")); + } + let limit = tail.limit.get_or_insert_with(Limit::default); + limit.count = Some(count); + limit.with_ties = with_ties; + } else if self + .word() + .is_some_and(|w| matches!(w.as_str(), "for" | "lock" | "settings" | "format" | "option" | "into")) + && self.stops(Ctx::Item) + { + self.pos += 1; + self.skip_clause(); + } else { + return Ok(()); + } + } + } + + fn exprs(&mut self, ctx: Ctx) -> Parsed> { + let mut out = vec![self.expr(ctx)?]; + while self.eat_punct(",") { + out.push(self.expr(ctx)?); + } + Ok(out) + } + + fn expr(&mut self, ctx: Ctx) -> Parsed { + let range = self.scan(ctx)?; + Ok(self.build(range)) + } + + // Whether the word here ends the expression being read. + fn stops(&self, ctx: Ctx) -> bool { + let Some(word) = self.peek().filter(|t| t.kind == TokenKind::Ident).map(|t| t.lower.as_str()) else { + return false; + }; + let next = |w: &str| self.kw_at(1, w); + let clickhouse = self.dialect == SqlDialect::ClickHouse; + // ClickHouse's `* EXCEPT (…)` belongs to its item. + if self.after_dot() || (clickhouse && word == "except" && self.prev().is_some_and(|t| is_op(t, "*"))) { + return false; + } + let clause = match word { + "where" | "having" | "order" | "limit" | "offset" | "fetch" | "union" | "intersect" | "except" | "into" => { + true + } + "from" => !(self.prev_kw(1, "distinct") && (self.prev_kw(2, "is") || self.prev_kw(2, "not"))), + "group" => !self.prev_kw(1, "within"), + "window" => self.at(1).is_some_and(Token::is_ident_like) && self.kw_at(2, "as"), + "for" => ["update", "share", "no", "key", "xml", "json", "browse"].into_iter().any(next), + "lock" => next("in"), + "prewhere" | "qualify" | "settings" => clickhouse, + "format" => clickhouse && !self.punct_at(1, "("), + "option" => self.dialect == SqlDialect::TSql && self.punct_at(1, "("), + _ => false, + }; + clause + || match ctx { + Ctx::Join => word == "on" || self.join_words().is_some(), + Ctx::Group => word == "with" && ["rollup", "cube", "totals"].into_iter().any(next), + Ctx::Order => { + matches!(word, "asc" | "desc") + || (word == "nulls" && (next("first") || next("last"))) + || (word == "with" && next("fill")) + } + Ctx::Limit => { + matches!(word, "row" | "rows" | "by" | "only" | "percent") || (word == "with" && next("ties")) + } + Ctx::Item | Ctx::Filter => false, + } + } + + // The tokens of one expression, from here to where `ctx` says it ends. + fn scan(&mut self, ctx: Ctx) -> Parsed> { + let start = self.pos; + let (mut depth, mut cases) = (0usize, 0usize); + while let Some(token) = self.peek() { + if depth == 0 && (closes(token) || token.is_punct(";")) { + break; + } + // `SELECT format FROM t`: a clause word that starts an expression is a name. + let soft = self.pos == start && SOFT.contains(&token.lower.as_str()); + if depth == 0 && cases == 0 && (token.is_punct(",") || (!soft && self.stops(ctx))) { + break; + } + depth = depth.saturating_add_signed(nesting(token)); + cases = cases.saturating_add_signed(case_nesting(token)); + self.pos += 1; + } + if depth > 0 { + return Err(self.error(")")); + } + if cases > 0 { + return Err(self.error("END")); + } + let dangling = self.pos > start && { + let last = &self.tokens[self.pos - 1]; + last.is_punct(".") || wants_operand(last) || TRAILING.contains(&last.lower.as_str()) + }; + if self.pos == start || dangling { + return Err(self.error("an expression")); + } + Ok(start..self.pos) + } + + fn build(&self, range: Range) -> Expr { + let span = self.tokens[range.start].start..self.tokens[range.end - 1].end; + Expr { text: self.text(range.clone()), kind: self.classify(range), span } + } + + // A space wherever the source had space or a comment. + fn text(&self, range: Range) -> String { + let mut out = String::new(); + for ix in range.clone() { + if ix > range.start && self.tokens[ix - 1].end < self.tokens[ix].start { + out.push(' '); + } + out.push_str(self.tokens[ix].text); + } + out + } + + fn classify(&self, range: Range) -> ExprKind { + let (mut depth, mut cases, mut betweens) = (0usize, 0usize, 0usize); + let (mut ands, mut compares, mut or) = (vec![], vec![], false); + let mut ix = range.start; + while ix < range.end { + let token = &self.tokens[ix]; + if depth == 0 && cases == 0 { + if let Some((len, op)) = self.compare_op(ix, range.end) { + compares.push((ix, len, op)); + ix += len; + continue; + } + match token.lower.as_str() { + "or" | "xor" => or = true, + "between" => betweens += 1, + "and" if betweens > 0 => betweens -= 1, + "and" => ands.push(ix), + _ => {} + } + } + depth = depth.saturating_add_signed(nesting(token)); + cases = cases.saturating_add_signed(case_nesting(token)); + ix += self.op_len(ix, range.end); + } + if or { + return ExprKind::Other; + } + if !ands.is_empty() { + let mut terms = vec![]; + let mut from = range.start; + for end in ands.into_iter().chain([range.end]) { + if from == end { + return ExprKind::Other; + } + terms.push(self.build(from..end)); + from = end + 1; + } + return ExprKind::And(terms); + } + if let [(at, len, op)] = compares.as_slice() + && *at > range.start + && at + len < range.end + && !self.tokens[range.start].is_keyword("not") + { + let left = Box::new(self.build(range.start..*at)); + let right = Box::new(self.build(at + len..range.end)); + return ExprKind::Compare { left, op: op.clone(), right }; + } + if let Some(kind) = self.dotted(range.clone()) { + return kind; + } + if is_value(&self.tokens[range.clone()]) { + return ExprKind::Value; + } + self.call(range).unwrap_or(ExprKind::Other) + } + + // How many tokens the operator at `ix` spans, so `->>` reads as one. + fn op_len(&self, ix: usize, end: usize) -> usize { + let mut len = 0; + while ix + len < end { + let token = &self.tokens[ix + len]; + let touching = len == 0 || self.tokens[ix + len - 1].end == token.start; + if token.kind != TokenKind::Op || opens(token) || closes(token) || !touching { + break; + } + len += 1; + } + len.max(1) + } + + fn compare_op(&self, ix: usize, end: usize) -> Option<(usize, String)> { + let token = &self.tokens[ix]; + if token.kind == TokenKind::Op { + let mut len = self.op_len(ix, end); + let mut lexeme: String = self.tokens[ix..ix + len].iter().map(|t| t.text).collect(); + // A sign after the operator belongs to the number: `a=-1`. + while len > 1 && lexeme.ends_with(['-', '+']) && !COMPARE.contains(&lexeme.as_str()) { + lexeme.pop(); + len -= 1; + } + return COMPARE.contains(&lexeme.as_str()).then_some((len, lexeme)); + } + let word = |ahead: usize| { + self.tokens[..end].get(ix + ahead).filter(|t| t.kind == TokenKind::Ident).map(|t| t.lower.as_str()) + }; + let matcher = |w: &str| matches!(w, "like" | "ilike" | "glob" | "regexp" | "rlike" | "in"); + let (len, op) = match (word(0)?, word(1)) { + ("is", Some("not")) if word(2) == Some("distinct") && word(3) == Some("from") => { + (4, "IS NOT DISTINCT FROM".to_string()) + } + ("is", Some("distinct")) if word(2) == Some("from") => (3, "IS DISTINCT FROM".to_string()), + ("is", Some("not")) => (2, "IS NOT".to_string()), + ("is", _) => (1, "IS".to_string()), + ("not", Some("similar")) if word(2) == Some("to") => (3, "NOT SIMILAR TO".to_string()), + ("similar", Some("to")) => (2, "SIMILAR TO".to_string()), + ("not", Some(w)) if matcher(w) => (2, format!("NOT {}", w.to_uppercase())), + (w, _) if matcher(w) => (1, w.to_uppercase()), + _ => return None, + }; + Some((len, op)) + } + + // `a`, `s.t.a`, `*` or `t.*`. + fn dotted(&self, range: Range) -> Option { + let mut parts = vec![]; + let mut ix = range.start; + loop { + let token = &self.tokens[ix]; + let modified = self.dialect == SqlDialect::ClickHouse + && self.tokens[..range.end] + .get(ix + 1) + .is_some_and(|t| matches!(t.lower.as_str(), "except" | "replace" | "apply")); + if is_op(token, "*") && (ix + 1 == range.end || modified) { + return Some(ExprKind::Wildcard(parts)); + } + if !token.is_ident_like() { + return None; + } + parts.push(to_ident(token)); + ix += 1; + if ix == range.end { + break; + } + if !self.tokens[ix].is_punct(".") || ix + 1 == range.end { + return None; + } + ix += 1; + } + let name = parts.pop()?; + let value = !name.quoted + && (VALUE_WORDS.contains(&name.value.to_ascii_lowercase().as_str()) || name.value.starts_with('@')); + (!value || !parts.is_empty()).then_some(ExprKind::Column { qualifier: parts, name }) + } + + fn call(&self, range: Range) -> Option { + let mut name = vec![]; + let mut ix = range.start; + loop { + let token = self.tokens[..range.end].get(ix).filter(|t| t.is_ident_like())?; + name.push(to_ident(token)); + ix += 1; + if ix + 1 < range.end && self.tokens[ix].is_punct(".") { + ix += 1; + } else { + break; + } + } + let keyword = |ident: &Ident| !ident.quoted && NOT_CALLS.contains(&ident.value.to_ascii_lowercase().as_str()); + if ix >= range.end || !self.tokens[ix].is_punct("(") || self.close_of(ix) != Some(range.end - 1) { + return None; + } + if name.len() == 1 && keyword(&name[0]) { + return None; + } + let (mut args, mut from, mut depth) = (vec![], ix + 1, 0usize); + for at in ix + 1..range.end - 1 { + let token = &self.tokens[at]; + let step = nesting(token) + case_nesting(token); + depth = depth.saturating_add_signed(step); + if step == 0 && depth == 0 && token.is_punct(",") { + if from < at { + args.push(self.build(from..at)); + } + from = at + 1; + } + } + if from < range.end - 1 { + args.push(self.build(from..range.end - 1)); + } + Some(ExprKind::Call { name, args }) + } +} diff --git a/crates/barsql-sql/tests/algebra.rs b/crates/barsql-sql/tests/algebra.rs new file mode 100644 index 0000000..2cf1d68 --- /dev/null +++ b/crates/barsql-sql/tests/algebra.rs @@ -0,0 +1,181 @@ +use barsql_core::SqlDialect; +use barsql_sql::{AlgebraError, AlgebraNode, TableRef, algebra, columns}; + +fn show(node: &AlgebraNode) -> String { + let head = + [node.symbol, node.detail.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" "); + match node.children.is_empty() { + true => head, + false => format!("{head}({})", node.children.iter().map(show).collect::>().join(", ")), + } +} + +fn tree(sql: &str) -> String { + show(&algebra(sql, SqlDialect::Postgres).unwrap()) +} + +#[test] +fn join_filter_group_sort_limit() { + assert_eq!( + tree( + "SELECT u.name, count(*) FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE u.active GROUP BY u.name HAVING count(*) > 1 ORDER BY 2 DESC LIMIT 5 OFFSET 10" + ), + "limit 5 OFFSET 10(τ 2 DESC(π u.name, count(*)(σ count(*) > 1(γ u.name(σ u.active(⋈ LEFT ON o.user_id = u.id(users u, orders o)))))))" + ); +} + +#[test] +fn cte_is_inlined_and_set_operations_branch() { + assert_eq!( + tree("WITH a AS (SELECT id FROM t) SELECT id FROM a UNION ALL SELECT id FROM b"), + "∪ ALL(π id(ρ a(π id(t))), π id(b))" + ); +} + +#[test] +fn subquery_alias_and_distinct() { + assert_eq!(tree("SELECT DISTINCT x FROM (SELECT 1 AS x) s, t"), "δ(π x(×(ρ s(π 1 AS x(())), t)))"); +} + +#[test] +fn rejects_what_is_not_a_query() { + assert_eq!(algebra("DELETE FROM t", SqlDialect::Sqlite), Err(AlgebraError::NotQuery)); + assert_eq!(algebra("SELECT 1; SELECT 2", SqlDialect::Sqlite), Err(AlgebraError::NotQuery)); + assert_eq!(algebra("SELEC 1", SqlDialect::Sqlite), Err(AlgebraError::Syntax(0))); +} + +fn find<'a>(node: &'a AlgebraNode, symbol: &str) -> &'a AlgebraNode { + fn walk<'a>(node: &'a AlgebraNode, symbol: &str) -> Option<&'a AlgebraNode> { + if node.symbol == symbol { + return Some(node); + } + node.children.iter().find_map(|child| walk(child, symbol)) + } + walk(node, symbol).expect(symbol) +} + +#[test] +fn operators_point_at_their_text() { + let sql = "SELECT u.name, count(*) AS n\nFROM users u JOIN orders o ON o.user_id = u.id\nWHERE u.active\nORDER BY n DESC LIMIT 5"; + let root = algebra(sql, SqlDialect::Postgres).unwrap(); + let text = |symbol: &str| &sql[find(&root, symbol).span.clone().unwrap()]; + assert_eq!(text("σ"), "u.active"); + assert_eq!(text("π"), "u.name, count(*) AS n"); + assert_eq!(text("⋈"), "orders o ON o.user_id = u.id"); + assert_eq!(text("τ"), "n DESC"); + assert_eq!(text("limit"), "5"); + let sql = "SELECT 1 FROM a, b UNION SELECT 2"; + let root = algebra(sql, SqlDialect::Postgres).unwrap(); + let text = |symbol: &str| &sql[find(&root, symbol).span.clone().unwrap()]; + assert_eq!((text("∪"), text("×")), (sql, "a, b")); +} + +#[test] +fn projections_list_their_items_by_alias() { + let root = algebra("SELECT a.x, count(*) AS n, b.* FROM a, b", SqlDialect::Sqlite).unwrap(); + let labels: Vec<_> = find(&root, "π").items.iter().map(|i| i.label.as_str()).collect(); + assert_eq!(labels, ["a.x", "n", "b.*"]); +} + +#[test] +fn columns_follow_the_operators() { + let lookup = |table: &TableRef| match table.parts.last()?.to_lowercase().as_str() { + "users" => Some(vec![("id".to_string(), "integer".to_string()), ("name".to_string(), "text".to_string())]), + "orders" => Some(vec![("id".to_string(), "integer".to_string()), ("total".to_string(), "real".to_string())]), + _ => None, + }; + let names = |sql: &str, symbol: &str| { + let root = algebra(sql, SqlDialect::Sqlite).unwrap(); + columns(find(&root, symbol), &lookup).into_iter().map(|c| format!("{}.{}", c.table, c.name)).collect::>() + }; + let sql = "SELECT u.name, o.total AS t, count(*) FROM users u JOIN orders o ON o.id = u.id"; + assert_eq!(names(sql, "⋈"), ["u.id", "u.name", "o.id", "o.total"]); + assert_eq!(names(sql, "π"), ["u.name", "o.t", ".count(*)"]); + assert_eq!(names("WITH u(a, b) AS (SELECT id, name FROM users) SELECT u.* FROM u", "π"), ["u.a", "u.b"]); + assert_eq!(names("SELECT x.* FROM (SELECT id, name FROM users) AS x(k, v)", "π"), ["x.k", "x.v"]); + assert_eq!(names("SELECT \"Users\".* FROM main.\"Users\"", "π"), ["Users.id", "Users.name"]); + let sql = "SELECT count(*) OVER (PARTITION BY id) AS n, sum(total)::int AS s FROM orders"; + let types: Vec<_> = + columns(&algebra(sql, SqlDialect::Postgres).unwrap(), &lookup).into_iter().map(|c| c.data_type).collect(); + assert_eq!(types, ["number", "number"]); +} + +#[test] +fn recursive_ctes_inline_once_and_read_themselves_as_a_leaf() { + let sql = "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 3) SELECT n FROM r"; + let root = algebra(sql, SqlDialect::Postgres).unwrap(); + assert_eq!(show(&root), "π n(ρ r(∪ ALL(π 1(()), π n + 1(σ n < 3(r)))))"); + let inner = &find(&root, "σ").children[0]; + assert_eq!((inner.detail.as_str(), inner.table.as_ref()), ("r", None)); +} + +#[test] +fn copies_of_ctes_stop_adding_up() { + let mut sql = "WITH c0 AS (SELECT * FROM t)".to_string(); + for n in 1..30 { + sql += &format!(", c{n} AS (SELECT * FROM c{p} x, c{p} y)", p = n - 1); + } + sql += " SELECT * FROM c29"; + fn size(node: &AlgebraNode) -> usize { + 1 + node.children.iter().map(size).sum::() + } + assert!(size(&algebra(&sql, SqlDialect::Postgres).unwrap()) < 5000); +} + +// On a stack the size of the app's main thread, which the graph is built on. +#[test] +fn nesting_up_to_the_limit_builds_without_running_out_of_stack() { + let nested = |depth: usize| format!("SELECT * FROM {}t{}", "(SELECT * FROM ".repeat(depth), ") s".repeat(depth)); + let calls = |depth: usize| format!("SELECT {}1{}", "f(".repeat(depth), ")".repeat(depth)); + let deep = [nested(120), calls(120), vec!["SELECT 1"; 1000].join(" UNION ")]; + let main = std::thread::Builder::new().stack_size(8 << 20); + main.spawn(move || deep.iter().for_each(|sql| drop(algebra(sql, SqlDialect::Postgres).unwrap()))) + .unwrap() + .join() + .unwrap(); + for sql in [nested(150), calls(150)] { + assert!(matches!(algebra(&sql, SqlDialect::Postgres), Err(AlgebraError::Syntax(_)))); + } +} + +#[test] +fn engine_clauses_take_their_place_in_the_tree() { + let tree = |sql: &str, dialect| show(&algebra(sql, dialect).unwrap()); + assert_eq!(tree("SELECT TOP 5 name FROM t ORDER BY name", SqlDialect::TSql), "limit 5(τ name(π name(t)))"); + assert_eq!( + tree( + "SELECT d, count() FROM hits PREWHERE x = 1 WHERE y = 2 GROUP BY d ORDER BY d LIMIT 3 BY d LIMIT 10", + SqlDialect::ClickHouse + ), + "limit 10(limit 3 BY d(τ d(π d, count()(γ d(σ y = 2(σ x = 1(hits)))))))" + ); + assert_eq!( + tree("SELECT * FROM u CROSS APPLY (SELECT 1 AS x) a", SqlDialect::TSql), + "π *(⋈ CROSS APPLY(u, ρ a(π 1 AS x(()))))" + ); + assert_eq!(tree("SELECT * FROM a LIMIT 5, 10", SqlDialect::MySql), "limit 10 OFFSET 5(π *(a))"); + assert_eq!(tree("SELECT * FROM \"My Table\" t", SqlDialect::Postgres), "π *(\"My Table\" t)"); + assert_eq!( + tree("SELECT * FROM t ORDER BY a FETCH FIRST 3 ROWS WITH TIES", SqlDialect::Postgres), + "limit 3 WITH TIES(τ a(π *(t)))" + ); + assert_eq!(tree("SELECT * FROM t LIMIT 1, 2 BY d", SqlDialect::ClickHouse), "limit 2 OFFSET 1 BY d(π *(t))"); + assert_eq!( + tree( + "SELECT a FROM t LIMIT 1 UNION ALL SELECT b FROM u LIMIT 1 UNION ALL SELECT c FROM v", + SqlDialect::ClickHouse + ), + "∪ ALL(∪ ALL(limit 1(π a(t)), limit 1(π b(u))), π c(v))" + ); + let root = algebra("SELECT * FROM (VALUES (1), (2), (3)) v(x)", SqlDialect::Postgres).unwrap(); + let values = &find(&root, "ρ").children[0]; + assert_eq!((values.detail.as_str(), values.rows), ("VALUES", Some(3))); +} + +#[test] +fn a_selection_lists_the_conditions_it_requires_together() { + let root = algebra("SELECT 1 FROM t WHERE a = 1 AND (b = 2 OR c = 3) AND d BETWEEN 1 AND 2", SqlDialect::Postgres) + .unwrap(); + let items: Vec<_> = find(&root, "σ").items.iter().map(|i| i.expr.as_str()).collect(); + assert_eq!(items, ["a = 1", "(b = 2 OR c = 3)", "d BETWEEN 1 AND 2"]); +} diff --git a/crates/barsql-sql/tests/select.rs b/crates/barsql-sql/tests/select.rs new file mode 100644 index 0000000..c0dc741 --- /dev/null +++ b/crates/barsql-sql/tests/select.rs @@ -0,0 +1,417 @@ +use barsql_core::SqlDialect::{self, ClickHouse, MySql, Postgres, Sqlite, TSql}; +use barsql_sql::select::{ + Expr, ExprKind, FromItem, JoinKind, ParseError, Query, Select, SetExpr, SetOp, TableFactor, parse_query, +}; + +fn parse(sql: &str, dialect: SqlDialect) -> Query { + parse_query(sql, dialect).unwrap_or_else(|error| panic!("{sql}: {error:?}")) +} + +fn select(query: &Query) -> &Select { + match &query.body { + SetExpr::Select(select) => select, + other => panic!("not a SELECT: {other:?}"), + } +} + +fn names(item: &FromItem) -> Vec { + let name = |factor: &TableFactor| match factor { + TableFactor::Table { name, alias, .. } => { + let name = name.iter().map(|part| part.value.as_str()).collect::>().join("."); + alias.as_ref().map_or(name.clone(), |alias| format!("{name} {}", alias.name.value)) + } + TableFactor::Derived { alias, .. } => format!("({})", alias.as_ref().map_or("", |a| a.name.value.as_str())), + TableFactor::Function { call, .. } => call.text.clone(), + TableFactor::Arrays { text, .. } => text.clone(), + TableFactor::Nested { .. } => "nested".into(), + }; + [name(&item.factor)].into_iter().chain(item.joins.iter().map(|join| name(&join.factor))).collect() +} + +fn texts(exprs: &[Expr]) -> Vec<&str> { + exprs.iter().map(|e| e.text.as_str()).collect() +} + +#[test] +fn every_engine_reads_its_own_select_syntax() { + let generic = [ + "SELECT u.id, o.total FROM users u JOIN orders o ON o.user_id = u.id LEFT JOIN payments p ON p.order_id = o.id", + "SELECT t.n FROM (SELECT count(*) AS n FROM orders GROUP BY user_id) t WHERE t.n > 1", + "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 10) SELECT n FROM r", + "SELECT id FROM a UNION SELECT id FROM b EXCEPT SELECT id FROM c", + "SELECT id, row_number() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn FROM orders", + "SELECT CASE WHEN total > 100 THEN 'big' ELSE 'small' END AS size FROM orders o WHERE status IN ('paid', 'sent') AND EXISTS (SELECT 1 FROM users u WHERE u.id = o.user_id)", + "SELECT DISTINCT a.x FROM a JOIN b USING (id) NATURAL JOIN c CROSS JOIN d", + ]; + for dialect in SqlDialect::ALL { + for sql in generic { + parse(sql, dialect); + } + } + let own = [ + (Postgres, "SELECT * FROM orders FOR UPDATE SKIP LOCKED"), + (Postgres, "SELECT DISTINCT ON (user_id) user_id, total FROM orders ORDER BY user_id, created_at DESC"), + (Postgres, "SELECT u.id, x.total FROM users u CROSS JOIN LATERAL (SELECT sum(total) AS total FROM orders) x"), + (Postgres, "SELECT data->>'name' AS name, tags::text[] FROM docs WHERE data @> '{\"a\":1}'::jsonb AND id = $1"), + (Postgres, "SELECT a.id FROM a FULL OUTER JOIN b ON b.id = a.id"), + (Postgres, "SELECT $$it's$$ AS s, count(*) FILTER (WHERE total > 10) FROM orders"), + (Postgres, "SELECT * FROM generate_series(1, 3) WITH ORDINALITY AS g(n, i)"), + (MySql, "SELECT `u`.`id` FROM `users` `u` LIMIT 5, 10"), + (MySql, "SELECT user_id, sum(total) FROM orders GROUP BY user_id WITH ROLLUP"), + (MySql, "SELECT * FROM orders USE INDEX (idx_user) WHERE user_id = ?"), + (MySql, "SELECT \"text\" AS s, 1 <=> NULL, id DIV 2 FROM t"), + (MySql, "SELECT SQL_CALC_FOUND_ROWS * FROM a STRAIGHT_JOIN b ON b.id = a.id LOCK IN SHARE MODE"), + (TSql, "SELECT TOP (10) PERCENT WITH TIES id FROM orders ORDER BY total"), + (TSql, "SELECT u.id, x.total FROM users u OUTER APPLY (SELECT TOP 1 total FROM orders) x"), + (TSql, "SELECT * FROM orders ORDER BY id OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY"), + (TSql, "SELECT [name], N'ünï' AS s FROM [dbo].[users] WITH (NOLOCK) WHERE id = @id OPTION (RECOMPILE)"), + (TSql, "SELECT total = sum(x) INTO #totals FROM t FOR XML PATH('')"), + (Sqlite, "SELECT * FROM t WHERE name GLOB 'a*'"), + (Sqlite, "SELECT * FROM t INDEXED BY idx_name WHERE name = :name"), + (Sqlite, "SELECT rowid, typeof(x) FROM t NOT INDEXED WHERE x = ?1"), + (ClickHouse, "SELECT * FROM hits SAMPLE 1/10 OFFSET 1/2 WHERE CounterID = 34"), + (ClickHouse, "SELECT s, arr FROM t ARRAY JOIN arr"), + (ClickHouse, "SELECT * FROM hits FINAL PREWHERE EventDate = today() WHERE UserID = 1"), + ( + ClickHouse, + "SELECT domain, count() FROM hits GROUP BY domain WITH TOTALS ORDER BY count() DESC LIMIT 5 BY domain", + ), + (ClickHouse, "SELECT * FROM hits SETTINGS max_threads = 8 FORMAT JSONEachRow"), + (ClickHouse, "WITH 10 AS cap SELECT * FROM a FINAL GLOBAL ANY LEFT JOIN b USING id LIMIT cap"), + ]; + for (dialect, sql) in own { + parse(sql, dialect); + } +} + +#[test] +fn clauses_land_where_they_belong() { + let sql = "SELECT u.name, count(*) AS n FROM users u LEFT JOIN orders o ON o.user_id = u.id \ + WHERE u.active AND o.total > 10 GROUP BY u.name HAVING count(*) > 1 ORDER BY n DESC, 1 LIMIT 5 OFFSET 10"; + let query = parse(sql, Postgres); + let select = select(&query); + let items: Vec<_> = + select.items.iter().map(|i| (i.expr.text.as_str(), i.alias.as_ref().map(|a| a.value.as_str()))).collect(); + assert_eq!(items, [("u.name", None), ("count(*)", Some("n"))]); + assert_eq!(names(&select.from[0]), ["users u", "orders o"]); + assert_eq!(select.from[0].joins[0].kind, JoinKind::Left); + assert_eq!(select.from[0].joins[0].on.as_ref().map(|on| on.text.as_str()), Some("o.user_id = u.id")); + let ExprKind::And(terms) = &select.filter.as_ref().unwrap().kind else { panic!("{:?}", select.filter) }; + assert_eq!(texts(terms), ["u.active", "o.total > 10"]); + assert_eq!(texts(&select.group_by.as_ref().unwrap().keys), ["u.name"]); + assert_eq!(select.having.as_ref().map(|h| h.text.as_str()), Some("count(*) > 1")); + let keys: Vec<_> = query.order_by.iter().map(|k| (k.text.as_str(), k.desc)).collect(); + assert_eq!(keys, [("n DESC", true), ("1", false)]); + let limit = query.limit.as_ref().unwrap(); + assert_eq!( + (limit.count.as_ref().map(|c| c.text.as_str()), limit.offset.as_ref().map(|o| o.text.as_str())), + (Some("5"), Some("10")) + ); + assert_eq!(&sql[select.from[0].joins[0].span.clone()], "orders o ON o.user_id = u.id"); +} + +#[test] +fn each_engine_limits_its_own_way() { + let limit = |sql: &str, dialect| { + let limit = parse(sql, dialect).limit.unwrap(); + (limit.count.map(|c| c.text), limit.offset.map(|o| o.text)) + }; + let some = |count: &str, offset: Option<&str>| (Some(count.to_string()), offset.map(str::to_string)); + assert_eq!(limit("SELECT * FROM t LIMIT 5, 10", MySql), some("10", Some("5"))); + assert_eq!(limit("SELECT * FROM t LIMIT 10 OFFSET 5", Sqlite), some("10", Some("5"))); + assert_eq!(limit("SELECT * FROM t ORDER BY a OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY", TSql), some("10", Some("5"))); + assert_eq!(limit("SELECT * FROM t FETCH FIRST 10 ROWS ONLY", Postgres), some("10", None)); + let query = parse("SELECT TOP (10) PERCENT WITH TIES * FROM t ORDER BY a", TSql); + let top = select(&query).top.as_ref().unwrap(); + assert_eq!((top.count.text.as_str(), top.percent, top.with_ties), ("10", true, true)); + let query = parse("SELECT d, x FROM t ORDER BY x LIMIT 2 BY d LIMIT 10", ClickHouse); + let by = query.limit_by.as_ref().unwrap(); + assert_eq!((by.count.text.as_str(), texts(&by.by)), ("2", vec!["d"])); + assert_eq!(query.limit.and_then(|l| l.count).map(|c| c.text), Some("10".into())); + assert_eq!(limit("SELECT * FROM t FETCH FIRST ROW ONLY", Postgres), some("1", None)); + assert!(parse("SELECT * FROM t ORDER BY a FETCH NEXT 3 ROWS WITH TIES", Postgres).limit.unwrap().with_ties); + for sql in ["SELECT * FROM t LIMIT 1, 2 BY d", "SELECT * FROM t LIMIT 2 OFFSET 1 BY d"] { + let by = parse(sql, ClickHouse).limit_by.unwrap(); + assert_eq!((by.count.text.as_str(), by.offset.map(|o| o.text)), ("2", Some("1".into())), "{sql}"); + } +} + +#[test] +fn joins_know_their_kind() { + let kinds = |sql: &str, dialect| -> Vec<(JoinKind, bool)> { + let query = parse(sql, dialect); + select(&query).from[0].joins.iter().map(|join| (join.kind, join.natural)).collect() + }; + use JoinKind::*; + assert_eq!( + kinds("SELECT * FROM a LEFT OUTER JOIN b ON true RIGHT JOIN c ON true FULL JOIN d ON true", Postgres), + [(Left, false), (Right, false), (Full, false)] + ); + assert_eq!( + kinds("SELECT * FROM a NATURAL LEFT JOIN b CROSS JOIN c INNER JOIN d USING (id)", Postgres), + [(Left, true), (Cross, false), (Inner, false)] + ); + assert_eq!( + kinds("SELECT * FROM a CROSS APPLY f(a.x) OUTER APPLY (SELECT 1 AS y) b", TSql), + [(CrossApply, false), (OuterApply, false)] + ); + assert_eq!( + kinds("SELECT * FROM a ANY LEFT JOIN b USING (id) LEFT SEMI JOIN c ON true ARRAY JOIN arr", ClickHouse), + [(Left, false), (Semi, false), (Array, false)] + ); + let query = parse("SELECT * FROM a JOIN b USING (id, region)", MySql); + let using: Vec<_> = select(&query).from[0].joins[0].using.iter().map(|c| c.value.as_str()).collect(); + assert_eq!(using, ["id", "region"]); + assert_eq!( + kinds("SELECT * FROM a INNER HASH JOIN b ON a.id = b.id LEFT MERGE JOIN c ON c.id = a.id", TSql), + [(Inner, false), (Left, false)] + ); + let query = parse("SELECT * FROM f JOIN b ON b.hash = f.hash JOIN c ON c.left = global JOIN d ON true", ClickHouse); + let conditions: Vec<_> = + select(&query).from[0].joins.iter().map(|j| j.on.as_ref().unwrap().text.as_str()).collect(); + assert_eq!(conditions, ["b.hash = f.hash", "c.left = global", "true"]); +} + +#[test] +fn a_second_on_joins_the_tables_before_it_as_one() { + let query = parse("SELECT * FROM a LEFT JOIN b JOIN c ON c.id = b.id ON b.id = a.id", Postgres); + let from = &select(&query).from[0]; + let [join] = from.joins.as_slice() else { panic!("{from:?}") }; + assert_eq!((join.kind, join.on.as_ref().map(|on| on.text.as_str())), (JoinKind::Left, Some("b.id = a.id"))); + let TableFactor::Nested { item, .. } = &join.factor else { panic!("{join:?}") }; + assert_eq!(names(item), ["b", "c"]); + assert_eq!(item.joins[0].on.as_ref().map(|on| on.text.as_str()), Some("c.id = b.id")); +} + +#[test] +fn hints_and_samples_leave_the_table_and_its_alias() { + let tables = |sql: &str, dialect| names(&select(&parse(sql, dialect)).from[0]); + assert_eq!(tables("SELECT * FROM [dbo].[users] u WITH (NOLOCK)", TSql), ["dbo.users u"]); + assert_eq!(tables("SELECT * FROM orders o FORCE INDEX FOR JOIN (idx) JOIN t USING (id)", MySql), ["orders o", "t"]); + assert_eq!(tables("SELECT * FROM t AS x INDEXED BY idx", Sqlite), ["t x"]); + assert_eq!(tables("SELECT * FROM hits AS h FINAL SAMPLE 0.1", ClickHouse), ["hits h"]); + assert_eq!(tables("SELECT * FROM t TABLESAMPLE SYSTEM (10) REPEATABLE (1) AS s", Postgres), ["t s"]); + assert_eq!(tables("SELECT * FROM ONLY \"Parent\" p", Postgres), ["Parent p"]); + assert_eq!(tables("SELECT * FROM sales s PIVOT (sum(amount) FOR m IN ([1], [2])) AS p", TSql), ["sales s"]); + assert_eq!(tables("SELECT * FROM t FOR SYSTEM_TIME AS OF '2024-01-01' AS x", TSql), ["t x"]); + assert_eq!(tables("SELECT * FROM t FOR SYSTEM_TIME BETWEEN @a AND @b x JOIN u ON u.id = x.id", TSql), ["t x", "u"]); + assert_eq!(tables("SELECT * FROM OPENJSON(@j) WITH (id int '$.id') AS j", TSql), ["OPENJSON(@j)"]); + assert_eq!(tables("SELECT * FROM db..t", TSql), ["db..t"]); + assert_eq!(tables("SELECT * FROM ((SELECT 1 AS id) s JOIN t ON t.id = s.id)", Postgres), ["nested"]); +} + +#[test] +fn expressions_say_what_shape_they_are() { + let kind = |sql: &str, dialect| select(&parse(&format!("SELECT {sql}"), dialect)).items[0].expr.kind.clone(); + let column = |sql: &str| match kind(sql, Postgres) { + ExprKind::Column { qualifier, name } => { + qualifier.iter().map(|q| q.value.clone()).chain([name.value]).collect::>().join("|") + } + other => panic!("{sql}: {other:?}"), + }; + assert_eq!(column("a"), "a"); + assert_eq!(column("s.\"T\".a"), "s|T|a"); + assert!(matches!(kind("t.*", Postgres), ExprKind::Wildcard(q) if q.len() == 1)); + for value in ["NULL", "'x'", "-1", "$1", "DATE '2024-01-01'", "INTERVAL '1' DAY", "E'\\n'", "CURRENT_DATE"] { + assert_eq!(kind(value, Postgres), ExprKind::Value, "{value}"); + } + assert_eq!(kind("@id", TSql), ExprKind::Value); + assert_eq!(kind("?1", Sqlite), ExprKind::Value); + assert_eq!(kind(":name", Sqlite), ExprKind::Value); + let ExprKind::Call { name, args } = kind("pg_catalog.round(avg(x), 2)", Postgres) else { panic!() }; + assert_eq!((name.len(), texts(&args)), (2, vec!["avg(x)", "2"])); + let compare = |sql: &str, dialect| match kind(sql, dialect) { + ExprKind::Compare { left, op, right } => (left.text, op, right.text), + other => panic!("{sql}: {other:?}"), + }; + let three = |a: &str, op: &str, b: &str| (a.to_string(), op.to_string(), b.to_string()); + assert_eq!(compare("a=-1", Postgres), three("a", "=", "-1")); + assert_eq!(compare("data->>'k' <> 'v'", Postgres), three("data->>'k'", "<>", "'v'")); + assert_eq!(compare("x NOT LIKE 'a%'", Postgres), three("x", "NOT LIKE", "'a%'")); + assert_eq!(compare("x IS NOT NULL", Postgres), three("x", "IS NOT", "NULL")); + assert_eq!(compare("x IN (1, 2)", Postgres), three("x", "IN", "(1, 2)")); + assert_eq!(compare("a <=> b", MySql), three("a", "<=>", "b")); + assert_eq!(kind("NOT a = 1", Postgres), ExprKind::Other); + assert_eq!(kind("a = 1 OR b = 2 AND c = 3", Postgres), ExprKind::Other); + let and = |sql: &str| match kind(sql, Postgres) { + ExprKind::And(terms) => terms.into_iter().map(|t| t.text).collect::>(), + other => panic!("{sql}: {other:?}"), + }; + assert_eq!(and("a BETWEEN 1 AND 2 AND b"), ["a BETWEEN 1 AND 2", "b"]); + assert_eq!(and("CASE WHEN x AND y THEN 1 END = 1 AND z"), ["CASE WHEN x AND y THEN 1 END = 1", "z"]); + assert_eq!(and("NOT a AND (b OR c)"), ["NOT a", "(b OR c)"]); +} + +#[test] +fn items_find_their_aliases() { + let aliases = |sql: &str, dialect| -> Vec> { + select(&parse(sql, dialect)).items.iter().map(|i| i.alias.as_ref().map(|a| a.value.clone())).collect() + }; + assert_eq!( + aliases("SELECT count(*) n, a AS b, c \"Quoted\", d.e, x::text, y IS NULL FROM t", Postgres), + [Some("n".into()), Some("b".into()), Some("Quoted".into()), None, None, None] + ); + assert_eq!( + aliases("SELECT CASE WHEN a THEN 1 END total, sum(x) OVER w FROM t WINDOW w AS (ORDER BY a)", Postgres), + [Some("total".into()), None] + ); + assert_eq!(aliases("SELECT n = count(*), 'x' AS 'label' FROM t", TSql), [Some("n".into()), Some("label".into())]); + let none = |sql: &str, dialect| assert!(aliases(sql, dialect).iter().all(Option::is_none), "{sql}"); + none("SELECT INTERVAL '1' DAY, ts AT TIME ZONE 'UTC', a IS DISTINCT FROM b, BINARY c FROM t", Postgres); + none("SELECT now() - INTERVAL 1 DAY, DATE '2024-01-01', 'a' 'b' FROM t", MySql); + assert_eq!( + aliases("SELECT x::double precision AS d, y::character varying z, name 'Label' FROM t", MySql), + [Some("d".into()), Some("z".into()), Some("Label".into())] + ); +} + +#[test] +fn names_beyond_ascii_and_clause_words_after_a_dot_stay_names() { + let query = parse("SELECT café, t.naïve AS größe FROM tablé t JOIN 名前 n ON n.offset = t.limit", Postgres); + let first = select(&query); + let items: Vec<_> = + first.items.iter().map(|i| (i.expr.text.as_str(), i.alias.as_ref().map(|a| a.value.as_str()))).collect(); + assert_eq!(items, [("café", None), ("t.naïve", Some("größe"))]); + assert_eq!(names(&first.from[0]), ["tablé t", "名前 n"]); + assert_eq!(first.from[0].joins[0].on.as_ref().map(|on| on.text.as_str()), Some("n.offset = t.limit")); + let query = parse("SELECT format, k.from FROM t k WHERE window > 1 ORDER BY k.order", ClickHouse); + let items: Vec<_> = select(&query).items.iter().map(|i| i.expr.text.as_str()).collect(); + assert_eq!(items, ["format", "k.from"]); + assert_eq!(select(&query).filter.as_ref().map(|f| f.text.as_str()), Some("window > 1")); + let query = parse("SELECT * EXCEPT (secret), t.* REPLACE (x + 1 AS x) FROM t", ClickHouse); + assert!(select(&query).items.iter().all(|i| matches!(i.expr.kind, ExprKind::Wildcard(_)))); +} + +#[test] +fn text_reads_as_written_without_comments() { + let sql = "SELECT a +\n /* why */ b AS s, -- trailing\n f( x ) FROM t"; + let query = parse(sql, Postgres); + let items = &select(&query).items; + assert_eq!((items[0].text.as_str(), items[0].expr.text.as_str()), ("a + b AS s", "a + b")); + assert_eq!(&sql[items[0].span.clone()], "a +\n /* why */ b AS s"); + assert_eq!(items[1].text, "f( x )"); +} + +#[test] +fn set_operations_follow_each_engines_precedence() { + let shape = |dialect| match parse("SELECT 1 UNION SELECT 2 INTERSECT SELECT 3", dialect).body { + SetExpr::SetOp { op, left, right, .. } => { + (op, matches!(*left, SetExpr::SetOp { .. }), matches!(*right, SetExpr::SetOp { .. })) + } + other => panic!("{other:?}"), + }; + assert_eq!(shape(Postgres), (SetOp::Union, false, true)); + assert_eq!(shape(Sqlite), (SetOp::Intersect, true, false)); + let query = parse("(SELECT a FROM t ORDER BY a LIMIT 1) UNION ALL (SELECT b FROM u)", MySql); + let SetExpr::SetOp { all: true, left, .. } = &query.body else { panic!("{:?}", query.body) }; + assert!(matches!(&**left, SetExpr::Query(q) if q.limit.is_some() && !q.order_by.is_empty())); + let query = parse("SELECT a FROM t ORDER BY a LIMIT 1 UNION ALL SELECT b FROM u", ClickHouse); + assert!(matches!(&query.body, SetExpr::SetOp { left, .. } if matches!(&**left, SetExpr::Query(_)))); + let sql = "SELECT a FROM t UNION ALL SELECT b FROM u ORDER BY b LIMIT 2"; + let query = parse(sql, ClickHouse); + assert!(query.order_by.is_empty() && query.limit.is_none(), "the last SELECT's own"); + let SetExpr::SetOp { right, .. } = &query.body else { panic!("{:?}", query.body) }; + assert!(matches!(&**right, SetExpr::Query(q) if q.limit.is_some())); + let query = parse(sql, Postgres); + assert!(!query.order_by.is_empty() && query.limit.is_some(), "the whole union's"); + assert_eq!(&sql[query.body.span()], "SELECT a FROM t UNION ALL SELECT b FROM u"); +} + +#[test] +fn queries_nest_with_their_own_parts() { + let query = parse( + "WITH a AS (SELECT 1 AS x), b(y) AS MATERIALIZED (SELECT 2) SELECT * FROM a, b, (VALUES (1), (2)) v(z)", + Postgres, + ); + let ctes: Vec<_> = query.ctes.iter().map(|c| (c.name.value.as_str(), c.columns.len())).collect(); + assert_eq!(ctes, [("a", 0), ("b", 1)]); + let from = &select(&query).from; + let TableFactor::Derived { query: values, alias: Some(alias), .. } = &from[2].factor else { panic!("{from:?}") }; + assert!(matches!(&values.body, SetExpr::Values { rows, .. } if rows.len() == 2)); + assert_eq!(alias.columns[0].value, "z"); + let query = parse("SELECT * FROM (a JOIN b ON a.id = b.id) AS ab LEFT JOIN c ON c.id = ab.id", Postgres); + assert!(matches!(&select(&query).from[0].factor, TableFactor::Nested { alias: Some(_), .. })); + assert_eq!(select(&query).from[0].joins.len(), 1); + let query = parse("SELECT a IS DISTINCT FROM b, percentile_cont(0.5) WITHIN GROUP (ORDER BY x) FROM t", Postgres); + assert_eq!(select(&query).items.len(), 2); + assert_eq!(names(&select(&query).from[0]), ["t"]); +} + +#[test] +fn half_typed_queries_fail_where_they_stop() { + let at = |sql: &str| match parse_query(sql, Postgres) { + Err(ParseError::Syntax { at, .. }) => at, + other => panic!("{sql}: {other:?}"), + }; + assert_eq!(at("SELECT u. FROM users u"), 10); + assert_eq!(at("SELECT * FROM users u JOIN orders o ON "), 39); + assert_eq!(at("SELECT * FROM users WHERE "), 26); + assert_eq!(at("SELECT id, FROM users"), 11); + assert_eq!(at("SELECT * FROM "), 14); + assert_eq!(at("SELECT count(*) AS FROM t"), 19); + assert_eq!(at("SELECT 'open FROM t"), 7); + assert_eq!(at("SELECT a FROM t WHERE (a = 1"), 28); + assert_eq!(at("SELECT 1 x y"), 11); + assert_eq!(at("SELECT * FROM t WHERE a = 1 AND"), 31); + assert_eq!(at("SELECT CASE WHEN a THEN 1 FROM t"), 32); + assert_eq!(at("SELECT * FROM a JOIN b ON a.id = b. JOIN c"), 36); +} + +#[test] +fn every_prefix_parses_or_fails_without_panicking() { + let queries = [ + "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 3), s AS MATERIALIZED (VALUES (1, 'a'))\ + SELECT DISTINCT ON (a.x) a.x AS \"X\", count(*) FILTER (WHERE b.y IS NOT NULL) n, CASE WHEN c BETWEEN 1 AND 2 THEN \ + $$it's$$ END FROM a NATURAL LEFT JOIN (b JOIN c USING (id)) bc CROSS JOIN LATERAL f(a.x) WITH ORDINALITY g(v, i) \ + WHERE a.x = -1 AND (b.y OR c.z) AND d->>'k' NOT IN (SELECT k FROM e) GROUP BY ALL HAVING sum(x) > 0 WINDOW w AS \ + (ORDER BY a) ORDER BY 1 DESC NULLS LAST OFFSET 5 ROWS FETCH FIRST 10 ROWS ONLY FOR UPDATE SKIP LOCKED;", + "SELECT TOP (10) PERCENT WITH TIES t = sum(x), [a].[b] FROM [dbo].[t] x WITH (NOLOCK) OUTER APPLY (SELECT 1 y) z \ + ORDER BY 1 OFFSET 2 ROWS OPTION (RECOMPILE)", + "SELECT SQL_CALC_FOUND_ROWS `a`, \"s\" FROM t USE INDEX (i) STRAIGHT_JOIN u ON u.id = t.id GROUP BY a WITH ROLLUP \ + LIMIT 5, 10 LOCK IN SHARE MODE", + "WITH 1 AS one SELECT d, count() FROM hits FINAL SAMPLE 1/10 GLOBAL ANY LEFT JOIN u USING id ARRAY JOIN arr AS a \ + PREWHERE x = 1 WHERE y = 2 GROUP BY d WITH TOTALS ORDER BY d LIMIT 3 BY d LIMIT 10 SETTINGS a = 1 FORMAT JSON", + "SELECT rowid FROM t INDEXED BY i WHERE x GLOB 'a*' AND y = ?1 UNION SELECT 1 INTERSECT SELECT 2 EXCEPT SELECT :n", + ]; + for sql in queries { + for dialect in SqlDialect::ALL { + for end in (0..=sql.len()).filter(|&end| sql.is_char_boundary(end)) { + let _ = parse_query(&sql[..end], dialect); + } + assert!(parse_query(sql, dialect).is_ok() || dialect != own_dialect(sql), "{dialect:?}: {sql}"); + } + } +} + +// The engine each fixture above is written for. +fn own_dialect(sql: &str) -> SqlDialect { + match () { + _ if sql.contains("NOLOCK") => TSql, + _ if sql.contains("ROLLUP") => MySql, + _ if sql.contains("FINAL") => ClickHouse, + _ if sql.contains("GLOB") => Sqlite, + _ => Postgres, + } +} + +#[test] +fn only_one_query_is_a_query() { + for sql in + ["INSERT INTO t VALUES (1)", "WITH x AS (SELECT 1) DELETE FROM t", "SELECT 1; SELECT 2", "", "-- nothing"] + { + assert_eq!(parse_query(sql, Postgres), Err(ParseError::NotQuery), "{sql}"); + } + assert!(matches!(parse_query("SELEC 1", Postgres), Err(ParseError::Syntax { at: 0, .. }))); + assert!(parse_query("SELECT 1;", Postgres).is_ok()); + assert!(parse_query("; SELECT 1", Postgres).is_ok()); + assert!(select(&parse("SELECT FROM t", Postgres)).items.is_empty()); + assert!(parse("WITH gone AS (DELETE FROM t RETURNING *) SELECT * FROM gone", Postgres).ctes.is_empty()); +} + +#[test] +fn nesting_stops_at_an_error_before_the_stack_does() { + let deep = format!("SELECT {}1{}", "(".repeat(300), ")".repeat(300)); + assert!(matches!(parse_query(&deep, Postgres), Err(ParseError::Syntax { expected: "a smaller query", .. }))); + let unions = vec!["SELECT 1"; 1002].join(" UNION "); + assert!(matches!(parse_query(&unions, Postgres), Err(ParseError::Syntax { expected: "a smaller query", .. }))); +} diff --git a/crates/barsql-ui/locales/bg.json b/crates/barsql-ui/locales/bg.json index 0e4262c..0475e20 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -316,6 +316,7 @@ }, "shortcuts": { "items": { + "showAlgebra": "Показване на заявката като релационна алгебра", "runSelection": "Изпълни избраното или заявката", "commandPalette": "Палитра с команди", "saveQueryAs": "Запази заявката като" @@ -534,6 +535,36 @@ "noRows": "Още няма редове за графика.", "blank": "(празно)" }, + "algebra": { + "title": "Релационна алгебра", + "hint": "Плъзнете за преместване · {{modifier}}+скрол или щипване за мащаб · Задръжте над оператор, за да видите колоните му · Кликнете, за да го намерите в заявката", + "moreColumns": "+{{count}} още колона", + "moreColumns_other": "+{{count}} още колони", + "noColumns": "Колоните на тази таблица още не са заредени.", + "stale": "Заявката е променена, откакто е начертан този граф. Начертайте го отново.", + "notQuery": "Като релационна алгебра може да се покаже само една заявка SELECT.", + "syntax": "Заявката не може да се прочете около „{{near}}“.", + "syntaxEnd": "Заявката свършва, преди да е завършена.", + "search": "Намери оператор или таблица", + "noMatches": "Няма такъв оператор или таблица", + "operators": "{{count}} оператор", + "operators_other": "{{count}} оператора", + "ops": { + "table": "Таблица", + "select": "Селекция", + "project": "Проекция", + "join": "Съединение", + "cross": "Произведение", + "group": "Групиране", + "sort": "Сортиране", + "limit": "Лимит", + "distinct": "Distinct", + "union": "Обединение", + "intersect": "Сечение", + "except": "Разлика", + "rename": "Преименуване" + } + }, "erDiagram": { "exportSvg": "Запазване като SVG", "tables": "{{count}} таблица", diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index 863c529..90fcd3d 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -316,6 +316,7 @@ }, "shortcuts": { "items": { + "showAlgebra": "Die Abfrage als relationale Algebra anzeigen", "runSelection": "Auswahl oder Anweisung ausführen", "commandPalette": "Befehlspalette", "saveQueryAs": "Abfrage speichern unter" @@ -535,6 +536,36 @@ "noRows": "Noch keine Zeilen für ein Diagramm.", "blank": "(leer)" }, + "algebra": { + "title": "Relationale Algebra", + "hint": "Ziehen zum Verschieben · {{modifier}}+Scrollen oder Zoomgeste zum Zoomen · Mit der Maus über einen Operator fahren, um seine Spalten zu sehen · Klicken, um ihn in der Abfrage zu finden", + "moreColumns": "+{{count}} weitere Spalte", + "moreColumns_other": "+{{count}} weitere Spalten", + "noColumns": "Die Spalten dieser Tabelle sind noch nicht geladen.", + "stale": "Die Abfrage hat sich seit dem Zeichnen dieses Graphen geändert. Zeichne ihn neu.", + "notQuery": "Nur ein einzelnes SELECT kann als relationale Algebra angezeigt werden.", + "syntax": "Die Abfrage ist bei „{{near}}“ nicht lesbar.", + "syntaxEnd": "Die Abfrage endet, bevor sie vollständig ist.", + "search": "Operator oder Tabelle suchen", + "noMatches": "Kein Operator und keine Tabelle passt", + "operators": "{{count}} Operator", + "operators_other": "{{count}} Operatoren", + "ops": { + "table": "Tabelle", + "select": "Selektion", + "project": "Projektion", + "join": "Verbund", + "cross": "Produkt", + "group": "Gruppierung", + "sort": "Sortierung", + "limit": "Limit", + "distinct": "Distinct", + "union": "Vereinigung", + "intersect": "Schnitt", + "except": "Differenz", + "rename": "Umbenennung" + } + }, "erDiagram": { "exportSvg": "Als SVG speichern", "tables": "{{count}} Tabelle", diff --git a/crates/barsql-ui/locales/en.json b/crates/barsql-ui/locales/en.json index b6f061e..805fde9 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -338,6 +338,7 @@ }, "shortcuts": { "items": { + "showAlgebra": "Show the query as relational algebra", "runSelection": "Run selection or statement", "commandPalette": "Command palette", "saveQueryAs": "Save query as" @@ -560,6 +561,36 @@ "noRows": "No rows to chart yet.", "blank": "(empty)" }, + "algebra": { + "title": "Relational algebra", + "hint": "Drag to pan · {{modifier}}+scroll or pinch to zoom · Hover an operator to see its columns · Click to find it in the query", + "moreColumns": "+{{count}} more column", + "moreColumns_other": "+{{count}} more columns", + "noColumns": "The columns of this table haven't loaded yet.", + "stale": "The query has changed since this graph was drawn. Draw it again.", + "notQuery": "Only a single SELECT can be shown as relational algebra.", + "syntax": "Couldn't read the query near \"{{near}}\".", + "syntaxEnd": "The query ends before it's complete.", + "search": "Find an operator or table", + "noMatches": "No operator or table matches", + "operators": "{{count}} operator", + "operators_other": "{{count}} operators", + "ops": { + "table": "Table", + "select": "Selection", + "project": "Projection", + "join": "Join", + "cross": "Product", + "group": "Grouping", + "sort": "Sort", + "limit": "Limit", + "distinct": "Distinct", + "union": "Union", + "intersect": "Intersection", + "except": "Difference", + "rename": "Rename" + } + }, "erDiagram": { "exportSvg": "Save as SVG", "tables": "{{count}} table", diff --git a/crates/barsql-ui/locales/es.json b/crates/barsql-ui/locales/es.json index b1b329a..ce09511 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -316,6 +316,7 @@ }, "shortcuts": { "items": { + "showAlgebra": "Mostrar la consulta como álgebra relacional", "runSelection": "Ejecutar la selección o la sentencia", "commandPalette": "Paleta de comandos", "saveQueryAs": "Guardar consulta como" @@ -544,6 +545,36 @@ "noRows": "Aún no hay filas para graficar.", "blank": "(vacío)" }, + "algebra": { + "title": "Álgebra relacional", + "hint": "Arrastra para desplazarte · {{modifier}}+rueda o pellizca para acercar · Pasa el cursor sobre un operador para ver sus columnas · Haz clic para ubicarlo en la consulta", + "moreColumns": "+{{count}} columna más", + "moreColumns_other": "+{{count}} columnas más", + "noColumns": "Las columnas de esta tabla todavía no se cargaron.", + "stale": "La consulta cambió desde que se dibujó este grafo. Vuelve a dibujarlo.", + "notQuery": "Solo una consulta SELECT puede mostrarse como álgebra relacional.", + "syntax": "No se pudo leer la consulta cerca de \"{{near}}\".", + "syntaxEnd": "La consulta termina antes de estar completa.", + "search": "Buscar un operador o una tabla", + "noMatches": "Ningún operador ni tabla coincide", + "operators": "{{count}} operador", + "operators_other": "{{count}} operadores", + "ops": { + "table": "Tabla", + "select": "Selección", + "project": "Proyección", + "join": "Reunión", + "cross": "Producto", + "group": "Agrupación", + "sort": "Orden", + "limit": "Límite", + "distinct": "Distinto", + "union": "Unión", + "intersect": "Intersección", + "except": "Diferencia", + "rename": "Renombrar" + } + }, "erDiagram": { "exportSvg": "Guardar como SVG", "tables": "{{count}} tabla", diff --git a/crates/barsql-ui/src/actions.rs b/crates/barsql-ui/src/actions.rs index fd4bd29..02af546 100644 --- a/crates/barsql-ui/src/actions.rs +++ b/crates/barsql-ui/src/actions.rs @@ -54,6 +54,7 @@ actions!( RunAll, ExplainQuery, ExplainAnalyze, + ShowAlgebra, NextTab, PrevTab, FormatQuery, diff --git a/crates/barsql-ui/src/algebra_graph.rs b/crates/barsql-ui/src/algebra_graph.rs new file mode 100644 index 0000000..c37d98e --- /dev/null +++ b/crates/barsql-ui/src/algebra_graph.rs @@ -0,0 +1,1145 @@ +mod svg; + +use std::collections::HashSet; +use std::ops::Range; +use std::rc::Rc; +use std::time::Duration; + +use barsql_core::{ConnectionConfig, SqlDialect}; +use barsql_sql::{AlgebraError, AlgebraNode, Column, Item, TableRef, algebra, columns, display_type}; +use gpui_kit::assets::IconName as Lucide; +use gpui_kit::base::{Align, Placement, Positioner}; +use gpui_kit::component::button::ButtonVariants; +use gpui_kit::component::scroll::ScrollbarAxis; +use gpui_kit::component::{ActiveTheme, Icon, StyledExt, Theme, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +use crate::assets::icon_svg; +use crate::er_diagram::search::Search; +use crate::er_diagram::zoom::{self, Viewport}; +use crate::er_diagram::{FADED, TextWidths, save_svg}; +use crate::form; +use crate::fuzzy::substring_rank; +use crate::i18n::{I18n, compact, t, t_count, t_with}; +use crate::schema; +use crate::scrollbars::HoverScrollbar as _; +use crate::tokens::{ICON_XS, RADIUS, STRIP, TEXT_2XS, TEXT_SM, TEXT_XS}; +use crate::{theme, toast}; + +// Sizes are rems of the 13px root, like the ER diagram's. +const NODE_W: f32 = 18.462; +const HEADER_H: f32 = 2.154; +const GAP_X: f32 = 2.308; +const GAP_Y: f32 = 2.846; +const MARGIN: f32 = 1.538; +const BODY_PAD: f32 = 0.385; +// What a body has room for across: the node less its padding. +const INNER_W: f32 = NODE_W - 1.231; +const PILL_H: f32 = 1.462; +const PILL_GAP: f32 = 0.308; +const MAX_PILL_ROWS: usize = 4; +const LINE_H: f32 = 1.385; +const LINE_GAP: f32 = 0.231; +// Room for the AND that leads a condition. +const AND_W: f32 = 2.; +// About how many characters of code fit across a body. +const CHARS_PER_LINE: usize = 32; +// What the preview lists, with the rest counted. +const PREVIEW_COLUMNS: usize = 12; +const PREVIEW_W: f32 = 20.; +const PREVIEW_PAD: f32 = 0.769; +const PREVIEW_ROW_H: f32 = 1.692; +// As long as a tooltip waits. +const PREVIEW_DELAY: Duration = Duration::from_millis(500); + +// A pick, for the query tab to mark. +pub enum AlgebraEvent { + // The operator's range in the drawn statement; None clears the mark. + Reveal { range: Option>, color: Hsla }, +} + +// What a node shows under its header. +enum Body { + None, + // The items of a projection, grouping or sort, a row of pills at a time. + Pills(Vec>), + // An expression as code, wrapping to a second line at most. + Lines(Vec), + // The conditions of a selection, one a row, each one on a single line. + Conditions(Vec), +} + +struct Flat { + // Without its children, which the layout's root keeps. + node: AlgebraNode, + body: Body, + // Its parent, and which child of it this is. + up: Option<(usize, usize)>, +} + +fn shallow(node: &AlgebraNode) -> AlgebraNode { + let AlgebraNode { symbol, detail, items, span, table, rows, .. } = node; + let (detail, items, span, table) = (detail.clone(), items.clone(), span.clone(), table.clone()); + AlgebraNode { symbol, detail, children: vec![], items, span, table, rows: *rows } +} + +// A join's kind, if it says one, and its condition. +fn join_parts(detail: &str) -> (Option<&str>, &str) { + const KINDS: [&str; 10] = + ["CROSS APPLY", "OUTER APPLY", "LEFT ARRAY", "ARRAY", "LEFT", "RIGHT", "FULL", "CROSS", "SEMI", "ANTI"]; + let kind = + KINDS.into_iter().find(|kind| detail.strip_prefix(kind).is_some_and(|r| r.is_empty() || r.starts_with(' '))); + let rest = kind.map_or(detail, |kind| detail[kind.len()..].trim_start()); + (kind, rest.strip_prefix("ON ").unwrap_or(rest)) +} + +fn body_of(node: &AlgebraNode) -> Body { + let lines = |text: &str| if text.is_empty() { Body::None } else { Body::Lines(vec![text.to_string()]) }; + match node.symbol { + "" => Body::None, + "π" | "γ" | "τ" if !node.items.is_empty() => Body::Pills(pill_rows(&node.items)), + "ρ" if !node.items.is_empty() => { + let columns = node.items.iter().map(|item| item.label.as_str()).collect::>().join(", "); + Body::Pills(vec![vec![format!("{}({columns})", node.detail)]]) + } + "ρ" | "limit" if !node.detail.is_empty() => Body::Pills(vec![vec![node.detail.clone()]]), + "σ" if node.items.len() > 1 => Body::Conditions(node.items.iter().map(|item| item.expr.clone()).collect()), + "⋈" => lines(join_parts(&node.detail).1), + _ => lines(&node.detail), + } +} + +fn line_count(text: &str) -> usize { + text.chars().count().div_ceil(CHARS_PER_LINE).clamp(1, 2) +} + +// Where each operator goes: leaves side by side along the bottom, every parent above and between its children. +struct Layout { + root: Rc, + // In the order of a walk from the root. The first is the root. + flat: Vec, + // Left, top and height. + boxes: Vec<(f32, f32, f32)>, + // Parent and child. + edges: Vec<(usize, usize)>, + width: f32, + height: f32, +} + +impl Layout { + fn subtree(&self, ix: usize) -> &AlgebraNode { + let mut path = vec![]; + let mut at = ix; + while let Some((parent, child)) = self.flat[at].up { + path.push(child); + at = parent; + } + path.iter().rev().fold(&self.root, |node, &child| &node.children[child]) + } +} + +// A guess at a pill's width, for filling rows before anything is drawn. +fn pill_width(label: &str) -> f32 { + (label.chars().count() as f32 * 0.58 + 1.4).min(INNER_W) +} + +fn row_width(row: &[String]) -> f32 { + row.iter().map(|label| pill_width(label)).sum::() + PILL_GAP * row.len().saturating_sub(1) as f32 +} + +// The items in rows that fit the node. Past the last row, a "+N" stands for the rest. +fn pill_rows(items: &[Item]) -> Vec> { + let mut rows: Vec> = vec![]; + for item in items { + let fits = rows.last().is_some_and(|row| row_width(row) + PILL_GAP + pill_width(&item.label) <= INNER_W); + match (fits, rows.len() == MAX_PILL_ROWS) { + (true, _) => rows.last_mut().expect("a row fits it").push(item.label.clone()), + (false, true) => break, + (false, false) => rows.push(vec![item.label.clone()]), + } + } + let shown = |rows: &[Vec]| rows.iter().map(Vec::len).sum::(); + if shown(&rows) < items.len() { + // Room for the count in the last row, wide enough for the biggest there could be. + let room = pill_width(&format!("+{}", items.len())); + while let Some(row) = rows.last_mut() { + if row.is_empty() || row_width(row) + PILL_GAP + room <= INNER_W { + break; + } + row.pop(); + } + let more = format!("+{}", items.len() - shown(&rows)); + if let Some(row) = rows.last_mut() { + row.push(more); + } + } + rows +} + +// The "+N" pill that ends a cut list. +fn is_count(label: &str) -> bool { + label.strip_prefix('+').is_some_and(|n| n.chars().all(|c| c.is_ascii_digit())) +} + +fn height_of(body: &Body) -> f32 { + let rows = |count: usize, each: f32, gap: f32| { + HEADER_H + count as f32 * each + count.saturating_sub(1) as f32 * gap + 2. * BODY_PAD + }; + match body { + Body::None => HEADER_H, + Body::Pills(pills) => rows(pills.len(), PILL_H, PILL_GAP), + Body::Conditions(list) => rows(list.len(), LINE_H, LINE_GAP), + Body::Lines(lines) => { + let count: usize = lines.iter().map(|text| line_count(text)).sum(); + rows(count, LINE_H, LINE_GAP) + } + } +} + +fn arrange(root: AlgebraNode) -> Layout { + fn place( + node: &AlgebraNode, + up: Option<(usize, usize)>, + next: &mut f32, + out: &mut Layout, + depths: &mut Vec, + ) -> usize { + let ix = out.flat.len(); + let body = body_of(node); + let height = height_of(&body); + let depth = up.map_or(0, |(parent, _)| depths[parent] + 1); + out.flat.push(Flat { node: shallow(node), body, up }); + out.boxes.push((0., 0., height)); + depths.push(depth); + let children: Vec = + node.children.iter().enumerate().map(|(n, child)| place(child, Some((ix, n)), next, out, depths)).collect(); + let x = match (children.first(), children.last()) { + (Some(&first), Some(&last)) => (out.boxes[first].0 + out.boxes[last].0) / 2., + _ => { + *next += NODE_W + GAP_X; + *next - NODE_W - GAP_X + } + }; + out.boxes[ix].0 = x; + out.edges.extend(children.into_iter().map(|child| (ix, child))); + ix + } + let root = Rc::new(root); + let mut out = Layout { root: root.clone(), flat: vec![], boxes: vec![], edges: vec![], width: 0., height: 0. }; + let mut depths = vec![]; + place(&root, None, &mut 0., &mut out, &mut depths); + // A row of the graph is as tall as its tallest box. + let mut tall = vec![0f32; depths.iter().max().map_or(0, |d| d + 1)]; + for (ix, &depth) in depths.iter().enumerate() { + tall[depth] = tall[depth].max(out.boxes[ix].2); + } + let mut tops = vec![]; + let mut y = MARGIN; + for height in &tall { + tops.push(y); + y += height + GAP_Y; + } + for (ix, &depth) in depths.iter().enumerate() { + out.boxes[ix].0 += MARGIN; + out.boxes[ix].1 = tops[depth]; + } + out.width = out.boxes.iter().fold(0f32, |w, (x, ..)| w.max(*x)) + NODE_W + MARGIN; + out.height = out.boxes.iter().fold(0f32, |h, (_, y, height)| h.max(y + height)) + MARGIN; + out +} + +// The body under the header, centred. +fn body_element(body: &Body, ix: usize, theme: &Theme) -> Option { + let code = |text: String, lines: usize| { + div().min_w_0().font_family(theme.mono_font_family.clone()).text_size(TEXT_XS).line_clamp(lines).child(text) + }; + let column = + |gap: f32| v_flex().flex_1().min_h_0().justify_center().gap(rems(gap)).px(rems(0.615)).py(rems(BODY_PAD)); + let element = match body { + Body::None => return None, + Body::Pills(rows) => column(PILL_GAP).children(rows.iter().enumerate().map(|(r, row)| { + h_flex().flex_none().gap(rems(PILL_GAP)).children(row.iter().enumerate().map(|(c, label)| { + let more = is_count(label); + div() + .debug_selector(move || format!("ra-pill-{ix}-{r}-{c}")) + .flex_none() + .h(rems(PILL_H)) + .px(rems(0.538)) + .flex() + .items_center() + .max_w(rems(INNER_W)) + .rounded(rems(PILL_H / 2.)) + .border_1() + .border_color(theme.border) + .bg(if more { theme.background } else { theme.secondary }) + .text_size(TEXT_XS) + .when(more, |el| el.text_color(theme.muted_foreground)) + .truncate() + .child(label.clone()) + })) + })), + // Never shrunk, or line_clamp cuts descenders like `_`. + Body::Lines(lines) => column(LINE_GAP).children(lines.iter().enumerate().map(|(n, text)| { + code(text.clone(), line_count(text)).flex_none().debug_selector(move || format!("ra-code-{ix}-{n}")) + })), + Body::Conditions(list) => column(LINE_GAP).children(list.iter().enumerate().map(|(row, text)| { + h_flex() + .flex_none() + .gap(rems(0.385)) + .child( + div() + .flex_none() + .w(rems(AND_W)) + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_2XS) + .text_color(theme.muted_foreground) + .child(if row > 0 { "AND" } else { "" }), + ) + .child(code(text.clone(), 1).flex_1().debug_selector(move || format!("ra-code-{ix}-{row}"))) + })), + }; + Some(element.into_any_element()) +} + +// A child-to-parent curve in rems, and its arrowhead's back corners. +struct EdgePath { + points: [(f32, f32); 4], + head: [(f32, f32); 2], +} + +impl Layout { + fn edge_path(&self, parent: usize, child: usize) -> EdgePath { + let (from, to) = (self.boxes[child], self.boxes[parent]); + let (x1, y1, x2, y2) = (from.0 + NODE_W / 2., from.1, to.0 + NODE_W / 2., to.1 + to.2); + let reach = (y1 - y2) / 2.; + EdgePath { + points: [(x1, y1), (x1, y1 - reach), (x2, y2 + reach), (x2, y2)], + head: [(x2 - 0.346, y2 + 0.692), (x2 + 0.346, y2 + 0.692)], + } + } +} + +// A line from each operator up to the one that reads it, with an arrowhead where it arrives. +fn paint_edges(layout: &Layout, color: Hsla, bounds: Bounds, window: &mut Window) { + let rem = window.rem_size(); + let at = |(x, y): (f32, f32)| point(bounds.left() + rem * x, bounds.top() + rem * y); + for &(parent, child) in &layout.edges { + let EdgePath { points: [start, c1, c2, end], head } = layout.edge_path(parent, child); + let mut path = PathBuilder::stroke(px(1.5)); + path.move_to(at(start)); + path.cubic_bezier_to(at(end), at(c1), at(c2)); + if let Ok(path) = path.build() { + window.paint_path(path, color); + } + let mut arrow = PathBuilder::fill(); + arrow.move_to(at(end)); + head.into_iter().for_each(|corner| arrow.line_to(at(corner))); + arrow.close(); + if let Ok(arrow) = arrow.build() { + window.paint_path(arrow, color); + } + } +} + +// What a node's header says: an operator's name in the locale, or the table as written. +fn title(node: &AlgebraNode, cx: &App) -> String { + match node.symbol.is_empty() { + true => node.detail.clone(), + false => t(cx, &format!("algebra.ops.{}", op(node.symbol))).to_string(), + } +} + +// Nodes whose title, condition or items hold `query`: whole matches first, then leading, then anywhere. +fn find(flat: &[Flat], titles: &[String], query: &str) -> Vec { + let query = query.trim().to_lowercase(); + if query.is_empty() { + return Vec::new(); + } + let mut hits: Vec<(u8, usize)> = flat + .iter() + .zip(titles) + .enumerate() + .filter_map(|(ix, (flat, title))| { + let node = &flat.node; + let items = node.items.iter().flat_map(|item| [item.label.as_str(), item.expr.as_str()]); + let rank = [title.as_str(), node.detail.as_str()] + .into_iter() + .chain(items) + .filter_map(|text| substring_rank(text, &query)) + .min()?; + Some((rank, ix)) + }) + .collect(); + hits.sort(); + hits.into_iter().map(|(_, ix)| ix).collect() +} + +// The search box's placeholder, with the operator and table counts. +fn search_hint(layout: &Layout, cx: &App) -> SharedString { + let operators = layout.flat.iter().filter(|flat| !flat.node.symbol.is_empty()).count(); + let tables = layout.flat.iter().filter(|flat| flat.node.table.is_some()).count(); + let operators = t_count(cx, "algebra.operators", operators as i64, &[]); + let tables = t_count(cx, "erDiagram.tables", tables as i64, &[]); + format!("{} ({operators} · {tables})", t(cx, "algebra.search")).into() +} + +// The name an operator goes by in the locale. +fn op(symbol: &str) -> &'static str { + match symbol { + "σ" => "select", + "π" => "project", + "⋈" => "join", + "×" => "cross", + "γ" => "group", + "τ" => "sort", + "limit" => "limit", + "δ" => "distinct", + "∪" => "union", + "∩" => "intersect", + "−" => "except", + "ρ" => "rename", + _ => "table", + } +} + +// A symbol takes its colour from the theme, and nothing else is coloured until it's picked. `base` is the theme's +// warning, primary, success and muted colours. +fn tone(symbol: &str, base: [Hsla; 4]) -> Hsla { + match op(symbol) { + "select" => base[0], + "project" => base[1], + "join" | "cross" => base[2], + _ => base[3], + } +} + +fn palette(cx: &App) -> [Hsla; 4] { + let theme = cx.theme(); + [theme.warning, theme.primary, theme.success, theme.muted_foreground] +} + +// The schema a table is qualified with, unless T-SQL's db..t leaves it out. +fn qualifier(table: &TableRef) -> Option<&str> { + let parts = &table.parts; + parts.len().checked_sub(2).map(|ix| parts[ix].as_str()).filter(|schema| !schema.is_empty()) +} + +// The schema and name, as loaded, of the table `table` stands for. +fn find_table(cx: &App, connection_id: &str, table: &TableRef) -> Option<(String, String)> { + let (name, schema) = (table.parts.last()?, qualifier(table)); + let loaded = schema::get(cx, connection_id)?; + loaded.loaded_tables().into_iter().find_map(|(listed, tables)| { + if schema.is_some_and(|wanted| !wanted.eq_ignore_ascii_case(listed)) { + return None; + } + let found = tables.iter().find(|t| t.name.eq_ignore_ascii_case(name))?; + Some((listed.to_string(), found.name.clone())) + }) +} + +fn table_columns(cx: &App, connection_id: &str, table: &TableRef) -> Option> { + let (schema, table) = find_table(cx, connection_id, table)?; + let columns = schema::get(cx, connection_id)?.columns(&schema, &table)?; + Some(columns.iter().map(|c| (c.name.clone(), c.data_type.clone())).collect()) +} + +// The columns that come out of an operator, with their types. +#[derive(IntoElement)] +struct Preview { + symbol: &'static str, + title: SharedString, + detail: String, + tone: Hsla, + dialect: Option, + columns: Vec, + qualified: bool, + more: Option, + empty: SharedString, +} + +impl Preview { + fn new(node: &AlgebraNode, connection: &ConnectionConfig, tone: Hsla, title: SharedString, cx: &App) -> Self { + let lookup = |table: &TableRef| table_columns(cx, &connection.id, table); + let columns = columns(node, &lookup); + let tables: HashSet = + columns.iter().filter(|c| !c.table.is_empty()).map(|c| c.table.to_lowercase()).collect(); + let hidden = columns.len().saturating_sub(PREVIEW_COLUMNS); + // What a projection, grouping or sort lists is already in the node. + let says_more = !node.symbol.is_empty() && !matches!(node.symbol, "π" | "γ" | "τ"); + Self { + symbol: node.symbol, + title, + detail: if says_more { node.detail.clone() } else { String::new() }, + tone, + dialect: connection.driver.dialect(), + qualified: tables.len() > 1, + columns, + more: (hidden > 0).then(|| t_count(cx, "algebra.moreColumns", hidden as i64, &[])), + empty: t(cx, "algebra.noColumns"), + } + } +} + +impl RenderOnce for Preview { + fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let rows = self.columns.iter().take(PREVIEW_COLUMNS).enumerate().map(|(ix, column)| { + let table = (self.qualified && !column.table.is_empty()).then(|| format!("{}.", column.table)); + h_flex() + .debug_selector(move || format!("ra-preview-row-{ix}")) + .h(rems(PREVIEW_ROW_H)) + .px(rems(0.615)) + .gap(rems(0.462)) + .when(ix > 0, |el| el.border_t_1().border_color(theme.border.opacity(0.5))) + .child( + h_flex() + .flex_1() + .min_w_0() + .children(table.map(|table| { + div() + .flex_none() + .max_w(rems(6.154)) + .truncate() + .text_color(theme.muted_foreground) + .child(table) + })) + .child(div().min_w_0().truncate().child(column.name.clone())), + ) + .child( + div() + .flex_none() + .max_w(rems(7.692)) + .truncate() + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .child(display_type(self.dialect, &column.data_type)), + ) + }); + let list = match self.columns.is_empty() { + true => div().text_size(TEXT_XS).text_color(theme.muted_foreground).child(self.empty).into_any_element(), + false => v_flex() + .overflow_hidden() + .rounded(RADIUS) + .border_1() + .border_color(theme.border) + .children(rows) + .into_any_element(), + }; + v_flex() + .debug_selector(|| "ra-preview".into()) + .w(rems(PREVIEW_W + 2. * PREVIEW_PAD)) + .gap(rems(0.615)) + .p(rems(PREVIEW_PAD)) + .bg(theme.popover) + .border_1() + .border_color(theme.border) + .rounded(RADIUS) + .shadow_md() + .text_size(TEXT_SM) + .child( + h_flex() + .gap(rems(0.462)) + .child(match self.symbol.is_empty() { + true => div().child(Icon::new(Lucide::Table2).size(ICON_XS).text_color(theme.muted_foreground)), + false => div().font_semibold().text_color(self.tone).child(self.symbol), + }) + .child(div().flex_1().min_w_0().truncate().font_semibold().child(self.title)), + ) + .when(!self.detail.is_empty(), |el| { + el.child( + div() + .w_full() + .line_clamp(3) + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .child(self.detail), + ) + }) + .child(list) + .children(self.more.map(|more| div().text_size(TEXT_XS).text_color(theme.muted_foreground).child(more))) + } +} + +// A statement as relational algebra, in its query tab's results. +pub struct AlgebraGraph { + connection: ConnectionConfig, + focus: FocusHandle, + layout: Rc, + selected: Option, + viewport: Viewport, + search: Search, + // Each table node's loaded schema and name. + tables: Vec>, + // Table nodes with size estimates, to redraw as more arrive. + sized: usize, + // The operator the pointer is on, while its preview waits to show. + hover: Option<(usize, Task<()>)>, + preview: Option, + _subscriptions: Vec, +} + +impl EventEmitter for AlgebraGraph {} + +impl AlgebraGraph { + pub(crate) fn new( + connection: ConnectionConfig, + root: AlgebraNode, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let layout = arrange(root); + let hint = search_hint(&layout, cx); + let (search, searching) = + Search::new(hint, |this: &mut Self| &mut this.search, Self::rank, Self::show, window, cx); + let subscriptions = vec![ + searching, + cx.observe_global_in::(window, |this, window, cx| { + this.search.set_placeholder(search_hint(&this.layout, cx), window, cx); + // Operators are found by their names in the language. + let matches = this.rank(this.search.query(), cx); + this.search.rematch(matches); + cx.notify(); + }), + cx.observe_global::(|this, cx| { + let sized = this.resolve(cx); + if sized != this.sized || this.preview.is_some() { + this.sized = sized; + cx.notify(); + } + }), + ]; + schema::ensure_loaded(&connection.id, connection.driver.clone(), cx); + let tables = vec![None; layout.flat.len()]; + let mut graph = Self { + connection, + focus: cx.focus_handle(), + viewport: Viewport::new(layout.width, layout.height), + layout: Rc::new(layout), + selected: None, + search, + tables, + sized: 0, + hover: None, + preview: None, + _subscriptions: subscriptions, + }; + graph.sized = graph.resolve(cx); + graph + } + + // Finds table nodes and loads their columns and estimates; returns how many are sized. + fn resolve(&mut self, cx: &mut Context) -> usize { + let (id, layout) = (self.connection.id.clone(), self.layout.clone()); + let mut sized = 0; + let mut unknown = vec![]; + for (ix, flat) in layout.flat.iter().enumerate() { + let Some(table) = &flat.node.table else { continue }; + let listed = |schema: &str| schema::get(cx, &id).is_some_and(|entry| entry.tables(schema).is_some()); + if self.tables[ix].as_ref().is_some_and(|(schema, _)| !listed(schema)) { + self.tables[ix] = None; + } + if self.tables[ix].is_none() { + self.tables[ix] = find_table(cx, &id, table); + match &self.tables[ix] { + // The schema cache keeps the load going. + Some((schema, name)) => drop(schema::columns(&id, schema, name, cx)), + None => unknown.extend(qualifier(table).map(str::to_string)), + } + } + if let Some((schema, _)) = &self.tables[ix] { + schema::load_sizes(&id, schema, cx); + sized += usize::from(schema::get(cx, &id).is_some_and(|entry| entry.sizes_loaded(schema))); + } + } + schema::load_named_schemas(&id, &unknown, cx); + sized + } + + // A table's estimated rows or a VALUES count, abbreviated. + fn rows_estimate(&self, ix: usize, cx: &App) -> Option { + if let Some(rows) = self.layout.flat.get(ix)?.node.rows { + return Some(compact(cx, rows as i64)); + } + let (schema, name) = self.tables.get(ix)?.as_ref()?; + let rows = schema::get(cx, &self.connection.id)?.size(schema, name)?.rows?; + Some(compact(cx, rows)) + } + + fn titles(&self, cx: &App) -> Vec { + self.layout.flat.iter().map(|flat| title(&flat.node, cx)).collect() + } + + fn rank(&self, query: &str, cx: &App) -> Vec { + find(&self.layout.flat, &self.titles(cx), query) + } + + fn show(&mut self, ix: usize, window: &Window, _: &mut Context) { + if let Some(&(x, y, height)) = self.layout.boxes.get(ix) { + self.viewport.centre_on((x + NODE_W / 2., y + height / 2.), window.rem_size()); + } + } + + fn viewport(this: &mut Self) -> &mut Viewport { + &mut this.viewport + } + + // The operator, lit in its own colour here and in the query. Picking it again lets go. + fn select(&mut self, ix: Option, cx: &mut Context) { + self.selected = if self.selected == ix { None } else { ix }; + let base = palette(cx); + let picked = self.selected.map(|ix| &self.layout.flat[ix].node); + let range = picked.and_then(|node| node.span.clone()); + cx.emit(AlgebraEvent::Reveal { range, color: picked.map_or(base[3], |node| tone(node.symbol, base)) }); + cx.notify(); + } + + // Another database finds the tables again. + pub(crate) fn set_connection(&mut self, connection: ConnectionConfig, cx: &mut Context) { + if connection.id != self.connection.id { + self.tables.fill(None); + } + self.connection = connection; + self.sized = self.resolve(cx); + cx.notify(); + } + + // The query dropped this graph's mark, as its caret moved on. + pub(crate) fn let_go(&mut self, cx: &mut Context) { + if self.selected.take().is_some() { + cx.notify(); + } + } + + #[cfg(test)] + pub(crate) fn selected(&self) -> Option { + self.selected + } + + // The preview waits for the pointer to rest on an operator, and leaves with it. + fn hover(&mut self, ix: usize, hovered: bool, cx: &mut Context) { + if hovered { + let wait = cx.spawn(async move |this, cx| { + cx.background_executor().timer(PREVIEW_DELAY).await; + let _ = this.update(cx, |this, cx| { + if this.hover.as_ref().is_some_and(|(at, _)| *at == ix) { + this.preview = Some(ix); + cx.notify(); + } + }); + }); + self.hover = Some((ix, wait)); + if self.preview.take().is_some() { + cx.notify(); + } + return; + } + if self.hover.as_ref().is_some_and(|(at, _)| *at == ix) { + self.hover = None; + } + if self.preview == Some(ix) { + self.preview = None; + cx.notify(); + } + } + + // Where node `ix` is in the window, as zoomed and scrolled. + fn node_bounds(&self, ix: usize, rem: Pixels) -> Option> { + let &(x, y, height) = self.layout.boxes.get(ix)?; + let scale = rem * self.viewport.zoom; + Some(Bounds::new(self.viewport.in_window((x, y), rem), size(scale * NODE_W, scale * height))) + } + + // Beside its operator and outside the zoom, so it never covers the node it lists. + fn preview_card(&self, window: &Window, cx: &App) -> Option> { + let ix = self.preview?; + let bounds = self.node_bounds(ix, window.rem_size())?; + // A tab left with the pointer on a node never hears it leave. + if !bounds.contains(&window.mouse_position()) { + return None; + } + let node = &self.layout.flat[ix].node; + let tone = tone(node.symbol, palette(cx)); + let preview = Preview::new(self.layout.subtree(ix), &self.connection, tone, title(node, cx).into(), cx); + let gap = window.rem_size() * 0.615; + let place = Positioner::side(bounds).placement(Placement::Right).align(Align::Start).offset(gap); + Some(deferred(place.margin(gap).child(preview)).with_priority(1)) + } + + // The ER diagram's toolbar, less its keys-only toggle and its note on a cut diagram. + fn toolbar(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + let modifier = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl" }; + let search = self.search.field("algebra.noMatches", "ra-matches", window, cx); + h_flex() + .flex_none() + .h(STRIP) + .gap(rems(0.615)) + .px(rems(0.769)) + .bg(theme.sidebar) + .border_b_1() + .border_color(theme.border) + .child(div().flex_grow_1().flex_basis(rems(15.385)).min_w_0().child(search)) + .child(zoom::buttons("ra", &self.viewport, true, Self::viewport, cx)) + .child( + form::filter_button("ra-fit", Icon::new(Lucide::Scan)).tooltip(t(cx, "erDiagram.fitTooltip")).on_click( + cx.listener(|this, _, window, cx| { + this.viewport.fit(window.rem_size()); + cx.notify(); + }), + ), + ) + .child( + form::filter_button("ra-export", Icon::new(Lucide::Download)) + .tooltip(t(cx, "erDiagram.exportSvg")) + .on_click(cx.listener(|this, _, _, cx| this.export(cx))), + ) + .child(form::filter_button("ra-help", Icon::new(Lucide::CircleQuestionMark)).ghost().tooltip(t_with( + cx, + "algebra.hint", + &[("modifier", modifier)], + ))) + } + + // As drawn, in the theme's colours. + fn svg(&self, cx: &App) -> String { + let theme = cx.theme(); + let base = palette(cx); + let titles = self.titles(cx); + let tones = self.layout.flat.iter().map(|flat| tone(flat.node.symbol, base)).collect(); + let table_icon = icon_svg(Lucide::Table2); + let family = font(theme.font_family.clone()); + let semibold = Font { weight: FontWeight::SEMIBOLD, ..family.clone() }; + let widths = TextWidths::new(&[family, semibold, font(theme.mono_font_family.clone())], cx); + let measure = |text: &str, size: f32, heavy: bool| widths.of(usize::from(heavy), text, size); + let measure_code = |text: &str, size: f32| widths.of(2, text, size); + let look = svg::Look { + background: theme::opaque(theme.background), + header: theme.secondary, + border: theme.border, + text: theme.foreground, + muted: theme.muted_foreground, + edge: theme.muted_foreground.opacity(0.6), + tones, + table_icon: &table_icon, + mono: &theme.mono_font_family, + measure: &measure, + measure_code: &measure_code, + }; + let rows: Vec> = (0..self.layout.flat.len()).map(|ix| self.rows_estimate(ix, cx)).collect(); + svg::render(&self.layout, &titles, &rows, &look) + } + + fn export(&self, cx: &App) { + save_svg(self.svg(cx), &t(cx, "algebra.title"), cx); + } + + // Like an ER table: a header with the operator, and under it what it works on: pills where it lists things, else + // the condition or expression as code. + fn node(&self, ix: usize, tone: Hsla, cx: &mut Context) -> AnyElement { + let theme = cx.theme().clone(); + let flat = &self.layout.flat[ix]; + let node = &flat.node; + let (x, y, height) = self.layout.boxes[ix]; + let table = node.symbol.is_empty(); + let picked = self.selected == Some(ix); + let title = title(node, cx); + let rows = if table { self.rows_estimate(ix, cx) } else { None }; + // Hits are tinted, the one in view more; the rest fade. + let hit = self.search.matches.contains(&ix); + let border = match () { + _ if picked => tone, + _ if self.search.current() == Some(ix) => theme.primary, + _ if hit => theme.primary.opacity(0.5), + _ => theme.border, + }; + let faded = !self.search.matches.is_empty() && !hit && !picked; + // The kind of join sits in the header, and the body keeps the condition. + let tag = if node.symbol == "⋈" { join_parts(&node.detail).0.map(str::to_string) } else { None }; + let has_body = !matches!(flat.body, Body::None); + let header = h_flex() + .debug_selector(move || format!("ra-header-{ix}")) + // A table has no body, so its header takes all of the node inside the border. + .map(|el| if has_body { el.h(rems(HEADER_H)).flex_none() } else { el.flex_1().min_h_0() }) + .px(rems(0.615)) + .gap(rems(0.462)) + .bg(if picked { tone.opacity(0.14) } else { theme.secondary }) + .when(has_body, |el| el.border_b_1().border_color(if picked { tone.opacity(0.4) } else { theme.border })) + .child(match table { + true => div().child(Icon::new(Lucide::Table2).size(ICON_XS).text_color(theme.muted_foreground)), + false => div().flex_none().min_w(ICON_XS).font_semibold().text_color(tone).child(node.symbol), + }) + .child( + div() + .debug_selector(move || format!("ra-title-{ix}")) + .flex_1() + .min_w_0() + .truncate() + .font_semibold() + .child(title.clone()), + ) + .children( + rows.map(|rows| div().flex_none().text_size(TEXT_XS).text_color(theme.muted_foreground).child(rows)), + ) + .children(tag.map(|tag| { + div() + .flex_none() + .px(rems(0.462)) + .rounded(rems(PILL_H / 2.)) + .border_1() + .border_color(theme.border) + .bg(theme.background) + .text_size(TEXT_2XS) + .text_color(theme.muted_foreground) + .child(tag) + })); + let body = body_element(&flat.body, ix, &theme); + v_flex() + .id(("ra-node", ix)) + .debug_selector(move || format!("ra-node-{ix}")) + .absolute() + .left(rems(x)) + .top(rems(y)) + .w(rems(NODE_W)) + .h(rems(height)) + .overflow_hidden() + .rounded(RADIUS) + .border_1() + .border_color(border) + .bg(theme.background) + .when(faded, |el| el.opacity(FADED)) + .text_size(TEXT_SM) + .cursor_pointer() + .child(header) + .children(body) + .on_hover(cx.listener(move |this, hovered: &bool, _, cx| this.hover(ix, *hovered, cx))) + .on_click(cx.listener(move |this, _, _, cx| { + cx.stop_propagation(); + if !this.viewport.panned { + this.select(Some(ix), cx); + } + })) + .into_any_element() + } +} + +impl Render for AlgebraGraph { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + self.viewport.fit_once(window); + let layout = self.layout.clone(); + let base = palette(cx); + let edge = theme.muted_foreground.opacity(0.6); + let margin = self.viewport.margin(window.rem_size(), self.viewport.zoom); + let nodes: Vec = (0..layout.flat.len()) + .map(|ix| { + let tone = tone(layout.flat[ix].node.symbol, base); + self.node(ix, tone, cx) + }) + .collect(); + let content = div() + .relative() + .flex_none() + .ml(margin.x) + .mt(margin.y) + .w(rems(layout.width)) + .h(rems(layout.height)) + .child( + canvas(|_, _, _| {}, move |bounds, _, window, _| paint_edges(&layout, edge, bounds, window)) + .absolute() + .inset_0(), + ) + .children(nodes); + let area = zoom::area("ra-graph", &self.viewport, Self::viewport, cx) + .on_click(cx.listener(|this, _, _, cx| { + if !this.viewport.panned && this.selected.is_some() { + this.select(None, cx); + } + })) + .child(zoom::zoomed(self.viewport.zoom, content)); + v_flex().size_full().track_focus(&self.focus).bg(theme.background).child(self.toolbar(window, cx)).child( + div() + .relative() + .flex_1() + .min_h_0() + .child(area) + .child(zoom::wheel_zoom(Self::viewport, cx)) + .children(self.preview_card(window, cx)) + .hover_scrollbar(&self.viewport.scroll, ScrollbarAxis::Both), + ) + } +} + +// The query as a tree for this connection's dialect. +pub(crate) fn parse(sql: &str, connection: &ConnectionConfig) -> Result { + algebra(sql, connection.driver.dialect().unwrap_or(SqlDialect::Postgres)) +} + +pub(crate) fn report(error: AlgebraError, sql: &str, cx: &mut App) { + let message = match error { + AlgebraError::NotQuery => t(cx, "algebra.notQuery"), + AlgebraError::Syntax(at) => { + let line = sql.get(at..).and_then(|rest| rest.lines().next()).unwrap_or_default(); + let near: String = line.trim_end().chars().take(24).collect(); + match near.is_empty() { + true => t(cx, "algebra.syntaxEnd"), + false => t_with(cx, "algebra.syntax", &[("near", &near)]), + } + } + }; + toast::error(message, cx); +} + +#[cfg(test)] +mod tests { + use barsql_core::SqlDialect; + use barsql_sql::{Item, Source, algebra}; + + use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, point, px, size}; + + use super::{AlgebraGraph, PREVIEW_DELAY, arrange, find, join_parts, op, pill_rows}; + use crate::schema; + use crate::test_support::{Env, in_root, settle}; + + fn item(label: &str) -> Item { + Item { label: label.into(), expr: label.into(), source: Source::Expr } + } + + fn open<'a>(sql: &'static str, cx: &'a mut TestAppContext) -> (Env, &'a mut VisualTestContext) { + let env = Env::new(cx); + let (root, connection) = (algebra(sql, SqlDialect::Sqlite).unwrap(), env.connection.clone()); + let (_, cx) = in_root(cx, |window, cx| AlgebraGraph::new(connection, root, window, cx)); + cx.simulate_resize(size(px(1200.), px(800.))); + (env, cx) + } + + fn draw(cx: &mut VisualTestContext) { + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + + #[test] + fn parents_sit_between_their_children() { + let join = algebra("SELECT * FROM a JOIN b ON a.id = b.id", SqlDialect::Sqlite).unwrap(); + let layout = arrange(join); + let find = |name: &str| layout.flat.iter().position(|f| f.node.detail == name).unwrap(); + let join_ix = layout.flat.iter().position(|f| f.node.symbol == "⋈").unwrap(); + let (a, b) = (layout.boxes[find("a")], layout.boxes[find("b")]); + assert_eq!(layout.boxes[join_ix].0, (a.0 + b.0) / 2.); + assert!(layout.boxes[join_ix].1 < a.1); + } + + // A node's border is drawn inside its height, which mustn't push what it holds off centre. + #[gpui_kit::test] + fn pills_and_titles_sit_in_the_middle_of_their_rows(cx: &mut TestAppContext) { + let sql = "SELECT t.id, t.name FROM things t JOIN things u ON u.id = t.id WHERE t.id > 1 AND u.name = 'x'"; + let (_env, cx) = open(sql, cx); + let mut bounds = |selector: &'static str| { + draw(cx); + cx.debug_bounds(selector).unwrap_or_else(|| panic!("{selector} is not drawn")) + }; + let (node, header, pill) = (bounds("ra-node-0"), bounds("ra-header-0"), bounds("ra-pill-0-0-0")); + let (above, below) = (pill.top() - header.bottom(), node.bottom() - px(1.) - pill.bottom()); + assert!((above - below).abs() < px(0.5), "{above:?} above the pill, {below:?} below it"); + let (leaf, title) = (bounds("ra-node-3"), bounds("ra-title-3")); + assert!((leaf.center().y - title.center().y).abs() < px(0.5), "{title:?} in {leaf:?}"); + let (join_line, condition) = (bounds("ra-code-2-0"), bounds("ra-code-1-0")); + assert_eq!(join_line.size.height, condition.size.height, "a join's line keeps its full height"); + } + + #[test] + fn search_finds_tables_conditions_and_names_best_first() { + let sql = "SELECT u.name FROM users u JOIN user_roles r ON r.user_id = u.id WHERE u.active"; + let layout = arrange(algebra(sql, SqlDialect::Postgres).unwrap()); + let titles: Vec = layout + .flat + .iter() + .map(|f| if f.node.symbol.is_empty() { f.node.detail.clone() } else { op(f.node.symbol).to_string() }) + .collect(); + let found = |query: &str| { + find(&layout.flat, &titles, query).into_iter().map(|ix| titles[ix].as_str()).collect::>() + }; + assert_eq!(found("USERS U"), ["users u"]); + assert_eq!(found("user"), ["users u", "user_roles r", "join"]); + assert_eq!(found("active"), ["select"]); + assert!(found(" ").is_empty()); + } + + #[test] + fn a_join_header_takes_kinds_of_more_than_one_word() { + assert_eq!(join_parts("CROSS APPLY"), (Some("CROSS APPLY"), "")); + assert_eq!(join_parts("LEFT ON a.id = b.id"), (Some("LEFT"), "a.id = b.id")); + assert_eq!(join_parts("ON a = b"), (None, "a = b")); + assert_eq!(join_parts("LEFTOVER"), (None, "LEFTOVER")); + } + + #[test] + fn pills_wrap_into_rows_and_count_what_does_not_fit() { + assert_eq!(pill_rows(&[item("a"), item("b"), item("c")]), vec![vec!["a", "b", "c"]]); + let many: Vec = (0..60).map(|n| item(&format!("column_{n}"))).collect(); + let rows = pill_rows(&many); + assert_eq!(rows.len(), 4, "capped"); + let shown = rows.iter().map(Vec::len).sum::() - 1; + assert_eq!(rows.last().and_then(|row| row.last()), Some(&format!("+{}", 60 - shown))); + // A last row of one wide pill gives it up, so the count fits. + let wide: Vec = (0..6).map(|n| item(&format!("{n}{}", "x".repeat(40)))).collect(); + let rows = pill_rows(&wide); + assert!(rows.iter().all(|row| super::row_width(row) <= super::INNER_W), "{rows:?}"); + assert_eq!(rows.last(), Some(&vec!["+3".to_string()])); + } + + #[test] + fn a_preview_reads_its_operator_with_what_is_under_it() { + let layout = + arrange(algebra("SELECT a FROM (SELECT a FROM t) s JOIN u ON u.a = s.a", SqlDialect::Postgres).unwrap()); + for (ix, flat) in layout.flat.iter().enumerate() { + let subtree = layout.subtree(ix); + assert_eq!((subtree.symbol, &subtree.detail), (flat.node.symbol, &flat.node.detail)); + assert!(flat.node.children.is_empty()); + } + assert_eq!(layout.subtree(0), &*layout.root); + } + + #[gpui_kit::test] + fn a_rested_on_operator_lists_its_columns_beside_it(cx: &mut TestAppContext) { + let (env, cx) = open("SELECT * FROM things WHERE id > 1", cx); + let id = env.connection.id.clone(); + settle(cx, |cx| cx.update(|_, cx| schema::get(cx, &id).and_then(|s| s.columns("main", "things")).is_some())); + draw(cx); + let node = cx.debug_bounds("ra-node-0").expect("the projection is drawn"); + cx.simulate_mouse_move(node.center(), None, Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("ra-preview").is_none(), "it waits for the pointer to rest"); + cx.executor().advance_clock(PREVIEW_DELAY); + draw(cx); + draw(cx); + let card = cx.debug_bounds("ra-preview").expect("the preview shows"); + assert!(card.left() > node.right(), "{card:?} beside {node:?}"); + assert!((card.top() - node.top()).abs() < px(1.), "{card:?} level with {node:?}"); + let rows = ["ra-preview-row-0", "ra-preview-row-1", "ra-preview-row-2"]; + let drawn = rows.into_iter().filter(|row| cx.debug_bounds(row).is_some()).count(); + assert_eq!(drawn, 2, "id and name, nothing made up"); + cx.simulate_mouse_move(point(px(4.), px(796.)), None, Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("ra-preview").is_none(), "it leaves with the pointer"); + // Zoomed in until the graph scrolls, it still finds its node. + cx.simulate_resize(size(px(1200.), px(300.))); + draw(cx); + let zoom_in = cx.debug_bounds("ra-zoom-in").expect("the zoom buttons are drawn"); + for _ in 0..5 { + cx.simulate_click(zoom_in.center(), Modifiers::default()); + draw(cx); + } + let top = cx.debug_bounds("ra-node-0").expect("the projection is drawn"); + assert!(top.top() < zoom_in.bottom(), "{top:?} scrolled up under the toolbar"); + let node = cx.debug_bounds("ra-node-1").expect("the selection is drawn"); + cx.simulate_mouse_move(node.center(), None, Modifiers::default()); + cx.executor().advance_clock(PREVIEW_DELAY); + draw(cx); + draw(cx); + let card = cx.debug_bounds("ra-preview").expect("the preview shows when zoomed"); + assert!(card.left() > node.right(), "{card:?} beside {node:?}"); + assert!((card.top() - node.top().max(px(8.))).abs() < px(1.), "{card:?} level with {node:?}"); + } +} diff --git a/crates/barsql-ui/src/algebra_graph/svg.rs b/crates/barsql-ui/src/algebra_graph/svg.rs new file mode 100644 index 0000000..c008fce --- /dev/null +++ b/crates/barsql-ui/src/algebra_graph/svg.rs @@ -0,0 +1,315 @@ +// The graph as a standalone SVG, from the canvas' layout. + +use std::fmt::Write as _; + +use gpui_kit::Hsla; + +use super::{ + AND_W, BODY_PAD, Body, Flat, HEADER_H, INNER_W, LINE_GAP, LINE_H, Layout, NODE_W, PILL_GAP, PILL_H, is_count, + join_parts, line_count, +}; +use crate::er_diagram::svg::{FONT, REM, escape, fit, hex, inner, paint}; + +// The canvas' spacing and type sizes in px at 100%. +const PAD: f32 = 0.615 * REM; +const GAP: f32 = 0.462 * REM; +const ICON: f32 = 0.923 * REM; +const TITLE: f32 = 12.; +const SMALL: f32 = 11.; +const TINY: f32 = 10.; + +pub struct Look<'a> { + pub background: Hsla, + pub header: Hsla, + pub border: Hsla, + pub text: Hsla, + pub muted: Hsla, + pub edge: Hsla, + // Each node's symbol colour, in the layout's order. + pub tones: Vec, + pub table_icon: &'a str, + pub mono: &'a str, + // A text's width in px at a size, semibold or not, and in the code font. + pub measure: &'a dyn Fn(&str, f32, bool) -> f32, + pub measure_code: &'a dyn Fn(&str, f32) -> f32, +} + +pub fn render(layout: &Layout, titles: &[String], rows: &[Option], look: &Look) -> String { + let (width, height) = (layout.width * REM, layout.height * REM); + let mut out = String::new(); + let _ = write!( + out, + r#""# + ); + let _ = write!( + out, + r#"{}"#, + inner(look.table_icon) + ); + let _ = write!(out, r#""#, paint("fill", look.background)); + edges(&mut out, layout, look.edge); + for (ix, flat) in layout.flat.iter().enumerate() { + let tone = look.tones.get(ix).copied().unwrap_or(look.muted); + let title = titles.get(ix).map_or("", String::as_str); + let rows = rows.get(ix).and_then(Option::as_deref); + node(&mut out, ix, flat, layout.boxes[ix], (title, rows), tone, look); + } + out.push_str("\n"); + out +} + +fn edges(out: &mut String, layout: &Layout, color: Hsla) { + let px = |(x, y): (f32, f32)| (x * REM, y * REM); + for &(parent, child) in &layout.edges { + let edge = layout.edge_path(parent, child); + let [(x1, y1), (cx1, cy1), (cx2, cy2), (x2, y2)] = edge.points.map(px); + let [(lx, ly), (rx, ry)] = edge.head.map(px); + let stroke = paint("stroke", color); + let _ = write!( + out, + r#""# + ); + let _ = write!(out, r#""#, paint("fill", color)); + } +} + +// `says` is the header's title and, for a table, its row estimate. +fn node( + out: &mut String, + ix: usize, + flat: &Flat, + at: (f32, f32, f32), + says: (&str, Option<&str>), + tone: Hsla, + look: &Look, +) { + let (title, rows) = says; + let (x, y, w, h) = (at.0 * REM, at.1 * REM, NODE_W * REM, at.2 * REM); + let header = HEADER_H * REM; + let node = &flat.node; + // Clipped like the canvas' box, so the header's corners round with it. + let _ = write!( + out, + r#""# + ); + let _ = write!(out, r#""#, paint("fill", look.background)); + let _ = write!(out, r#""#, paint("fill", look.header)); + if !matches!(flat.body, Body::None) { + let _ = write!( + out, + r#""#, + y + header, + x + w, + y + header, + paint("stroke", look.border) + ); + } + let middle = y + header / 2.; + let mut left = x + PAD; + if node.symbol.is_empty() { + let _ = write!( + out, + r##""##, + middle - ICON / 2., + hex(look.muted) + ); + left += ICON + GAP; + } else { + text(out, left, middle + TITLE * 0.35, TITLE, tone, r#" font-weight="600""#, node.symbol); + left += (look.measure)(node.symbol, TITLE, true).max(ICON) + GAP; + } + let mut right = x + w - PAD; + if let Some(tag) = (node.symbol == "⋈").then(|| join_parts(&node.detail).0).flatten() { + let (tag_w, tag_h) = ((look.measure)(tag, TINY, false) + 2. * GAP, TINY + 6.); + let _ = write!( + out, + r#""#, + right - tag_w, + middle - tag_h / 2., + tag_h / 2., + paint("fill", look.background), + paint("stroke", look.border) + ); + text(out, right - tag_w / 2., middle + TINY * 0.35, TINY, look.muted, r#" text-anchor="middle""#, tag); + right -= tag_w + GAP; + } + if let Some(rows) = rows { + text(out, right, middle + SMALL * 0.35, SMALL, look.muted, r#" text-anchor="end""#, rows); + right -= (look.measure)(rows, SMALL, false) + GAP; + } + let shown = fit(title, right - left, TITLE, true, look.measure); + text(out, left, middle + TITLE * 0.35, TITLE, look.text, r#" font-weight="600""#, &shown); + body(out, &flat.body, x, y + header + BODY_PAD * REM, look); + out.push_str(""); + // GPUI draws a box's border inside it, over what it holds. + let _ = write!( + out, + r#""#, + x + 0.5, + y + 0.5, + w - 1., + h - 1., + paint("stroke", look.border) + ); +} + +// What a node holds under its header, from `top`. +fn body(out: &mut String, body: &Body, x: f32, top: f32, look: &Look) { + let room = INNER_W * REM; + let mono = format!(r#" font-family="{}""#, escape(&format!("'{}', monospace", look.mono))); + let code_width = |body: &str, size: f32, _: bool| (look.measure_code)(body, size); + let line_step = (LINE_H + LINE_GAP) * REM; + let base_of = |line_top: f32| line_top + LINE_H * REM / 2. + SMALL * 0.35; + match body { + Body::None => {} + Body::Pills(rows) => { + let (pill_h, pill_pad) = (PILL_H * REM, 0.538 * REM); + for (row, labels) in rows.iter().enumerate() { + let row_top = top + row as f32 * (pill_h + PILL_GAP * REM); + let mut left = x + PAD; + for label in labels { + let more = is_count(label); + let wide = (look.measure)(label, SMALL, false) + 2. * pill_pad; + let pill_w = wide.min(room); + let _ = write!( + out, + r#""#, + pill_h / 2., + paint("fill", if more { look.background } else { look.header }), + paint("stroke", look.border) + ); + let shown = match wide > room { + true => fit(label, room - 2. * pill_pad, SMALL, false, look.measure), + false => label.clone(), + }; + let color = if more { look.muted } else { look.text }; + text(out, left + pill_pad, row_top + pill_h / 2. + SMALL * 0.35, SMALL, color, "", &shown); + left += pill_w + PILL_GAP * REM; + } + } + } + Body::Lines(texts) => { + let mut line_top = top; + for lines in texts { + for line in wrap(lines, room, line_count(lines), &|part| (look.measure_code)(part, SMALL)) { + let shown = fit(&line, room, SMALL, false, &code_width); + text(out, x + PAD, base_of(line_top), SMALL, look.text, &mono, &shown); + line_top += line_step; + } + } + } + Body::Conditions(list) => { + let and_w = AND_W * REM + 0.385 * REM; + for (row, condition) in list.iter().enumerate() { + let base = base_of(top + row as f32 * line_step); + if row > 0 { + text(out, x + PAD, base, TINY, look.muted, &mono, "AND"); + } + let shown = fit(condition, room - and_w, SMALL, false, &code_width); + text(out, x + PAD + and_w, base, SMALL, look.text, &mono, &shown); + } + } + } +} + +fn text(out: &mut String, x: f32, base: f32, size: f32, color: Hsla, extra: &str, body: &str) { + let _ = write!( + out, + r#"{}"#, + paint("fill", color), + escape(body) + ); +} + +// Up to `lines` lines of `room` px, broken at spaces; the last keeps the rest. +fn wrap(text: &str, room: f32, lines: usize, measure: &dyn Fn(&str) -> f32) -> Vec { + let mut out: Vec = vec![]; + let mut line = String::new(); + for word in text.split(' ') { + let longer = if line.is_empty() { word.to_string() } else { format!("{line} {word}") }; + if line.is_empty() || measure(&longer) <= room { + line = longer; + } else { + out.push(std::mem::replace(&mut line, word.to_string())); + } + } + out.push(line); + if out.len() > lines { + let rest = out.split_off(lines.saturating_sub(1)).join(" "); + out.push(rest); + } + out +} + +#[cfg(test)] +mod tests { + use barsql_core::SqlDialect; + use barsql_sql::algebra; + use gpui_kit::hsla; + + use super::*; + use crate::algebra_graph::arrange; + + #[test] + fn the_svg_draws_each_operator_what_it_holds_and_its_lines() { + let sql = "SELECT u.name, count(*) AS n FROM users u LEFT JOIN orders o ON o.user_id = u.id \ + WHERE u.active AND o.total > 100 GROUP BY u.name"; + let layout = arrange(algebra(sql, SqlDialect::Postgres).unwrap()); + let titles: Vec = layout + .flat + .iter() + .map(|flat| match flat.node.symbol.is_empty() { + true => flat.node.detail.clone(), + false => format!("op {}", flat.node.symbol), + }) + .collect(); + let gray = hsla(0., 0., 0.5, 1.); + let measure = |text: &str, size: f32, _: bool| text.chars().count() as f32 * size * 0.6; + let measure_code = |text: &str, size: f32| text.chars().count() as f32 * size * 0.6; + let icon = r#""#; + let look = Look { + background: gray, + header: gray, + border: gray, + text: gray, + muted: gray, + edge: gray.opacity(0.6), + tones: vec![], + table_icon: icon, + mono: "Fira Code", + measure: &measure, + measure_code: &measure_code, + }; + let rows: Vec> = + layout.flat.iter().map(|flat| (flat.node.detail == "users u").then(|| "1.2k".to_string())).collect(); + let svg = render(&layout, &titles, &rows, &look); + assert!(svg.starts_with("\n")); + for text in [ + ">users u<", + ">orders o<", + ">LEFT<", + ">o.user_id = u.id<", + ">AND<", + ">o.total > 100<", + ">n<", + ">u.name<", + ">1.2k<", + ] { + assert!(svg.contains(text), "{text}"); + } + assert_eq!(svg.matches(r##"href="#table""##).count(), 2, "an icon for each table"); + assert_eq!(svg.matches(r#"stroke-width="1.5""#).count(), layout.edges.len(), "a line for each edge"); + assert_eq!(svg.matches(r#" Z""#).count(), layout.edges.len(), "an arrowhead for each edge"); + assert!(svg.contains(r#""#), "the icon keeps its own path"); + assert!(svg.contains("font-family=\"'Fira Code', monospace\""), "code in the code font"); + } + + #[test] + fn code_wraps_onto_its_lines_and_the_last_takes_the_rest() { + let width = |text: &str| text.chars().count() as f32; + assert_eq!(wrap("aa bb cc", 5., 2, &width), ["aa bb", "cc"]); + assert_eq!(wrap("aa bb cc dd ee", 5., 2, &width), ["aa bb", "cc dd ee"]); + assert_eq!(wrap("aa bb", 10., 2, &width), ["aa bb"]); + assert_eq!(wrap("aaaaaaaaaa", 5., 1, &width), ["aaaaaaaaaa"]); + } +} diff --git a/crates/barsql-ui/src/assets.rs b/crates/barsql-ui/src/assets.rs index a1b4600..021985c 100644 --- a/crates/barsql-ui/src/assets.rs +++ b/crates/barsql-ui/src/assets.rs @@ -180,6 +180,12 @@ fn raster(svg: &'static [u8], pixels: Size, cx: &mut App) -> Optio pub struct AppAssets; +// An icon's SVG text, for an export. +pub(crate) fn icon_svg(name: Lucide) -> String { + let bytes = AppAssets.load(&name.path()).ok().flatten(); + bytes.map(|bytes| String::from_utf8_lossy(&bytes).into_owned()).unwrap_or_default() +} + impl AssetSource for AppAssets { fn load(&self, path: &str) -> Result>> { if let Some((_, bytes)) = ENGINES.iter().find(|(at, _)| *at == path) { diff --git a/crates/barsql-ui/src/command_palette.rs b/crates/barsql-ui/src/command_palette.rs index 59abe73..6dd6ecc 100644 --- a/crates/barsql-ui/src/command_palette.rs +++ b/crates/barsql-ui/src/command_palette.rs @@ -35,6 +35,7 @@ fn catalog(cx: &App) -> Vec<(String, Box)> { (item("shortcuts.items.runAll"), Box::new(RunAll)), (item("shortcuts.items.explainQuery"), Box::new(ExplainQuery)), (item("shortcuts.items.explainAnalyze"), Box::new(ExplainAnalyze)), + (item("shortcuts.items.showAlgebra"), Box::new(ShowAlgebra)), (item("editor.contextFormat"), Box::new(FormatQuery)), (item("editor.contextToggleComment"), Box::new(ToggleComment)), (item("editor.contextGoToDefinition"), Box::new(GoToDefinition)), diff --git a/crates/barsql-ui/src/er_diagram.rs b/crates/barsql-ui/src/er_diagram.rs index 850c331..77fcb13 100644 --- a/crates/barsql-ui/src/er_diagram.rs +++ b/crates/barsql-ui/src/er_diagram.rs @@ -1,26 +1,29 @@ mod layout; -mod svg; +pub(crate) mod search; +pub(crate) mod svg; #[cfg(test)] mod tests; -mod zoom; +pub(crate) mod zoom; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; +use std::sync::Arc; use barsql_app::{DiagramRef, EditorTab}; use barsql_core::{ColumnInfo, ConnectionConfig}; use barsql_sql::display_type; use gpui_kit::assets::IconName as Lucide; use gpui_kit::component::button::{Button, ButtonVariants}; -use gpui_kit::component::input::{InputEvent, InputState}; use gpui_kit::component::scroll::ScrollbarAxis; -use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, Selectable, Sizable, StyledExt, h_flex, v_flex}; +use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, Selectable, StyledExt, h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use self::layout::{BOX_W, ErTable, HEADER_H, Layout, ROW_H, Spot, arrange, find, key_count}; -use crate::assets::AppAssets; +use self::search::Search; +use self::zoom::Viewport; +use crate::assets::icon_svg; use crate::form::{self, ToolButton as _}; use crate::i18n::{I18n, compact, t, t_count, t_with}; use crate::schema; @@ -31,9 +34,7 @@ use crate::{file_dialogs, theme, toast}; // Tables a diagram loads. pub const MAX_TABLES: usize = 200; // Boxes away from the picked table fade to this. -const FADED: f32 = 0.3; -// A press that moves further pans, and doesn't count as a click. -const PAN_SLOP: Pixels = px(4.); +pub(crate) const FADED: f32 = 0.3; enum State { Loading, @@ -44,15 +45,42 @@ enum State { pub(crate) type OnOpen = Rc; -// A drag on the diagram pans it. GPUI draws a dragged value, so this one draws nothing. -struct Pan; +// Text widths as the canvas shapes them, fallback fonts included. +pub(crate) struct TextWidths { + text_system: Arc, + faces: Vec, + cache: RefCell>, +} + +impl TextWidths { + pub(crate) fn new(fonts: &[Font], cx: &App) -> Self { + let text_system = cx.text_system().clone(); + let faces = fonts.iter().map(|font| text_system.resolve_font(font)).collect(); + Self { text_system, faces, cache: RefCell::default() } + } -impl Render for Pan { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - Empty + pub(crate) fn of(&self, face: usize, text: &str, size: f32) -> f32 { + let mut cache = self.cache.borrow_mut(); + let shape = |ch| f32::from(self.text_system.layout_width(self.faces[face], px(size), ch)); + text.chars().map(|ch| *cache.entry((ch, face, size.to_bits())).or_insert_with(|| shape(ch))).sum() } } +// Asks where to save `text` as `name`.svg, and says how that went. +pub(crate) fn save_svg(text: String, name: &str, cx: &App) { + let picked = file_dialogs::pick_save_path(&format!("{name}.svg"), cx); + cx.spawn(async move |cx| { + let Some(path) = picked.await else { return }; + let file_name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); + let written = std::fs::write(&path, text); + cx.update(|cx| match written { + Ok(()) => toast::success(t_with(cx, "toast.savedFile", &[("fileName", &file_name)]), cx), + Err(error) => toast::error(format!("{}: {error}", t(cx, "errors.exportFailed")), cx), + }); + }) + .detach(); +} + // The tables of a schema and the keys between them, in a tab of their own. Drag to pan, ⌘ or Ctrl with the wheel, a // pinch or the buttons to zoom. Hovering a table previews its keys and a click keeps them lit; a double click opens // it. @@ -65,20 +93,10 @@ pub struct ErDiagram { total: usize, keys_only: bool, layout: Rc, - zoom: f32, - // Fitted once the viewport's size is known. - fitted: bool, + viewport: Viewport, hovered: Option, selected: Option, - search: Entity, - query: String, - matches: Vec, - hit: usize, - scroll: ScrollHandle, - // Where the pointer and the scroll were when a press started, for a drag to pan from, and whether it moved far - // enough to be a pan rather than a click. - pan: Option<(Point, Point)>, - panned: bool, + search: Search, // So only the row estimates' arrival redraws it, not every schema change. sized: bool, // Empty until the next frame builds it again, as the tables or the language changed. @@ -98,19 +116,10 @@ impl ErDiagram { cx: &mut Context, ) -> Self { let placeholder = t(cx, "erDiagram.search"); - let search = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder)); + let (search, searching) = + Search::new(placeholder, |this: &mut Self| &mut this.search, Self::rank, Self::show, window, cx); let subscriptions = vec![ - // The input also reports a change after Enter, with the same text, which mustn't start the hits over. - cx.subscribe_in(&search, window, |this, input, event: &InputEvent, window, cx| match event { - InputEvent::Change => { - let query = input.read(cx).value().to_string(); - if query != this.query { - this.find(query, window, cx); - } - } - InputEvent::PressEnter { shift, .. } => this.step_hit(if *shift { -1 } else { 1 }, window, cx), - _ => {} - }), + searching, cx.observe_global_in::(window, |this, _, cx| { this.placeholder_shown = SharedString::default(); cx.notify(); @@ -127,6 +136,7 @@ impl ErDiagram { } }), ]; + let layout = arrange(&[], false); Self { id, connection, @@ -135,18 +145,11 @@ impl ErDiagram { state: State::Loading, total: 0, keys_only: false, - layout: Rc::new(arrange(&[], false)), - zoom: 1., - fitted: false, + viewport: Viewport::new(layout.width, layout.height), + layout: Rc::new(layout), hovered: None, selected: None, search, - query: String::new(), - matches: Vec::new(), - hit: 0, - scroll: ScrollHandle::new(), - pan: None, - panned: false, sized: false, placeholder_shown: SharedString::default(), on_open, @@ -195,8 +198,7 @@ impl ErDiagram { self.total = total; self.placeholder_shown = SharedString::default(); self.state = State::Ready(Rc::new(tables)); - self.fitted = false; - self.relayout(); + self.relayout(true); } pub(crate) fn title(&self, cx: &App) -> SharedString { @@ -224,78 +226,39 @@ impl ErDiagram { window.focus(&self.focus, cx); } - fn relayout(&mut self) { + fn relayout(&mut self, refit: bool) { if let State::Ready(tables) = &self.state { self.layout = Rc::new(arrange(tables, self.keys_only)); + self.viewport.resize(self.layout.width, self.layout.height, refit); } } - fn content(&self, rem: Pixels, zoom: f32) -> Size { - size(rem * self.layout.width * zoom, rem * self.layout.height * zoom) - } - - // The empty room a diagram smaller than the viewport is centred in. - fn margin(&self, rem: Pixels, zoom: f32) -> Point { - let (view, content) = (self.scroll.bounds().size, self.content(rem, zoom)); - point(((view.width - content.width) / 2.).max(px(0.)), ((view.height - content.height) / 2.).max(px(0.))) - } - - // `anchor`, in the window, stays over the same part of the diagram. Without one, the middle of the view does. - fn zoom_to(&mut self, zoom: f32, anchor: Option>, window: &Window, cx: &mut Context) { - let zoom = zoom.clamp(zoom::MIN, zoom::MAX); - if (zoom - self.zoom).abs() < 1e-4 { - return; - } - let (view, rem) = (self.scroll.bounds(), window.rem_size()); - let anchor = anchor.map_or(point(view.size.width / 2., view.size.height / 2.), |at| at - view.origin); - let from = self.scroll.offset() + self.margin(rem, self.zoom); - let offset = zoom::anchored(from, anchor, self.zoom, zoom) - self.margin(rem, zoom); - self.zoom = zoom; - self.scroll.set_offset(offset); - cx.notify(); - } - - fn fit(&mut self, window: &Window, cx: &mut Context) { - self.zoom = zoom::fit(self.content(window.rem_size(), 1.), self.scroll.bounds().size); - self.scroll.set_offset(point(px(0.), px(0.))); - cx.notify(); + fn viewport(this: &mut Self) -> &mut Viewport { + &mut this.viewport } fn centre_on(&mut self, ix: usize, window: &Window) { - let Some(placed) = self.layout.boxes.get(ix) else { return }; - let scale = window.rem_size() * self.zoom; - let (x, y) = placed.center(); - let target = point(scale * x, scale * y); - let content = self.content(window.rem_size(), self.zoom); - self.scroll.set_offset(zoom::centred(target, self.scroll.bounds().size, content)); + if let Some(placed) = self.layout.boxes.get(ix) { + self.viewport.centre_on(placed.center(), window.rem_size()); + } } - fn find(&mut self, query: String, window: &Window, cx: &mut Context) { - let State::Ready(tables) = &self.state else { return }; - self.matches = find(tables, &query); - self.query = query; - self.hit = 0; - if let Some(&first) = self.matches.first() { - self.selected = Some(first); - self.centre_on(first, window); + fn rank(&self, query: &str, _: &App) -> Vec { + match &self.state { + State::Ready(tables) => find(tables, query), + _ => Vec::new(), } - cx.notify(); } - fn step_hit(&mut self, by: isize, window: &Window, cx: &mut Context) { - if self.matches.is_empty() { - return; - } - self.hit = (self.hit as isize + by).rem_euclid(self.matches.len() as isize) as usize; - let ix = self.matches[self.hit]; + // A search hit is picked as well as brought into view. + fn show(&mut self, ix: usize, window: &Window, _: &mut Context) { self.selected = Some(ix); self.centre_on(ix, window); - cx.notify(); } fn toggle_keys(&mut self, window: &Window, cx: &mut Context) { self.keys_only = !self.keys_only; - self.relayout(); + self.relayout(false); if let Some(ix) = self.selected { self.centre_on(ix, window); } @@ -315,25 +278,9 @@ impl ErDiagram { window.defer(cx, move |window, cx| on_open(name, window, cx)); } - fn pan_to(&mut self, position: Point, cx: &mut Context) { - let Some((start, offset)) = self.pan else { return }; - let moved = position - start; - self.panned |= moved.x.abs().max(moved.y.abs()) > PAN_SLOP; - self.scroll.set_offset(offset + moved); - cx.notify(); - } - fn toolbar(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme().clone(); let ready = matches!(self.state, State::Ready(_)); - let found = match (!self.query.trim().is_empty(), self.matches.len()) { - (false, _) => None, - (true, 0) => Some(t(cx, "erDiagram.noMatches")), - (true, count) => { - let (index, count) = ((self.hit + 1).to_string(), count.to_string()); - Some(t_with(cx, "erDiagram.matches", &[("index", &index), ("count", &count)])) - } - }; // Only a cut diagram has something to say along the toolbar. How to get around waits behind the "?". let note = (self.total > MAX_TABLES).then(|| { let (shown, total) = (MAX_TABLES.to_string(), self.total.to_string()); @@ -341,16 +288,7 @@ impl ErDiagram { }); let modifier = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl" }; let hint = t_with(cx, "erDiagram.hint", &[("modifier", modifier)]); - // The hit count sits inside the field, so typing moves nothing. - let search = form::search_input(&self.search, window, cx).when_some(found, |input, found| { - input.suffix( - div() - .debug_selector(|| "er-matches".into()) - .text_size(TEXT_XS) - .text_color(theme.muted_foreground) - .child(found), - ) - }); + let search = self.search.field("erDiagram.noMatches", "er-matches", window, cx); h_flex() .debug_selector(|| "er-toolbar".into()) .flex_none() @@ -386,13 +324,16 @@ impl ErDiagram { .tooltip(t(cx, "erDiagram.keysOnlyTooltip")) .on_click(cx.listener(|this, _, window, cx| this.toggle_keys(window, cx))), ) - .child(self.zoom_buttons(ready, cx)) + .child(zoom::buttons("er", &self.viewport, ready, Self::viewport, cx)) .child( form::filter_button("er-fit", Icon::new(Lucide::Scan)) .debug_selector(|| "er-fit".into()) .disabled(!ready) .tooltip(t(cx, "erDiagram.fitTooltip")) - .on_click(cx.listener(|this, _, window, cx| this.fit(window, cx))), + .on_click(cx.listener(|this, _, window, cx| { + this.viewport.fit(window.rem_size()); + cx.notify(); + })), ) .child( form::filter_button("er-export", Icon::new(Lucide::Download)) @@ -428,35 +369,14 @@ impl ErDiagram { link: theme.primary, edge: theme.muted_foreground.opacity(0.6), }; - let icon = |name: Lucide| { - AppAssets.load(&name.path()).ok().flatten().map(|bytes| String::from_utf8_lossy(&bytes).into_owned()) - }; - let (key, link) = (icon(Lucide::KeyRound).unwrap_or_default(), icon(Lucide::Link).unwrap_or_default()); - let text_system = cx.text_system().clone(); - let regular = text_system.resolve_font(&font(theme.font_family.clone())); - let bold = text_system.resolve_font(&Font { weight: FontWeight::SEMIBOLD, ..font(theme.font_family.clone()) }); - // Shaped with fallback fonts, as the canvas is, so a character Inter lacks still has a width. - let widths = RefCell::new(HashMap::new()); - let measure = |text: &str, size: f32, heavy: bool| { - let id = if heavy { bold } else { regular }; - let mut widths = widths.borrow_mut(); - let width = |ch| f32::from(text_system.layout_width(id, px(size), ch)); - text.chars().map(|ch| *widths.entry((ch, heavy, size.to_bits())).or_insert_with(|| width(ch))).sum() - }; + let (key, link) = (icon_svg(Lucide::KeyRound), icon_svg(Lucide::Link)); + let family = font(theme.font_family.clone()); + let widths = TextWidths::new(&[family.clone(), Font { weight: FontWeight::SEMIBOLD, ..family }], cx); + let measure = |text: &str, size: f32, heavy: bool| widths.of(usize::from(heavy), text, size); let look = svg::Look { palette, icons: [&key, &link], measure: &measure }; let rows = |table: &str| self.rows_estimate(table, cx); let text = svg::render(tables, &self.layout, self.keys_only, self.connection.driver.dialect(), &look, rows); - let picked = file_dialogs::pick_save_path(&format!("{}.svg", self.schema), cx); - cx.spawn(async move |_, cx| { - let Some(path) = picked.await else { return }; - let file_name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); - let written = std::fs::write(&path, text); - cx.update(|cx| match written { - Ok(()) => toast::success(t_with(cx, "toast.savedFile", &[("fileName", &file_name)]), cx), - Err(error) => toast::error(format!("{}: {error}", t(cx, "errors.exportFailed")), cx), - }); - }) - .detach(); + save_svg(text, &self.schema, cx); } // The counts ride in the placeholder, so they never crowd what's typed. @@ -469,49 +389,6 @@ impl ErDiagram { format!("{find} ({tables} · {keys})").into() } - // Joined as Explain and its menu are. The zoom keeps one width, so nothing shifts as it changes. - fn zoom_buttons(&self, ready: bool, cx: &mut Context) -> impl IntoElement + use<> { - let percent = format!("{}%", (self.zoom * 100.).round()); - h_flex() - .child( - form::filter_button("er-zoom-out", Icon::new(IconName::Minus)) - .debug_selector(|| "er-zoom-out".into()) - .rounded_tr(px(0.)) - .rounded_br(px(0.)) - .disabled(!ready || self.zoom <= zoom::MIN) - .tooltip(t(cx, "erDiagram.zoomOut")) - .on_click( - cx.listener(|this, _, window, cx| this.zoom_to(zoom::step(this.zoom, false), None, window, cx)), - ), - ) - .child( - Button::new("er-zoom-reset") - .debug_selector(|| "er-zoom-reset".into()) - .small() - .h(rems(form::FIELD_REM)) - .w(rems(3.692)) - .p_0() - .rounded(px(0.)) - .border_l_0() - .child(div().text_size(TEXT_XS).child(percent)) - .disabled(!ready) - .tooltip(t(cx, "erDiagram.zoomReset")) - .on_click(cx.listener(|this, _, window, cx| this.zoom_to(1., None, window, cx))), - ) - .child( - form::filter_button("er-zoom-in", Icon::new(IconName::Plus)) - .debug_selector(|| "er-zoom-in".into()) - .rounded_tl(px(0.)) - .rounded_bl(px(0.)) - .border_l_0() - .disabled(!ready || self.zoom >= zoom::MAX) - .tooltip(t(cx, "erDiagram.zoomIn")) - .on_click( - cx.listener(|this, _, window, cx| this.zoom_to(zoom::step(this.zoom, true), None, window, cx)), - ), - ) - } - fn diagram(&self, tables: &[ErTable], cx: &mut Context) -> impl IntoElement { let layout = self.layout.clone(); let focus = self.selected.or(self.hovered); @@ -542,7 +419,7 @@ impl ErDiagram { .absolute() .inset_0(), ); - zoom::zoomed(self.zoom, content) + zoom::zoomed(self.viewport.zoom, content) } // The focused table has an accent border and header, and the open button. Its neighbours' borders are tinted, as @@ -559,7 +436,7 @@ impl ErDiagram { let theme = cx.theme().clone(); let at = self.layout.boxes[ix]; let focused = focus == Some(ix); - let marked = near.contains(&ix) || self.matches.contains(&ix); + let marked = near.contains(&ix) || self.search.matches.contains(&ix); let faded = focus.is_some() && !focused && !near.contains(&ix); let lit_rows: Vec = lit .iter() @@ -659,7 +536,7 @@ impl ErDiagram { })) .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| { cx.stop_propagation(); - if this.panned { + if this.viewport.panned { return; } match event.click_count() { @@ -747,7 +624,7 @@ fn paint_edges(layout: &Layout, only: Option<&[usize]>, bounds: Bounds, #[cfg(feature = "snapshot")] impl ErDiagram { pub(crate) fn fitted(&self) -> bool { - self.fitted + self.viewport.fitted() } // Lights up a table's keys, as a click on it does. @@ -768,7 +645,9 @@ impl ErDiagram { // As the zoom buttons do, past Fit's 100% cap. pub(crate) fn set_zoom(&mut self, zoom: f32, window: &Window, cx: &mut Context) { - self.zoom_to(zoom, None, window, cx); + if self.viewport.zoom_to(zoom, None, window.rem_size()) { + cx.notify(); + } } } @@ -777,18 +656,10 @@ impl Render for ErDiagram { let theme = cx.theme().clone(); if self.placeholder_shown.is_empty() { self.placeholder_shown = self.placeholder(cx); - let placeholder = self.placeholder_shown.clone(); - self.search.update(cx, |search, cx| search.set_placeholder(placeholder, window, cx)); + self.search.set_placeholder(self.placeholder_shown.clone(), window, cx); } - // Opens with all of it in view, unless that would make it too small to read. - if matches!(self.state, State::Ready(_)) && !self.fitted { - let view = self.scroll.bounds().size; - if view.width > px(0.) && view.height > px(0.) { - self.zoom = zoom::fit(self.content(window.rem_size(), 1.), view).clamp(zoom::READABLE, 1.); - self.fitted = true; - } else { - cx.on_next_frame(window, |_, _, cx| cx.notify()); - } + if matches!(self.state, State::Ready(_)) { + self.viewport.fit_once(window); } let body = match &self.state { State::Ready(tables) => self.diagram(&tables.clone(), cx).into_any_element(), @@ -796,56 +667,16 @@ impl Render for ErDiagram { State::Empty => form::empty_state(None, t(cx, "erDiagram.empty"), cx).m_auto().into_any_element(), _ => form::loading_state(t(cx, "erDiagram.loading"), cx).m_auto().into_any_element(), }; - let viewport = div() - .id("er-diagram") + let area = zoom::area("er-diagram", &self.viewport, Self::viewport, cx) .debug_selector(|| "er-diagram".into()) - .size_full() - .flex() - .overflow_scroll() - .track_scroll(&self.scroll) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, event: &MouseDownEvent, _, _| { - this.pan = Some((event.position, this.scroll.offset())); - this.panned = false; - }), - ) - .on_drag(Pan, |_, _, _, cx| cx.new(|_| Pan)) - .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| this.pan_to(event.event.position, cx))) .on_click(cx.listener(|this, _, _, cx| { - if !this.panned { + if !this.viewport.panned { this.selected = None; cx.notify(); } })) - .on_pinch(cx.listener(|this, event: &PinchEvent, window, cx| { - let zoom = this.zoom * (1. + event.delta); - this.zoom_to(zoom, Some(event.position), window, cx); - })) .child(body); - // ⌘ or Ctrl with the wheel zooms, ahead of the viewport scrolling. A plain wheel scrolls. - let this = cx.entity().downgrade(); - let wheel = canvas( - |_, _, _| {}, - move |bounds, _, window, _| { - let this = this.clone(); - window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| { - let zooming = event.modifiers.platform || event.modifiers.control; - if phase != DispatchPhase::Capture || !zooming || !bounds.contains(&event.position) { - return; - } - cx.stop_propagation(); - let dy = event.delta.pixel_delta(window.line_height()).y; - let _ = this.update(cx, |view, cx| { - let zoom = zoom::wheel(view.zoom, dy); - view.zoom_to(zoom, Some(event.position), window, cx); - }); - }); - }, - ) - .absolute() - .inset_0(); - let (scroll, zoom, dot) = (self.scroll.clone(), self.zoom, theme.border); + let (scroll, zoom, dot) = (self.viewport.scroll.clone(), self.viewport.zoom, theme.border); let dots = canvas(|_, _, _| {}, move |bounds, _, window, _| paint_dots(bounds, scroll.offset(), zoom, dot, window)) .absolute() @@ -856,9 +687,9 @@ impl Render for ErDiagram { .flex_1() .min_h_0() .child(dots) - .child(viewport) - .child(wheel) - .hover_scrollbar(&self.scroll, ScrollbarAxis::Both), + .child(area) + .child(zoom::wheel_zoom(Self::viewport, cx)) + .hover_scrollbar(&self.viewport.scroll, ScrollbarAxis::Both), ) } } diff --git a/crates/barsql-ui/src/er_diagram/layout.rs b/crates/barsql-ui/src/er_diagram/layout.rs index 978f61d..b342182 100644 --- a/crates/barsql-ui/src/er_diagram/layout.rs +++ b/crates/barsql-ui/src/er_diagram/layout.rs @@ -3,6 +3,8 @@ use std::collections::{HashMap, HashSet}; use barsql_core::ColumnInfo; +use crate::fuzzy::substring_rank; + pub const BOX_W: f32 = 16.923; pub const HEADER_H: f32 = 2.154; pub const ROW_H: f32 = 1.692; @@ -375,16 +377,7 @@ pub fn find(tables: &[ErTable], query: &str) -> Vec { let mut hits: Vec<(u8, String, usize)> = tables .iter() .enumerate() - .filter_map(|(ix, table)| { - let name = table.name.to_lowercase(); - let rank = match () { - _ if name == query => 0, - _ if name.starts_with(&query) => 1, - _ if name.contains(&query) => 2, - _ => return None, - }; - Some((rank, name, ix)) - }) + .filter_map(|(ix, table)| Some((substring_rank(&table.name, &query)?, table.name.to_lowercase(), ix))) .collect(); hits.sort(); hits.into_iter().map(|(_, _, ix)| ix).collect() diff --git a/crates/barsql-ui/src/er_diagram/search.rs b/crates/barsql-ui/src/er_diagram/search.rs new file mode 100644 index 0000000..000338c --- /dev/null +++ b/crates/barsql-ui/src/er_diagram/search.rs @@ -0,0 +1,94 @@ +// A diagram's search box: what's typed, the boxes it finds, best first, and the hit in view. +use gpui_kit::component::ActiveTheme; +use gpui_kit::component::input::{Input, InputEvent, InputState}; +use gpui_kit::*; + +use crate::form; +use crate::i18n::{t, t_with}; +use crate::tokens::TEXT_XS; + +pub struct Search { + input: Entity, + query: String, + pub matches: Vec, + hit: usize, +} + +impl Search { + // Enter and Shift+Enter step through what `rank` finds, and `show` brings each into view. + pub fn new( + placeholder: SharedString, + get: fn(&mut V) -> &mut Search, + rank: fn(&V, &str, &App) -> Vec, + show: fn(&mut V, usize, &Window, &mut Context), + window: &mut Window, + cx: &mut Context, + ) -> (Self, Subscription) { + let input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder)); + let subscription = cx.subscribe_in(&input, window, move |this, input, event: &InputEvent, window, cx| { + let hit = match event { + // Enter sends Change too, with the same text, which keeps the hit. + InputEvent::Change => { + let query = input.read(cx).value().to_string(); + if query == get(this).query { + return; + } + let matches = rank(this, &query, cx); + let search = get(this); + (search.query, search.matches, search.hit) = (query, matches, 0); + search.current() + } + InputEvent::PressEnter { shift, .. } => get(this).step(if *shift { -1 } else { 1 }), + _ => return, + }; + if let Some(ix) = hit { + show(this, ix, window, cx); + } + cx.notify(); + }); + (Self { input, query: String::new(), matches: Vec::new(), hit: 0 }, subscription) + } + + pub fn query(&self) -> &str { + &self.query + } + + // The hit in view. + pub fn current(&self) -> Option { + self.matches.get(self.hit).copied() + } + + fn step(&mut self, by: isize) -> Option { + if self.matches.is_empty() { + return None; + } + self.hit = (self.hit as isize + by).rem_euclid(self.matches.len() as isize) as usize; + self.current() + } + + // The same query found again, as what it matches was renamed. + pub fn rematch(&mut self, matches: Vec) { + self.hit = self.hit.min(matches.len().saturating_sub(1)); + self.matches = matches; + } + + pub fn set_placeholder(&self, text: SharedString, window: &mut Window, cx: &mut App) { + self.input.update(cx, |input, cx| input.set_placeholder(text, window, cx)); + } + + // With "x of y", or `none` without a hit, inside the box so typing moves nothing. + pub fn field(&self, none: &str, selector: &'static str, window: &Window, cx: &App) -> Input { + let found = match (!self.query.trim().is_empty(), self.matches.len()) { + (false, _) => None, + (true, 0) => Some(t(cx, none)), + (true, count) => { + let (index, count) = ((self.hit + 1).to_string(), count.to_string()); + Some(t_with(cx, "erDiagram.matches", &[("index", &index), ("count", &count)])) + } + }; + let input = form::search_input(&self.input, window, cx); + let Some(found) = found else { return input }; + let muted = cx.theme().muted_foreground; + input.suffix(div().debug_selector(move || selector.into()).text_size(TEXT_XS).text_color(muted).child(found)) + } +} diff --git a/crates/barsql-ui/src/er_diagram/svg.rs b/crates/barsql-ui/src/er_diagram/svg.rs index 76c7c68..ffec4aa 100644 --- a/crates/barsql-ui/src/er_diagram/svg.rs +++ b/crates/barsql-ui/src/er_diagram/svg.rs @@ -9,9 +9,9 @@ use gpui_kit::{Hsla, Rgba}; use super::layout::{BOX_W, ErTable, HEADER_H, Layout, ROW_H, Spot}; // One rem at the default zoom, and the margin around the diagram, in px. -const REM: f32 = 13.; +pub(crate) const REM: f32 = 13.; const MARGIN: f32 = 24.; -const FONT: &str = "Inter, -apple-system, 'Segoe UI', sans-serif"; +pub(crate) const FONT: &str = "Inter, -apple-system, 'Segoe UI', sans-serif"; pub struct Palette { pub background: Hsla, @@ -175,7 +175,7 @@ fn edges(out: &mut String, layout: &Layout, palette: &Palette) { } // Cut to `room` px with an ellipsis, as the canvas truncates. -fn fit(text: &str, room: f32, size: f32, bold: bool, measure: &dyn Fn(&str, f32, bool) -> f32) -> String { +pub(crate) fn fit(text: &str, room: f32, size: f32, bold: bool, measure: &dyn Fn(&str, f32, bool) -> f32) -> String { if measure(text, size, bold) <= room { return text.to_string(); } @@ -192,14 +192,14 @@ fn fit(text: &str, room: f32, size: f32, bold: bool, measure: &dyn Fn(&str, f32, } // What a Lucide file holds inside its element. -fn inner(icon: &str) -> &str { +pub(crate) fn inner(icon: &str) -> &str { let start = icon.find('>').map_or(0, |ix| ix + 1); let end = icon.rfind("").unwrap_or(icon.len()); icon.get(start..end).unwrap_or_default() } // SVG 1.1 has no #rrggbbaa, so alpha goes in its own attribute. -fn paint(attribute: &str, color: Hsla) -> String { +pub(crate) fn paint(attribute: &str, color: Hsla) -> String { let alpha = color.to_rgb().a; match alpha < 1. { true => format!(r#"{attribute}="{}" {attribute}-opacity="{alpha:.2}""#, hex(color)), @@ -207,13 +207,13 @@ fn paint(attribute: &str, color: Hsla) -> String { } } -fn hex(color: Hsla) -> String { +pub(crate) fn hex(color: Hsla) -> String { let Rgba { r, g, b, .. } = color.to_rgb(); let byte = |v: f32| (v * 255.).round() as u8; format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b)) } -fn escape(text: &str) -> String { +pub(crate) fn escape(text: &str) -> String { text.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) } diff --git a/crates/barsql-ui/src/er_diagram/tests.rs b/crates/barsql-ui/src/er_diagram/tests.rs index a6cca2e..a800678 100644 --- a/crates/barsql-ui/src/er_diagram/tests.rs +++ b/crates/barsql-ui/src/er_diagram/tests.rs @@ -91,11 +91,11 @@ fn click(cx: &mut VisualTestContext, selector: &'static str) { } fn zoom_of(view: &Entity, cx: &mut VisualTestContext) -> f32 { - view.read_with(cx, |view, _| view.zoom) + view.read_with(cx, |view, _| view.viewport.zoom) } fn offset(view: &Entity, cx: &mut VisualTestContext) -> Point { - view.read_with(cx, |view, _| view.scroll.offset()) + view.read_with(cx, |view, _| view.viewport.scroll.offset()) } fn wheel(cx: &mut VisualTestContext, at: Point, dy: f32, modifiers: Modifiers) { @@ -112,9 +112,10 @@ fn wheel(cx: &mut VisualTestContext, at: Point, dy: f32, modifiers: Modi fn under(view: &Entity, at: Point, cx: &mut VisualTestContext) -> Point { let rem = cx.update(|window, _| window.rem_size()); view.read_with(cx, |view, _| { - let origin = view.scroll.bounds().origin + view.margin(rem, view.zoom) + view.scroll.offset(); + let viewport = &view.viewport; + let origin = viewport.scroll.bounds().origin + viewport.margin(rem, viewport.zoom) + viewport.scroll.offset(); let local = at - origin; - point(local.x / view.zoom, local.y / view.zoom) + point(local.x / viewport.zoom, local.y / viewport.zoom) }) } @@ -153,8 +154,9 @@ fn a_big_schema_opens_readable_and_fit_shows_it_all(cx: &mut TestAppContext) { assert_eq!(zoom_of(&view, cx), zoom::READABLE); click(cx, "er-fit"); let rem = cx.update(|window, _| window.rem_size()); - let (zoom, content, viewport) = - view.read_with(cx, |view, _| (view.zoom, view.content(rem, view.zoom), view.scroll.bounds().size)); + let (zoom, content, viewport) = view.read_with(cx, |view, _| { + (view.viewport.zoom, view.viewport.content(rem, view.viewport.zoom), view.viewport.scroll.bounds().size) + }); assert!(zoom < zoom::READABLE, "Fit goes further"); assert!(content.width <= viewport.width + px(1.) && content.height <= viewport.height + px(1.)); } @@ -269,7 +271,7 @@ fn search_picks_the_best_match_and_enter_steps_through_the_rest(cx: &mut TestApp click(cx, "er-search"); cx.simulate_input("t01"); draw(cx); - let picked = |cx: &mut VisualTestContext| view.read_with(cx, |view, _| (view.selected, view.matches.len())); + let picked = |cx: &mut VisualTestContext| view.read_with(cx, |view, _| (view.selected, view.search.matches.len())); assert_eq!(picked(cx), (Some(10), 10), "t010 to t019, by name"); assert!(cx.debug_bounds("er-matches").is_some()); cx.simulate_keystrokes("enter"); diff --git a/crates/barsql-ui/src/er_diagram/zoom.rs b/crates/barsql-ui/src/er_diagram/zoom.rs index b439ba4..8b2635b 100644 --- a/crates/barsql-ui/src/er_diagram/zoom.rs +++ b/crates/barsql-ui/src/er_diagram/zoom.rs @@ -1,10 +1,16 @@ -// The diagram's zoom: the steps its buttons take, the zoom that fits it all, and the scroll offsets that keep the -// point under the pointer still or bring a table to the middle. GPUI can't scale a subtree, so Zoomed lays its child -// out at a larger or smaller rem instead. Every size in the diagram is in rems, text and icons too. +// The diagrams' pan and zoom: the steps the buttons take, the zoom that fits it all, and the scroll offsets that keep +// the point under the pointer still or bring a box to the middle. GPUI can't scale a subtree, so Zoomed lays its child +// out at a larger or smaller rem instead. Every size in a diagram is in rems, text and icons too. use std::panic::Location; +use gpui_kit::component::button::Button; +use gpui_kit::component::{Disableable, Icon, IconName, Sizable, h_flex}; use gpui_kit::*; +use crate::form; +use crate::i18n::t; +use crate::tokens::TEXT_XS; + pub const MIN: f32 = 0.1; pub const MAX: f32 = 2.; // It opens at least this large, so names stay readable. Fit goes further. @@ -12,6 +18,174 @@ pub const READABLE: f32 = 0.5; const STEPS: [f32; 14] = [0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1., 1.1, 1.25, 1.5, 1.75, 2.]; // A wheel or trackpad scroll this far doubles or halves the zoom. const WHEEL_DOUBLING: f32 = 240.; +// A press that moves further pans, and doesn't count as a click. +const PAN_SLOP: Pixels = px(4.); + +// What a pan drags; GPUI draws it, so it draws nothing. +pub struct Pan; + +impl Render for Pan { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Empty + } +} + +// The zoom and scroll over content `size` rems across, which is centred while smaller than the view. +pub struct Viewport { + pub zoom: f32, + pub scroll: ScrollHandle, + size: Size, + fitted: bool, + // Where the pointer and the scroll were when a press started, and whether it moved far enough to be a pan. + pan: Option<(Point, Point)>, + pub panned: bool, +} + +impl Viewport { + pub fn new(width: f32, height: f32) -> Self { + let size = size(width, height); + Self { zoom: 1., scroll: ScrollHandle::new(), size, fitted: false, pan: None, panned: false } + } + + // New content, fitted again on the next frame when `refit`. + pub fn resize(&mut self, width: f32, height: f32, refit: bool) { + self.size = size(width, height); + self.fitted &= !refit; + } + + #[cfg(feature = "snapshot")] + pub fn fitted(&self) -> bool { + self.fitted + } + + pub fn content(&self, rem: Pixels, zoom: f32) -> Size { + size(rem * self.size.width * zoom, rem * self.size.height * zoom) + } + + // The empty room around content smaller than the view. + pub fn margin(&self, rem: Pixels, zoom: f32) -> Point { + let (view, content) = (self.scroll.bounds().size, self.content(rem, zoom)); + point(((view.width - content.width) / 2.).max(px(0.)), ((view.height - content.height) / 2.).max(px(0.))) + } + + // Opens with all of it in view, unless that would make it too small to read. + pub fn fit_once(&mut self, window: &Window) { + if self.fitted { + return; + } + let view = self.scroll.bounds().size; + if view.width > px(0.) && view.height > px(0.) { + self.zoom = fit(self.content(window.rem_size(), 1.), view).clamp(READABLE, 1.); + self.fitted = true; + } else { + window.request_animation_frame(); + } + } + + pub fn fit(&mut self, rem: Pixels) { + self.zoom = fit(self.content(rem, 1.), self.scroll.bounds().size); + self.scroll.set_offset(point(px(0.), px(0.))); + } + + // Keeps `anchor`, or else the view's middle, over the same content; false if unchanged. + pub fn zoom_to(&mut self, zoom: f32, anchor: Option>, rem: Pixels) -> bool { + let zoom = zoom.clamp(MIN, MAX); + if (zoom - self.zoom).abs() < 1e-4 { + return false; + } + let view = self.scroll.bounds(); + let anchor = anchor.map_or(point(view.size.width / 2., view.size.height / 2.), |at| at - view.origin); + let from = self.scroll.offset() + self.margin(rem, self.zoom); + let offset = anchored(from, anchor, self.zoom, zoom) - self.margin(rem, zoom); + self.zoom = zoom; + self.scroll.set_offset(offset); + true + } + + // Scrolls the content's point `(x, y)`, in rems, to the middle of the view. + pub fn centre_on(&mut self, (x, y): (f32, f32), rem: Pixels) { + let scale = rem * self.zoom; + let target = point(scale * x, scale * y); + self.scroll.set_offset(centred(target, self.scroll.bounds().size, self.content(rem, self.zoom))); + } + + // Where the content's point `(x, y)`, in rems, is in the window. + pub fn in_window(&self, (x, y): (f32, f32), rem: Pixels) -> Point { + let scale = rem * self.zoom; + self.scroll.bounds().origin + self.scroll.offset() + self.margin(rem, self.zoom) + point(scale * x, scale * y) + } + + fn press(&mut self, at: Point) { + self.pan = Some((at, self.scroll.offset())); + self.panned = false; + } + + fn drag(&mut self, at: Point) -> bool { + let Some((start, offset)) = self.pan else { return false }; + let moved = at - start; + self.panned |= moved.x.abs().max(moved.y.abs()) > PAN_SLOP; + self.scroll.set_offset(offset + moved); + true + } +} + +// The scrolling area, where a drag pans and a pinch zooms about the pointer. +pub fn area( + id: &'static str, + viewport: &Viewport, + get: fn(&mut V) -> &mut Viewport, + cx: &mut Context, +) -> Stateful
{ + div() + .id(id) + .size_full() + .flex() + .overflow_scroll() + .track_scroll(&viewport.scroll) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, _| get(this).press(event.position)), + ) + .on_drag(Pan, |_, _, _, cx| cx.new(|_| Pan)) + .on_drag_move(cx.listener(move |this, event: &DragMoveEvent, _, cx| { + if get(this).drag(event.event.position) { + cx.notify(); + } + })) + .on_pinch(cx.listener(move |this, event: &PinchEvent, window, cx| { + let viewport = get(this); + if viewport.zoom_to(viewport.zoom * (1. + event.delta), Some(event.position), window.rem_size()) { + cx.notify(); + } + })) +} + +// Laid over the area: ⌘ or Ctrl with the wheel zooms about the pointer instead of scrolling. +pub fn wheel_zoom(get: fn(&mut V) -> &mut Viewport, cx: &mut Context) -> impl IntoElement + use { + let this = cx.entity().downgrade(); + canvas( + |_, _, _| {}, + move |bounds, _, window, _| { + let this = this.clone(); + window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| { + let zooming = event.modifiers.platform || event.modifiers.control; + if phase != DispatchPhase::Capture || !zooming || !bounds.contains(&event.position) { + return; + } + cx.stop_propagation(); + let dy = event.delta.pixel_delta(window.line_height()).y; + let _ = this.update(cx, |view, cx| { + let viewport = get(view); + if viewport.zoom_to(wheel(viewport.zoom, dy), Some(event.position), window.rem_size()) { + cx.notify(); + } + }); + }); + }, + ) + .absolute() + .inset_0() +} // The next step in or out from `zoom`, which may sit between steps after a pinch. pub fn step(zoom: f32, inward: bool) -> f32 { @@ -50,6 +224,57 @@ pub fn centred(target: Point, viewport: Size, content: Size( + id: &'static str, + viewport: &Viewport, + enabled: bool, + get: fn(&mut V) -> &mut Viewport, + cx: &mut Context, +) -> impl IntoElement + use { + let zoom = viewport.zoom; + let set = move |this: &mut V, to: f32, window: &mut Window, cx: &mut Context| { + if get(this).zoom_to(to, None, window.rem_size()) { + cx.notify(); + } + }; + let name = move |part: &str| format!("{id}-zoom-{part}"); + h_flex() + .child( + form::filter_button(ElementId::Name(name("out").into()), Icon::new(IconName::Minus)) + .debug_selector(move || name("out")) + .rounded_tr(px(0.)) + .rounded_br(px(0.)) + .disabled(!enabled || zoom <= MIN) + .tooltip(t(cx, "erDiagram.zoomOut")) + .on_click(cx.listener(move |this, _, window, cx| set(this, step(zoom, false), window, cx))), + ) + .child( + Button::new(ElementId::Name(name("reset").into())) + .debug_selector(move || name("reset")) + .small() + .h(rems(form::FIELD_REM)) + .w(rems(3.692)) + .p_0() + .rounded(px(0.)) + .border_l_0() + .child(div().text_size(TEXT_XS).child(format!("{}%", (zoom * 100.).round()))) + .disabled(!enabled) + .tooltip(t(cx, "erDiagram.zoomReset")) + .on_click(cx.listener(move |this, _, window, cx| set(this, 1., window, cx))), + ) + .child( + form::filter_button(ElementId::Name(name("in").into()), Icon::new(IconName::Plus)) + .debug_selector(move || name("in")) + .rounded_tl(px(0.)) + .rounded_bl(px(0.)) + .border_l_0() + .disabled(!enabled || zoom >= MAX) + .tooltip(t(cx, "erDiagram.zoomIn")) + .on_click(cx.listener(move |this, _, window, cx| set(this, step(zoom, true), window, cx))), + ) +} + pub struct Zoomed { zoom: f32, rem: Pixels, diff --git a/crates/barsql-ui/src/fuzzy.rs b/crates/barsql-ui/src/fuzzy.rs index 1107417..4aa9e48 100644 --- a/crates/barsql-ui/src/fuzzy.rs +++ b/crates/barsql-ui/src/fuzzy.rs @@ -128,6 +128,17 @@ pub fn rank_candidate(query: &str, primary: &str, secondary: &[&str]) -> Option< score.is_finite().then(|| FuzzyResult { score, ranges: primary_match.map(|m| m.ranges).unwrap_or_default() }) } +// A plain search's rank, ignoring case: 0 for the whole text, 1 for its start, 2 anywhere. `query` is lowercase. +pub fn substring_rank(text: &str, query: &str) -> Option { + let text = text.to_lowercase(); + match () { + _ if text == query => Some(0), + _ if text.starts_with(query) => Some(1), + _ if text.contains(query) => Some(2), + _ => None, + } +} + #[cfg(test)] mod tests { use super::{FuzzyResult, fuzzy_match, rank_candidate}; diff --git a/crates/barsql-ui/src/lib.rs b/crates/barsql-ui/src/lib.rs index 9cff278..55ad3fa 100644 --- a/crates/barsql-ui/src/lib.rs +++ b/crates/barsql-ui/src/lib.rs @@ -1,5 +1,6 @@ mod about_dialog; mod actions; +mod algebra_graph; mod assets; mod cell_content; mod cell_viewer; diff --git a/crates/barsql-ui/src/query_tab.rs b/crates/barsql-ui/src/query_tab.rs index 1dd9cc6..c598007 100644 --- a/crates/barsql-ui/src/query_tab.rs +++ b/crates/barsql-ui/src/query_tab.rs @@ -14,7 +14,7 @@ use gpui_kit::component::input::{ Editor, EditorMode, EditorState, GoToDefinition, InputEvent, RangeDecoration, RangeDecorationCollection, RangeDecorationStyle, Replace, Search, SelectAll, }; -use gpui_kit::component::menu::{DropdownMenu, PopupMenuItem}; +use gpui_kit::component::menu::{DropdownMenu, PopupMenu, PopupMenuItem}; use gpui_kit::component::native_menu::NativeMenu; use gpui_kit::component::{ ActiveTheme, Disableable, Icon, IconName, InteractiveElementExt as _, RopeExt, Sizable, h_flex, v_flex, @@ -25,8 +25,9 @@ use lsp_types::{Diagnostic, DiagnosticSeverity, ShowDocumentParams}; use crate::actions::{ BeginTransaction, CommitTransaction, ExplainAnalyze, ExplainQuery, FormatQuery, RenameSavedQuery, - RollbackTransaction, RunAll, RunSelection, SaveQuery, SaveQueryAs, TriggerSuggest, + RollbackTransaction, RunAll, RunSelection, SaveQuery, SaveQueryAs, ShowAlgebra, TriggerSuggest, }; +use crate::algebra_graph::{self, AlgebraEvent, AlgebraGraph}; use crate::completion::{self, Completion}; use crate::context_menu::{self, Entry}; use crate::database_pane; @@ -45,7 +46,7 @@ use crate::spinner::ProgressLine; use crate::sql_language::{self, SqlDefinitions, SqlLanguage, linked_table, lsp_range}; use crate::status_bar::Caret; use crate::tokens::{DOT_SM, ICON_XS, RADIUS, STRIP, TEXT_SM, TEXT_XS, TINT, TINT_BORDER}; -use crate::{params_dialog, shortcuts, state, theme}; +use crate::{params_dialog, shortcuts, state, theme, toast}; const EDITOR_CONTEXT: &str = "QueryEditor CodeEditor"; const COMPLETING_CONTEXT: &str = "QueryEditor CodeEditor completing"; @@ -53,8 +54,8 @@ const DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_millis(300); const STATUS_TICK: Duration = Duration::from_millis(100); // How long a run from the caret marks its statement. const FLASH: Duration = Duration::from_millis(500); -// Results pane share of the tab in percent, as (default, min, max). -const RESULTS_SHARE: (f32, f32, f32) = (40., 15., 70.); +// Results share in percent (default, min, max); the editor keeps editor_floor. +const RESULTS_SHARE: (f32, f32, f32) = (40., 15., 100.); // The run glyphs' column, this far into the gutter, so a hovered glyph's square lines up with the Run button above. const GLYPH_INSET: Pixels = px(3.); @@ -90,6 +91,11 @@ fn results_share(cx: &App) -> f32 { cx.try_global::().map_or(RESULTS_SHARE.0, |share| share.0) } +// About three lines at the editor's text size. +fn editor_floor(cx: &App) -> Pixels { + px(theme::editor_font_size(cx) * 5.) +} + // The results take all the room they may, or go back to where they were. fn toggle_results_maximized(cx: &mut App) { let (share, max) = (results_share(cx), RESULTS_SHARE.2); @@ -173,6 +179,10 @@ pub struct QueryTab { language: Rc, _occurrences: Entity, flash: RangeDecorationCollection, + // What the graph in the results has picked, and where that left the caret. + marks: RangeDecorationCollection, + marked: Option, + graph: Option<(WeakEntity, [Subscription; 2])>, flash_task: Task<()>, results: Entity, running: Option, @@ -235,6 +245,7 @@ impl QueryTab { let completion = cx.new(|cx| Completion::new(editor.clone(), Some(language.clone()), window, cx)); let occurrences = cx.new(|cx| OccurrenceMarks::new(&editor, cx)); let flash = editor.update(cx, |state, cx| state.create_range_decorations_collection(Vec::new(), cx)); + let marks = editor.update(cx, |state, cx| state.create_range_decorations_collection(Vec::new(), cx)); let dialect = connection.driver.dialect(); let (panel_connection, tab_id) = (connection.clone(), tab.id.clone()); let results = cx.new(|cx| { @@ -249,10 +260,18 @@ impl QueryTab { if matches!(event, InputEvent::Change) { sync_glyph_strip(&this.editor, window, cx); this.query_error = None; + if this.marked.is_some() { + this.let_go(cx); + } this.schedule_diagnostics(window, cx); cx.emit(QueryTabEvent::Edited); } }), + cx.observe(&editor, |this, editor, cx| { + if this.marked.is_some_and(|caret| caret != editor.read(cx).cursor()) { + this.let_go(cx); + } + }), cx.subscribe_in(&results, window, |this, _, event: &ResultsEvent, window, cx| match event { ResultsEvent::JumpToError { statement, position, message } => { this.jump_to_error(statement, *position, message, window, cx) @@ -293,6 +312,9 @@ impl QueryTab { language, _occurrences: occurrences, flash, + marks, + marked: None, + graph: None, flash_task: Task::ready(()), results, running: None, @@ -1113,17 +1135,70 @@ impl QueryTab { // Uses the selection, else the statement at the caret, else the whole text. fn explain_text(&self, cx: &App) -> String { + self.explain_source(cx).0 + } + + // The text explain takes, and where in the editor it begins. + fn explain_source(&self, cx: &App) -> (String, usize) { let state = self.editor.read(cx); let selected = state.selected_text().to_string(); - if !selected.trim().is_empty() { - return selected.trim().to_string(); + let (text, base) = match () { + _ if !selected.trim().is_empty() => (selected, state.selected_range().start), + _ => match self.statement_at_caret(cx) { + Some((text, start)) => (text, start), + None => (state.value().to_string(), 0), + }, + }; + let lead = text.len() - text.trim_start().len(); + (text.trim().to_string(), base + lead) + } + + // Where `sql` is now, nearest its old offset. + fn statement_at(&self, offset: usize, sql: &str, cx: &App) -> Option { + self.sql(cx).match_indices(sql).map(|(at, _)| at).min_by_key(|at| at.abs_diff(offset)) + } + + // Marks a graph pick where its statement now is. + fn reveal(&mut self, sql: &str, offset: usize, event: &AlgebraEvent, window: &mut Window, cx: &mut Context) { + let AlgebraEvent::Reveal { range, color } = event; + let Some(range) = range else { return self.unmark(cx) }; + let Some(start) = self.statement_at(offset, sql, cx) else { + toast::error(t(cx, "algebra.stale"), cx); + return self.let_go(cx); + }; + let mark = RangeDecoration::new(start + range.start..start + range.end) + .with_style(RangeDecorationStyle::Fill) + .with_color(color.opacity(0.3)); + self.marks.set(vec![mark], cx); + let caret = self.editor.update(cx, |state, cx| { + let position = state.text().offset_to_position(start + range.start); + state.set_cursor_position(position, window, cx); + state.cursor() + }); + self.marked = Some(caret); + // Keys stay the editor's, so its shortcuts work after a click in the graph. + self.focus_editor(window, cx); + } + + fn unmark(&mut self, cx: &mut Context) { + if self.marked.take().is_some() { + self.marks.clear(cx); } - match self.statement_at_caret(cx) { - Some((text, _)) => text.trim().to_string(), - None => state.value().trim().to_string(), + } + + // Drops the mark and the graph's pick. + fn let_go(&mut self, cx: &mut Context) { + self.unmark(cx); + if let Some((graph, _)) = &self.graph { + let _ = graph.update(cx, |graph, cx| graph.let_go(cx)); } } + #[cfg(test)] + pub(crate) fn marked(&self) -> bool { + self.marked.is_some() + } + // Shares the running state because an analyze takes as long as the query and cancels the same way. pub(crate) fn explain(&mut self, analyze: bool, window: &mut Window, cx: &mut Context) { if self.running.is_some() || (analyze && !self.can_analyze()) { @@ -1142,6 +1217,30 @@ impl QueryTab { }); } + // Replaces the results like a plan, asking about unsaved edits first. + fn show_algebra(&mut self, window: &mut Window, cx: &mut Context) { + let (sql, offset) = self.explain_source(cx); + if self.running.is_some() || sql.is_empty() { + return; + } + let root = match algebra_graph::parse(&sql, &self.connection) { + Ok(root) => root, + Err(error) => return algebra_graph::report(error, &sql, cx), + }; + self.after_discard(window, cx, move |tab, window, cx| { + tab.unmark(cx); + let (connection, root, sql) = (tab.connection.clone(), root.clone(), sql.clone()); + let graph = cx.new(|cx| AlgebraGraph::new(connection, root, window, cx)); + let picks = cx.subscribe_in(&graph, window, move |tab, _, event: &AlgebraEvent, window, cx| { + tab.reveal(&sql, offset, event, window, cx) + }); + // Whatever takes the graph's place takes its mark too. + let gone = cx.observe_release(&graph, |tab, _, cx| tab.unmark(cx)); + tab.graph = Some((graph.downgrade(), [picks, gone])); + tab.results.update(cx, |results, cx| results.show_algebra(graph, cx)); + }); + } + fn explain_sql(&mut self, sql: String, analyze: bool, window: &mut Window, cx: &mut Context) { if self.running.is_some() { return; @@ -1303,8 +1402,9 @@ impl QueryTab { if self.saved_query_id.is_empty() { return save.into_any_element(); } - let items: Vec<(&'static str, Box)> = - vec![("editor.update", Box::new(SaveQuery)), ("editor.saveAs", Box::new(SaveQueryAs))]; + let items = |menu: PopupMenu, cx: &App| { + menu.menu(t(cx, "editor.update"), Box::new(SaveQuery)).menu(t(cx, "editor.saveAs"), Box::new(SaveQueryAs)) + }; self.split_button(save, "save-menu", t(cx, "editor.saveOptions"), false, items, cx) } @@ -1315,7 +1415,7 @@ impl QueryTab { caret: &'static str, tooltip: SharedString, disabled: bool, - items: Vec<(&'static str, Box)>, + items: impl Fn(PopupMenu, &App) -> PopupMenu + 'static, cx: &mut Context, ) -> AnyElement { let tab = cx.entity().downgrade(); @@ -1333,28 +1433,27 @@ impl QueryTab { .disabled(disabled) .dropdown_menu(move |menu, _, cx| { let focus = tab.upgrade().map(|tab| tab.read(cx).editor.read(cx).focus_handle(cx)); - let menu = menu.when_some(focus, |menu, focus| menu.action_context(focus)); - items.iter().fold(menu, |menu, (key, action)| menu.menu(t(cx, key), action.boxed_clone())) + items(menu.when_some(focus, |menu, focus| menu.action_context(focus)), cx) }), ) .into_any_element() } - // Explain, and a caret for Explain analyze where the engine has one. Without it the caret would only repeat the - // button, so Explain stands alone. + // Explain, with Explain analyze and the algebra graph in its menu. fn explain_button(&self, cx: &mut Context) -> impl IntoElement + use<> { - let running = self.running.is_some(); + let (running, analyze) = (self.running.is_some(), self.can_analyze()); let explain = Button::new("explain") .debug_selector(|| "explain".into()) .tool(Icon::new(Lucide::Route), ICON_XS, t(cx, "editor.explain")) .tooltip(hint("tooltip.explain", "explainQuery", cx)) .disabled(running) .on_click(cx.listener(|this, _, window, cx| this.explain(false, window, cx))); - if !self.can_analyze() { - return explain.into_any_element(); - } - let items: Vec<(&'static str, Box)> = - vec![("editor.explain", Box::new(ExplainQuery)), ("editor.explainAnalyze", Box::new(ExplainAnalyze))]; + let items = move |menu: PopupMenu, cx: &App| { + menu.menu(t(cx, "editor.explain"), Box::new(ExplainQuery)) + .when(analyze, |menu| menu.menu(t(cx, "editor.explainAnalyze"), Box::new(ExplainAnalyze))) + .separator() + .menu(t(cx, "algebra.title"), Box::new(ShowAlgebra)) + }; self.split_button(explain, "explain-menu", t(cx, "editor.explainOptions"), running, items, cx) } @@ -1499,6 +1598,7 @@ fn editor_menu( if analyze { entries.push(Entry::item(t(cx, "editor.explainAnalyze"), ExplainAnalyze, false)); } + entries.push(Entry::item(t(cx, "algebra.title"), ShowAlgebra, false)); entries.extend([ Entry::Separator, Entry::item(t(cx, "editor.contextGoToDefinition"), GoToDefinition, false), @@ -1531,6 +1631,7 @@ impl Render for QueryTab { .on_action(cx.listener(|this, _: &RunAll, window, cx| this.run_all(window, cx))) .on_action(cx.listener(|this, _: &ExplainQuery, window, cx| this.explain(false, window, cx))) .on_action(cx.listener(|this, _: &ExplainAnalyze, window, cx| this.explain(true, window, cx))) + .on_action(cx.listener(|this, _: &ShowAlgebra, window, cx| this.show_algebra(window, cx))) .on_action(cx.listener(|this, _: &FormatQuery, window, cx| this.format(window, cx))) .on_action(cx.listener(|this, _: &TriggerSuggest, window, cx| this.suggest(window, cx))) .on_action(cx.listener(|this, _: &SaveQuery, window, cx| this.save(window, cx))) @@ -1550,11 +1651,14 @@ impl Render for QueryTab { this.transaction(TxnControl::Rollback, false, window, cx) })) }) - .on_drag_move(cx.listener(|_, event: &DragMoveEvent, _, cx| { - let bounds = event.bounds; + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { + let (bounds, y) = (event.bounds, event.event.position.y); if bounds.size.height > px(0.) { - let share = (bounds.bottom() - event.event.position.y) / bounds.size.height * 100.; - cx.set_global(ResultsShare(share.clamp(RESULTS_SHARE.1, RESULTS_SHARE.2))); + let share = ((bounds.bottom() - y) / bounds.size.height * 100.).max(RESULTS_SHARE.1); + // At the editor's floor counts as maximized, so a double click restores. + let floor = this.editor.read(cx).input_bounds().top() + editor_floor(cx); + let maximized = y <= floor && share > RESULTS_SHARE.1; + cx.set_global(ResultsShare(if maximized { RESULTS_SHARE.2 } else { share })); cx.notify(); } })) @@ -1566,7 +1670,7 @@ impl Render for QueryTab { .debug_selector(|| "query-editor".into()) .relative() .flex_1() - .min_h_0() + .min_h(editor_floor(cx)) .child( Editor::new(&self.editor) .size_full() @@ -1592,7 +1696,8 @@ impl Render for QueryTab { .id("results-pane") .debug_selector(|| "results-pane".into()) .relative() - .flex_none() + // Shrinks past its share to leave the editor its floor. + .flex_shrink_1() .min_h_0() .h(relative(results_share(cx) / 100.)) .child(self.results.clone()) diff --git a/crates/barsql-ui/src/query_tab/tests.rs b/crates/barsql-ui/src/query_tab/tests.rs index 80d0113..b04679f 100644 --- a/crates/barsql-ui/src/query_tab/tests.rs +++ b/crates/barsql-ui/src/query_tab/tests.rs @@ -4,8 +4,8 @@ use gpui_kit::component::scroll::ScrollbarMode; use gpui_kit::{Entity, Modifiers, MouseButton, Pixels, Point, TestAppContext, VisualTestContext, point, px}; use super::{ - GLYPH_INSET, QueryTab, TxnState, char_offset, dotted_title, glyph_strip, misspelt_range, new_tab_id, results_share, - word_range, + GLYPH_INSET, QueryTab, TxnState, char_offset, dotted_title, editor_floor, glyph_strip, misspelt_range, new_tab_id, + results_share, word_range, }; use crate::results::ResultStatus; use crate::schema; @@ -301,9 +301,16 @@ fn a_run_publishes_the_focused_row_for_the_json_panel(cx: &mut TestAppContext) { assert_eq!(row.set.display(0, 1), Some("thing 1")); } -// The splitter line is 1px but grabs 4px either side, over both the editor and the results. +// The editor's height once a frame has drawn, against the least it keeps. +fn editor_and_floor(cx: &mut VisualTestContext) -> (Pixels, Pixels) { + cx.update(|window, cx| window.draw(cx).clear(cx)); + let editor = cx.debug_bounds("query-editor").expect("the editor is drawn").size.height; + (editor, cx.update(|_, cx| editor_floor(cx))) +} + +// The 1px splitter grabs 4px either side; at the editor's floor the results are maximized. #[gpui_kit::test] -fn the_results_splitter_drags_between_fifteen_and_seventy_percent(cx: &mut TestAppContext) { +fn the_results_splitter_drags_from_fifteen_percent_to_the_editors_last_lines(cx: &mut TestAppContext) { let env = Env::new(cx); let (_tab, cx) = open(&env, cx, "SELECT 1"); cx.run_until_parked(); @@ -321,7 +328,9 @@ fn the_results_splitter_drags_between_fifteen_and_seventy_percent(cx: &mut TestA let height = cx.update(|window, _| window.bounds().size.height); let half = drag(cx, 0., (height / 2.).as_f32()); assert!((half - 50.).abs() < 1., "{half}"); - assert_eq!(drag(cx, -3., 0.), 70.); + assert_eq!(drag(cx, -3., 0.), 100.); + let (editor, floor) = editor_and_floor(cx); + assert!((editor - floor).abs() < px(1.), "{editor:?} tall, keeping {floor:?}"); assert_eq!(drag(cx, 3., height.as_f32()), 15.); } @@ -353,7 +362,9 @@ fn a_double_click_on_the_splitter_maximizes_the_results_and_restores_them(cx: &m cx.run_until_parked(); cx.update(|_, cx| results_share(cx)) }; - assert_eq!(double_click(cx), 70.); + assert_eq!(double_click(cx), 100.); + let (editor, floor) = editor_and_floor(cx); + assert!((editor - floor).abs() < px(1.), "{editor:?} tall, keeping {floor:?}"); assert_eq!(double_click(cx), 40., "back to where they were"); } diff --git a/crates/barsql-ui/src/results.rs b/crates/barsql-ui/src/results.rs index 9ecaba6..97fb509 100644 --- a/crates/barsql-ui/src/results.rs +++ b/crates/barsql-ui/src/results.rs @@ -17,6 +17,7 @@ use gpui_kit::component::{ActiveTheme, Disableable, Icon, Selectable, StyledExt, use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; +use crate::algebra_graph::AlgebraGraph; use crate::cell_viewer; use crate::chart_view::ChartView; use crate::dialogs; @@ -196,6 +197,7 @@ struct ResultSetView { rows_in: bool, summary: Option, plan: Option>, + algebra: Option>, error: Option, statement: Option, // Set once the rows turn out to be one table's, for its keys. @@ -244,7 +246,7 @@ impl ResultSetView { // Nothing to look at but the summary line. fn is_plain(&self) -> bool { - self.grid.is_none() && self.plan.is_none() && self.error.is_none() + self.grid.is_none() && self.plan.is_none() && self.algebra.is_none() && self.error.is_none() } // Row count for a grid, affected rows for a write, and no badge for errors, plans or DDL. @@ -369,6 +371,9 @@ impl ResultsPanel { } self.shown_changed(shown, cx); } + for graph in self.sets.iter().filter_map(|set| set.algebra.as_ref()) { + graph.update(cx, |graph, cx| graph.set_connection(connection.clone(), cx)); + } self.connection = Some(connection); } @@ -503,6 +508,15 @@ impl ResultsPanel { self.show(ResultSetView { plan: Some(plan), ..Default::default() }, cx); } + pub fn show_algebra(&mut self, graph: Entity, cx: &mut Context) { + self.show(ResultSetView { algebra: Some(graph), ..Default::default() }, cx); + } + + #[cfg(test)] + pub(crate) fn algebra(&self) -> Option<&Entity> { + self.sets.get(self.active)?.algebra.as_ref() + } + // A batch's later results carry its whole text too, and only its first can be traced. fn first_of_statement(&self, index: usize, statement: &str) -> bool { let before = index.checked_sub(1).and_then(|prev| self.sets.get(prev)); @@ -656,7 +670,7 @@ impl ResultsPanel { if let Some(error) = &set.error { return ResultStatus::Error(error.message.clone()); } - if set.plan.is_some() { + if set.plan.is_some() || set.algebra.is_some() { return ResultStatus::Empty; } if set.streaming { @@ -1590,7 +1604,10 @@ impl Render for ResultsPanel { // As before any result, while the tab's progress line says more is coming. (None, None, Some(_)) if set.grid_waits() => self.empty(None, cx), (None, None, Some(grid)) => self.grid(set, grid, cx), - (None, None, None) => self.empty(Some(set), cx), + (None, None, None) => match &set.algebra { + Some(graph) => graph.clone().into_any_element(), + None => self.empty(Some(set), cx), + }, }, }; // Panel colour behind the tabs, the grid toolbar and everything around the grid. diff --git a/crates/barsql-ui/src/scenarios/algebra.rs b/crates/barsql-ui/src/scenarios/algebra.rs new file mode 100644 index 0000000..0cb49a0 --- /dev/null +++ b/crates/barsql-ui/src/scenarios/algebra.rs @@ -0,0 +1,72 @@ +// The relational algebra graph: drawn in its query tab's results, where a pick marks the query above. +use gpui_kit::{Entity, TestAppContext}; + +use super::driver::{Driver, open}; +use crate::algebra_graph::AlgebraGraph; +use crate::i18n::t; + +const JOIN: &str = "SELECT * FROM things t JOIN things u ON u.id = t.id"; + +fn graph(app: &mut Driver) -> Option> { + let results = app.results(); + app.cx.update(|_, cx| results.read(cx).algebra().cloned()) +} + +// From Explain's menu (SQLite too) or Ctrl+Shift+R, in place of the results until a run. +#[gpui_kit::test] +fn explains_menu_and_a_shortcut_draw_the_graph_in_the_results(cx: &mut TestAppContext) { + let mut app = open(cx); + app.connect(); + app.set_sql(JOIN); + assert!(!app.shown("algebra"), "no button of its own"); + app.menu_pick("explain-menu", 1); + assert!(app.shown("ra-node-0"), "Explain, then the graph"); + assert_eq!(app.titles().len(), 1, "in the query's results, not a tab"); + let first = graph(&mut app).expect("the results show the graph").downgrade(); + app.set_sql("SELECT id FROM things"); + app.keys("mod-shift-r"); + assert!(first.upgrade().is_none(), "the new graph frees the old one"); + assert!(graph(&mut app).is_some(), "drawn again for the statement as it is now"); + app.click("ra-node-0"); + let query = app.tab(); + assert!(app.cx.update(|_, cx| query.read(cx).marked()), "a pick marks the query"); + app.click("run"); + app.wait_idle(); + assert!(graph(&mut app).is_none(), "the run's rows take its place"); + assert!(!app.cx.update(|_, cx| query.read(cx).marked()), "and its mark goes with it"); +} + +// A pick keeps the keys in the editor; a caret move or an edit drops the mark and the pick. +#[gpui_kit::test] +fn a_pick_marks_the_query_until_the_caret_moves_or_the_text_changes(cx: &mut TestAppContext) { + let mut app = open(cx); + let query = app.connect(); + app.set_sql(JOIN); + app.keys("mod-shift-r"); + let graph = graph(&mut app).expect("the results show the graph"); + let state = |app: &mut Driver| app.cx.update(|_, cx| (query.read(cx).marked(), graph.read(cx).selected())); + app.click("ra-node-1"); + assert_eq!(state(&mut app), (true, Some(1)), "the join is marked"); + app.keys("right"); + assert_eq!(state(&mut app), (false, None), "the caret moved on"); + app.click("ra-node-1"); + assert_eq!(state(&mut app), (true, Some(1)), "picked again, it's marked again"); + app.keys("delete"); + assert_eq!(state(&mut app), (false, None), "the text changed under a caret that stayed"); +} + +// A pick in a graph of an edited statement says so and lets go. +#[gpui_kit::test] +fn a_pick_in_a_graph_of_an_edited_statement_asks_for_a_new_one(cx: &mut TestAppContext) { + let mut app = open(cx); + let query = app.connect(); + app.set_sql(JOIN); + app.keys("mod-shift-r"); + let graph = graph(&mut app).expect("the results show the graph"); + app.set_sql("SELECT * FROM things a JOIN things u ON u.id = a.id"); + app.click("ra-node-1"); + let state = app.cx.update(|_, cx| (query.read(cx).marked(), graph.read(cx).selected())); + assert_eq!(state, (false, None)); + let stale = app.cx.update(|_, cx| t(cx, "algebra.stale").to_string()); + assert!(app.error_toasts().contains(&stale), "{:?}", app.error_toasts()); +} diff --git a/crates/barsql-ui/src/scenarios/editor.rs b/crates/barsql-ui/src/scenarios/editor.rs index 20d19ab..9f67f14 100644 --- a/crates/barsql-ui/src/scenarios/editor.rs +++ b/crates/barsql-ui/src/scenarios/editor.rs @@ -87,9 +87,9 @@ fn the_editors_right_click_menu_selects_all(cx: &mut TestAppContext) { app.connect(); app.set_sql("SELECT 1 AS first;\nSELECT 2 AS second;"); app.cx.update(|_, cx| cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string("x".into()))); - // Run statement, Run all, Explain, Go to definition, Change all occurrences, Toggle comment, Format SQL, Cut, - // Copy, Paste, Find, Replace, then Select all. SQLite has no Explain analyze. - app.input_menu("query-editor", 12); + // Run statement, Run all, Explain, Relational algebra, Go to definition, Change all occurrences, Toggle comment, + // Format SQL, Cut, Copy, Paste, Find, Replace, then Select all. SQLite has no Explain analyze. + app.input_menu("query-editor", 13); let tab = app.tab(); let selected = app.cx.update(|_, cx| tab.read(cx).editor().read(cx).selected_text().to_string()); assert_eq!(selected, "SELECT 1 AS first;\nSELECT 2 AS second;"); diff --git a/crates/barsql-ui/src/scenarios/mod.rs b/crates/barsql-ui/src/scenarios/mod.rs index 333f8fa..5b93475 100644 --- a/crates/barsql-ui/src/scenarios/mod.rs +++ b/crates/barsql-ui/src/scenarios/mod.rs @@ -1,6 +1,7 @@ // Whole-window tests. `Driver` sends keys, clicks and menu actions to the window, on Env's SQLite database. mod driver; +mod algebra; mod connections; mod editor; #[cfg(feature = "e2e")] diff --git a/crates/barsql-ui/src/scenarios/plans.rs b/crates/barsql-ui/src/scenarios/plans.rs index 2a9c635..7196f26 100644 --- a/crates/barsql-ui/src/scenarios/plans.rs +++ b/crates/barsql-ui/src/scenarios/plans.rs @@ -31,15 +31,6 @@ fn explain_shows_an_estimated_plan_with_sqlites_note(cx: &mut TestAppContext) { assert!(rows(&mut app).iter().all(|(_, label, _)| !label.is_empty())); } -// SQLite can't analyze, so Explain has no menu: it would only repeat the button. -#[gpui_kit::test] -fn the_explain_button_has_no_menu_without_analyze(cx: &mut TestAppContext) { - let mut app = open(cx); - app.connect(); - assert!(app.shown("explain")); - assert!(!app.shown("explain-menu")); -} - #[gpui_kit::test] fn the_selected_node_shows_its_details_and_the_raw_plan(cx: &mut TestAppContext) { let mut app = open(cx); diff --git a/crates/barsql-ui/src/shortcuts.rs b/crates/barsql-ui/src/shortcuts.rs index 92c9b64..f197a30 100644 --- a/crates/barsql-ui/src/shortcuts.rs +++ b/crates/barsql-ui/src/shortcuts.rs @@ -69,6 +69,7 @@ impl ShortcutDef { "runAll" => Box::new(RunAll), "explainQuery" => Box::new(ExplainQuery), "explainAnalyze" => Box::new(ExplainAnalyze), + "showAlgebra" => Box::new(ShowAlgebra), "saveQuery" => Box::new(SaveQuery), "saveQueryAs" => Box::new(SaveQueryAs), "renameSavedQuery" => Box::new(RenameSavedQuery), @@ -113,7 +114,7 @@ const VIEW: Category = Category::View; const GLOBAL: Scope = Scope::Global; const EDITOR: Scope = Scope::Editor; -pub const SHORTCUTS: [ShortcutDef; 22] = [ +pub const SHORTCUTS: [ShortcutDef; 23] = [ def("quickSearch", TABS, GLOBAL, "p", CTRL), def("commandPalette", VIEW, GLOBAL, "p", CTRL_SHIFT), def("runSelection", QUERY, EDITOR, "Enter", CTRL), @@ -121,6 +122,7 @@ pub const SHORTCUTS: [ShortcutDef; 22] = [ def("explainQuery", QUERY, EDITOR, "e", CTRL_SHIFT), // Not Ctrl+Alt, since Windows reports AltGr as Ctrl+Alt and German AltGr+E types the euro sign. def("explainAnalyze", QUERY, EDITOR, "a", CTRL_SHIFT), + def("showAlgebra", QUERY, EDITOR, "r", CTRL_SHIFT), def("saveQuery", QUERY, EDITOR, "s", CTRL), def("saveQueryAs", QUERY, EDITOR, "s", CTRL_SHIFT), def("renameSavedQuery", QUERY, EDITOR, "F2", NONE), diff --git a/crates/barsql-ui/src/shortcuts/tests.rs b/crates/barsql-ui/src/shortcuts/tests.rs index 1021875..e93b6f6 100644 --- a/crates/barsql-ui/src/shortcuts/tests.rs +++ b/crates/barsql-ui/src/shortcuts/tests.rs @@ -26,7 +26,7 @@ fn default_bindings_are_distinct_and_never_ctrl_alt() { let default = def.default_binding(); assert!(!(default.ctrl && default.alt), "{} defaults to a Ctrl+Alt chord (AltGr on Windows)", def.id); } - assert_eq!(SHORTCUTS.len(), 22); + assert_eq!(SHORTCUTS.len(), 23); } #[test] diff --git a/crates/barsql-ui/src/window_state.rs b/crates/barsql-ui/src/window_state.rs index 3e1eff0..a44401e 100644 --- a/crates/barsql-ui/src/window_state.rs +++ b/crates/barsql-ui/src/window_state.rs @@ -118,11 +118,12 @@ fn normal(last: &WindowState, bounds: Bounds, work: Option Pixels { +// No ceiling: the window decides how much of a wide one fits. +pub fn stored_width(cx: &App, key: &str, default: f32, min: f32) -> Pixels { let width = setting(cx, key) .and_then(|raw| raw.trim().parse::().ok()) .filter(|width| width.is_finite()) - .map_or(default, |width| (width as f32).clamp(min, max)); + .map_or(default, |width| (width as f32).max(min)); px(width) } diff --git a/crates/barsql-ui/src/workspace.rs b/crates/barsql-ui/src/workspace.rs index 23a51f7..b561f4b 100644 --- a/crates/barsql-ui/src/workspace.rs +++ b/crates/barsql-ui/src/workspace.rs @@ -57,8 +57,9 @@ const SIDEBAR_OPEN_KEY: &str = "barsql-sidebar-open"; const JSON_OPEN_KEY: &str = "barsql-json-open"; const SIDEBAR_WIDTH_KEY: &str = "barsql-sidebar-w"; const JSON_WIDTH_KEY: &str = "barsql-json-w"; -const SIDEBAR_WIDTHS: (f32, f32, f32) = (280., 200., 520.); -const JSON_WIDTHS: (f32, f32, f32) = (320., 220., 640.); +// Default and least widths; the most leaves the editor CENTER_MIN. +const SIDEBAR_WIDTHS: (f32, f32) = (280., 200.); +const JSON_WIDTHS: (f32, f32) = (320., 220.); // Below this the JSON viewer steps aside until the window widens again. const CENTER_MIN: f32 = 400.; const CLOSED_TABS_LIMIT: usize = 10; @@ -269,6 +270,9 @@ pub struct Workspace { json_panel: Entity, json_open: bool, json_width: Pixels, + // The window width the panels last laid out at, and the side panels' widths then. + laid_out_at: Pixels, + drawn: (Pixels, Pixels), window_state: Option, window_save: Task<()>, focus: FocusHandle, @@ -685,6 +689,8 @@ impl Workspace { json_panel, json_open: setting_bool(cx, JSON_OPEN_KEY, false), json_width: panel_width(cx, JSON_WIDTH_KEY, JSON_WIDTHS), + laid_out_at: px(0.), + drawn: (px(0.), px(0.)), window_state: None, window_save: Task::ready(()), focus, @@ -790,8 +796,11 @@ impl Workspace { fn panels_resized(&mut self, sizes: &[Pixels], cx: &mut Context) { let store = |key: &str, width: Pixels| set_setting(cx, key, &(width.as_f32().round() as i64).to_string()); + // Only the panel the drag moved, so the other keeps a width the window cut short. + let moved = |width: Pixels, drawn: Pixels| (width - drawn).abs() > px(0.5); if self.sidebar_open && let Some(&width) = sizes.first() + && moved(width, self.drawn.0) { self.sidebar_width = width; store(SIDEBAR_WIDTH_KEY, width); @@ -799,6 +808,7 @@ impl Workspace { // The JSON panel is in the group only while it's open and has room. if sizes.len() == usize::from(self.sidebar_open) + 2 && let Some(&width) = sizes.last() + && moved(width, self.drawn.1) { self.json_width = width; store(JSON_WIDTH_KEY, width); @@ -2587,8 +2597,8 @@ fn snapshot_update_state(panel: &str) -> update_dialog::UpdateState { } } -fn panel_width(cx: &App, key: &str, (default, min, max): (f32, f32, f32)) -> Pixels { - window_state::stored_width(cx, key, default, min, max) +fn panel_width(cx: &App, key: &str, (default, min): (f32, f32)) -> Pixels { + window_state::stored_width(cx, key, default, min) } // A tab takes its connection's new settings. Where the connection lists every database, a tab stays on the @@ -2605,8 +2615,20 @@ impl Render for Workspace { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme().clone(); let title = SharedString::from("BarSQL"); - let sidebar = if self.sidebar_open { self.sidebar_width } else { px(0.) }; - let json_shown = self.json_open && window.viewport_size().width - sidebar - self.json_width >= px(CENTER_MIN); + let width = window.viewport_size().width; + // A panel keeps a width the window cut short, so a wider window lays them out again. + let cut = (self.sidebar_open && self.drawn.0 < self.sidebar_width) + || (self.drawn.1 > px(0.) && self.drawn.1 < self.json_width); + if width > self.laid_out_at && cut { + self.reset_panels(cx); + } + self.laid_out_at = width; + // Room for the side panels, sidebar first. + let room = width - px(CENTER_MIN); + let sidebar = if self.sidebar_open { self.sidebar_width.min(room.max(px(SIDEBAR_WIDTHS.1))) } else { px(0.) }; + let json_shown = self.json_open && room - sidebar >= px(JSON_WIDTHS.1); + let json = if json_shown { self.json_width.min(room - sidebar) } else { px(0.) }; + self.drawn = (sidebar, json); let main = match self.active_tab() { Some(tab) => v_flex() .size_full() @@ -2744,7 +2766,7 @@ impl Render for Workspace { panels.child( resizable_panel() .size(self.sidebar_width) - .size_range(px(SIDEBAR_WIDTHS.1)..px(SIDEBAR_WIDTHS.2)) + .size_range(px(SIDEBAR_WIDTHS.1)..(room - json).max(px(SIDEBAR_WIDTHS.1))) .fixed() .child(self.sidebar.clone()), ) @@ -2754,7 +2776,7 @@ impl Render for Workspace { panels.child( resizable_panel() .size(self.json_width) - .size_range(px(JSON_WIDTHS.1)..px(JSON_WIDTHS.2)) + .size_range(px(JSON_WIDTHS.1)..(room - sidebar).max(px(JSON_WIDTHS.1))) .fixed() .child(self.json_panel.clone()), ) diff --git a/crates/barsql-ui/src/workspace/tests.rs b/crates/barsql-ui/src/workspace/tests.rs index fe51e9a..e7cadc8 100644 --- a/crates/barsql-ui/src/workspace/tests.rs +++ b/crates/barsql-ui/src/workspace/tests.rs @@ -483,16 +483,16 @@ fn history_sql_lands_in_the_plain_query_tab(cx: &mut TestAppContext) { } #[gpui_kit::test] -fn panel_widths_come_back_clamped_and_drags_store_them(cx: &mut TestAppContext) { +fn panel_widths_come_back_no_narrower_than_their_least_and_drags_store_them(cx: &mut TestAppContext) { let env = Env::new(cx); - env.bar.set_setting("barsql-sidebar-w", "700").unwrap(); + env.bar.set_setting("barsql-sidebar-w", "150").unwrap(); env.bar.set_setting("barsql-json-w", "wide").unwrap(); let (workspace, cx) = open(cx); let widths = cx.update(|_, cx| { let workspace = workspace.read(cx); (workspace.sidebar_width, workspace.json_width) }); - assert_eq!(widths, (px(520.), px(320.))); + assert_eq!(widths, (px(200.), px(320.))); workspace.update(cx, |workspace, cx| { workspace.json_open = true; @@ -531,6 +531,37 @@ fn the_side_panels_keep_their_widths_when_the_window_resizes(cx: &mut TestAppCon } } +// Side panels grow while the editor keeps 400px; a width that doesn't fit waits for a wider window. +#[gpui_kit::test] +fn side_panels_grow_as_long_as_the_editor_keeps_its_room(cx: &mut TestAppContext) { + let env = Env::new(cx); + env.bar.set_setting("barsql-sidebar-w", "1500").unwrap(); + env.bar.set_setting("barsql-json-w", "2000").unwrap(); + let (workspace, cx) = open(cx); + cx.simulate_resize(size(px(1200.), px(800.))); + assert_eq!(panel_widths(cx), (Some(px(800.)), None), "all but the editor's 400px"); + cx.simulate_resize(size(px(2400.), px(800.))); + assert_eq!(panel_widths(cx), (Some(px(1500.)), None), "its own width once there's room"); + workspace.update_in(cx, |workspace, window, cx| workspace.toggle_json_panel(window, cx)); + // 500px, and its header is inside its 1px border. + assert_eq!(panel_widths(cx), (Some(px(1500.)), Some(px(499.))), "the JSON panel takes what's left"); +} + +// A drag saves only the panel it moved, so the other keeps a width the window cut short. +#[gpui_kit::test] +fn a_drag_leaves_the_other_panels_saved_width_alone(cx: &mut TestAppContext) { + let env = Env::new(cx); + env.bar.set_setting("barsql-json-w", "2000").unwrap(); + let (workspace, cx) = open(cx); + workspace.update_in(cx, |workspace, window, cx| workspace.toggle_json_panel(window, cx)); + cx.simulate_resize(size(px(1600.), px(800.))); + assert_eq!(panel_widths(cx).1, Some(px(919.)), "920px, all the editor leaves"); + workspace.update(cx, |workspace, cx| workspace.panels_resized(&[px(300.), px(400.), px(920.)], cx)); + let settings = env.bar.settings(); + let saved = |key: &str| settings.get(key).map(String::as_str); + assert_eq!((saved("barsql-sidebar-w"), saved("barsql-json-w")), (Some("300"), Some("2000"))); +} + // Without room for the editor beside both side panels, the JSON panel steps aside, and comes back at its own width. #[gpui_kit::test] fn the_json_panel_steps_aside_on_a_narrow_window(cx: &mut TestAppContext) { diff --git a/guide/README.md b/guide/README.md index d0f70f4..4839c4e 100644 --- a/guide/README.md +++ b/guide/README.md @@ -6,7 +6,7 @@ Everything BarSQL does, one area per page. For screenshots, see the [README](../ | ---- | -------------- | | [⬇️ Installing](install.md) | Which file to pick, Homebrew, Scoop, the Linux install script, the first launch, uninstalling | | [🔌 Connections](connections.md) | Folders, read-only mode, every database on a server, SSL and TLS, SSH tunnels, SQLite extensions, engine notes | -| [🧠 SQL Editor](editor.md) | Autocomplete, multiple cursors, scripts, transactions, the query plan viewer, saved queries and history | +| [🧠 SQL Editor](editor.md) | Autocomplete, multiple cursors, scripts, transactions, the query plan viewer, the relational algebra graph, saved queries and history | | [🗃️ Schema Explorer](schema.md) | The databases list, the schema tree, ER diagrams, schema compare, Copy DDL, schema changes, the structure editor, table backups | | [📊 Results Grid](results.md) | Sorting, selection stats, quick charts, the cell and JSON viewers, editing data | | [📥 Import & Export](import-export.md) | CSV and SQL import, export formats | diff --git a/guide/app.md b/guide/app.md index 7613a23..389f996 100644 --- a/guide/app.md +++ b/guide/app.md @@ -28,6 +28,7 @@ The in-app shortcuts editor remaps all of these except the editor's own keys: go | Run all statements | `Ctrl/⌘ + Shift + Enter` | | Explain query plan | `Ctrl/⌘ + Shift + E` | | Explain query plan (analyze) | `Ctrl/⌘ + Shift + A` | +| Relational algebra graph | `Ctrl/⌘ + Shift + R` | | Save query | `Ctrl/⌘ + S` | | Save query as | `Ctrl/⌘ + Shift + S` | | Rename saved query | `F2` | diff --git a/guide/editor.md b/guide/editor.md index 7689d65..c8cf67a 100644 --- a/guide/editor.md +++ b/guide/editor.md @@ -22,9 +22,10 @@ - **Pinned transactions** per tab - run `BEGIN` / `COMMIT` / `ROLLBACK` as SQL or from the toolbar; queries run inside the open transaction until you commit or roll back (on every engine that holds one: not ClickHouse or Turso). Closing the tab, quitting or restarting for an update asks before rolling it back. On macOS so do the Dock's Quit, logging out and shutting down, which BarSQL cancels to ask. Renaming a connection or moving it to a folder keeps it open; disconnecting, or changing how it connects, rolls its tabs' transactions back and says so. Savepoints you make last until the transaction ends, across runs - **Another database for the tab** - on a connection with **Show all databases** on, the database button in the toolbar moves the tab to another of the server's databases, and suggestions follow it there. It waits while the tab has an open transaction or staged edits - **Query plan viewer** (`Ctrl/⌘+Shift+E`) - see below +- **Relational algebra graph** (`Ctrl/⌘+Shift+R`) - see below - `UPDATE` / `DELETE` / `INSERT` with **`RETURNING`** flow back to the Results Grid - Gutter icons to run individual statements -- Right-click menu with run, explain, go to definition, **change all occurrences**, toggle comment and **format SQL** +- Right-click menu with run, explain, **relational algebra**, go to definition, **change all occurrences**, toggle comment and **format SQL** - **Remappable keyboard shortcuts** ## 🧭 Query Plan Viewer @@ -44,6 +45,19 @@ Plans are outputs like any other, so a script can mix them freely - `SELECT …; - Per engine: PostgreSQL `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`, MySQL `EXPLAIN FORMAT=JSON` and `EXPLAIN ANALYZE`, MariaDB `ANALYZE FORMAT=JSON`, SQL Server's Showplan XML (`SET SHOWPLAN_XML` for an estimate, `SET STATISTICS XML` for actuals), SQLite and libSQL `EXPLAIN QUERY PLAN`, ClickHouse `EXPLAIN PLAN json = 1, indexes = 1` (plan shape and index use only - SQLite and ClickHouse report no cost or timings) - **Analyzing a write never leaves data behind** - `EXPLAIN ANALYZE` executes the statement, so a write runs inside a transaction that is always rolled back (and says so). On a tab with an open transaction it runs there, exactly where a plain **Run** would have +## 🧮 Relational Algebra Graph + +**Relational algebra** (`Ctrl/⌘+Shift+R`, or the menu on the toolbar's Explain button) draws the selected text, or the statement under the cursor, as a tree of relational algebra operators in the results, where a plan would show. Nothing runs - BarSQL reads the query itself, in your database's dialect, and the graph stays until the next run. + +Tables sit along the bottom, and each operator above what it reads: ⋈ joins, × products, σ selections, γ groupings, π projections, δ distinct, τ sorts, `limit`, ρ renames for subqueries and CTEs, and ∪ ∩ − for set operations. A CTE is drawn where it's used. + +- **Boxes say what they do** - projections, groupings and sorts list their items as pills, a selection puts each condition of its `AND` on its own row, and a join names its kind (`LEFT`, `CROSS APPLY`, …) in its header with its condition below. Tables show their estimated rows where the engine keeps them +- **Hover for the columns** - rest the pointer on a box and a card beside it lists the columns that come out of it, with their types +- **Click to find it in the query** - the text a box comes from is marked in the editor in the box's colour, and the caret moves there. Moving the caret or typing clears the mark; if the statement itself changed since the graph was drawn, the click says so +- **Get around** as in the ER diagram - drag to pan, zoom with the buttons, `⌘/Ctrl`+scroll or a pinch, and the fit button to see it all. Search finds operators and tables by name or by any text in their boxes, and Enter or Shift+Enter steps through the hits +- **Save as SVG** writes the graph as drawn +- Only a single query can be drawn - a `SELECT` with its `WITH` and set operations, or a `VALUES` list. Anything else, or text it can't read, says why + ## 📚 Query Library & History - **Saved queries** - name, filter, sort, link tabs with dirty-state tracking