From aece06c3374455f5da347617deea5a2c8e197f73 Mon Sep 17 00:00:00 2001 From: Bare7a Date: Tue, 1 Dec 2026 00:24:16 +0200 Subject: [PATCH] feat(BAR-54): Adds a visual query builder --- crates/barsql-app/src/lib.rs | 3 +- crates/barsql-sql/src/design.rs | 1384 +++++++++++++++++ crates/barsql-sql/src/lib.rs | 1 + crates/barsql-sql/src/select.rs | 73 +- crates/barsql-sql/tests/design.rs | 463 ++++++ crates/barsql-storage/src/lib.rs | 4 +- crates/barsql-storage/src/session.rs | 38 + crates/barsql-ui/locales/bg.json | 73 + crates/barsql-ui/locales/de.json | 73 + crates/barsql-ui/locales/en.json | 73 + crates/barsql-ui/locales/es.json | 73 + crates/barsql-ui/src/actions.rs | 1 + crates/barsql-ui/src/algebra_graph.rs | 5 +- crates/barsql-ui/src/assets.rs | 1 + crates/barsql-ui/src/command_palette.rs | 1 + crates/barsql-ui/src/completion.rs | 9 +- crates/barsql-ui/src/editor_commands.rs | 2 +- crates/barsql-ui/src/er_diagram.rs | 7 +- crates/barsql-ui/src/er_diagram/layout.rs | 50 +- crates/barsql-ui/src/er_diagram/tests.rs | 26 + crates/barsql-ui/src/er_diagram/zoom.rs | 5 + crates/barsql-ui/src/form.rs | 50 +- crates/barsql-ui/src/lib.rs | 2 + crates/barsql-ui/src/list_nav.rs | 4 +- crates/barsql-ui/src/query_builder.rs | 1289 +++++++++++++++ .../barsql-ui/src/query_builder/geometry.rs | 191 +++ crates/barsql-ui/src/query_builder/panel.rs | 867 +++++++++++ crates/barsql-ui/src/query_builder/tests.rs | 645 ++++++++ crates/barsql-ui/src/query_tab.rs | 504 ++++-- crates/barsql-ui/src/saved_panel.rs | 2 +- crates/barsql-ui/src/scenarios/algebra.rs | 15 + crates/barsql-ui/src/scenarios/editor.rs | 6 +- crates/barsql-ui/src/scenarios/engines.rs | 6 +- crates/barsql-ui/src/scenarios/import.rs | 2 +- crates/barsql-ui/src/scenarios/schema.rs | 14 +- crates/barsql-ui/src/scenarios/structure.rs | 2 +- crates/barsql-ui/src/schema_tree.rs | 29 + crates/barsql-ui/src/schema_tree/tests.rs | 15 + crates/barsql-ui/src/shortcuts.rs | 25 +- crates/barsql-ui/src/shortcuts/tests.rs | 24 +- crates/barsql-ui/src/shortcuts_dialog.rs | 19 +- .../barsql-ui/src/shortcuts_dialog/tests.rs | 15 + crates/barsql-ui/src/sidebar.rs | 5 + crates/barsql-ui/src/test_support.rs | 1 + crates/barsql-ui/src/tokens.rs | 2 + crates/barsql-ui/src/workspace.rs | 113 +- crates/barsql-ui/src/workspace/tests.rs | 66 +- guide/README.md | 2 +- guide/app.md | 1 + guide/editor.md | 20 +- 50 files changed, 6063 insertions(+), 238 deletions(-) create mode 100644 crates/barsql-sql/src/design.rs create mode 100644 crates/barsql-sql/tests/design.rs create mode 100644 crates/barsql-ui/src/query_builder.rs create mode 100644 crates/barsql-ui/src/query_builder/geometry.rs create mode 100644 crates/barsql-ui/src/query_builder/panel.rs create mode 100644 crates/barsql-ui/src/query_builder/tests.rs diff --git a/crates/barsql-app/src/lib.rs b/crates/barsql-app/src/lib.rs index 6853f91..4df08bb 100644 --- a/crates/barsql-app/src/lib.rs +++ b/crates/barsql-app/src/lib.rs @@ -30,7 +30,8 @@ pub use backup::{BackupOutcome, BackupRequest}; pub use barsql_db::tls::install_default_provider; pub use barsql_io::{CsvOptions, ImportPreview}; pub use barsql_storage::{ - ConnectionFolder, DiagramRef, EditorSession, EditorTab, HISTORY_LIMIT, StructureRef, TableViewRef, + BuilderRef, ConnectionFolder, DiagramRef, EditorSession, EditorTab, HISTORY_LIMIT, StructureRef, TablePlace, + TableViewRef, }; pub use edits::{ApplyError, ResultEdits, ResultTable, traced_beside_run, traced_select}; pub use events::{ diff --git a/crates/barsql-sql/src/design.rs b/crates/barsql-sql/src/design.rs new file mode 100644 index 0000000..9ef0354 --- /dev/null +++ b/crates/barsql-sql/src/design.rs @@ -0,0 +1,1384 @@ +use std::ops::Range; + +use barsql_core::{DriverType, SqlDialect}; + +use crate::lang::quoting::format_sql_identifier; +use crate::lang::tokens::{Token, TokenKind, tokenize_with}; +use crate::lex::LexRules; +use crate::select::{self, Expr, ExprKind, Ident, OrderKey, ParseError, SetExpr, SetOp, TableFactor}; + +// A SELECT as the visual builder edits it; what it can't take apart stays as written. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Design { + pub tables: Vec, + // Empty for `*`. + pub items: Vec, + pub distinct: bool, + pub filters: Vec, + pub group_by: Vec, + pub having: Vec, + pub order_by: Vec, + pub limit: Option, + pub offset: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Table { + // The schema, or database and schema, it's named with. + pub qualifier: Vec, + pub name: String, + pub alias: Option, + // How it joins the tables before it; None is a cross join, and always so for the first. + pub join: Option, +} + +impl Table { + pub fn key(&self) -> &str { + self.alias.as_deref().unwrap_or(&self.name) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Join { + pub kind: JoinKind, + pub on: Vec, + pub using: Vec, + // ON terms that aren't one column equal to another. + pub extra: Vec, +} + +impl Join { + fn is_empty(&self) -> bool { + self.on.is_empty() && self.using.is_empty() && self.extra.is_empty() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JoinKind { + Inner, + Left, + Right, + Full, +} + +impl JoinKind { + const ALL: [Self; 4] = [Self::Inner, Self::Left, Self::Right, Self::Full]; + + pub fn keyword(self) -> &'static str { + match self { + Self::Inner => "INNER", + Self::Left => "LEFT", + Self::Right => "RIGHT", + Self::Full => "FULL", + } + } + + // MySQL has no FULL JOIN. + pub fn offered(dialect: SqlDialect) -> &'static [Self] { + match dialect { + SqlDialect::MySql => &Self::ALL[..3], + _ => &Self::ALL, + } + } +} + +// `left = right`, `left` being the joined table's column. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pair { + pub left: ColumnRef, + pub right: ColumnRef, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ColumnRef { + pub table: usize, + pub column: String, +} + +impl ColumnRef { + pub fn new(table: usize, column: impl Into) -> Self { + Self { table, column: column.into() } + } + + pub fn same(&self, other: &Self) -> bool { + self.table == other.table && self.column.eq_ignore_ascii_case(&other.column) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Aggregate { + Count, + CountDistinct, + Sum, + Avg, + Min, + Max, +} + +impl Aggregate { + pub const ALL: [Self; 6] = [Self::Count, Self::CountDistinct, Self::Sum, Self::Avg, Self::Min, Self::Max]; + + pub fn name(self) -> &'static str { + match self { + Self::Count => "COUNT", + Self::CountDistinct => "COUNT DISTINCT", + Self::Sum => "SUM", + Self::Avg => "AVG", + Self::Min => "MIN", + Self::Max => "MAX", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Operand { + Column(ColumnRef), + // COUNT(*) when `of` is None. + Aggregate { func: Aggregate, of: Option }, + Expr(String), + // A picked item by its name in the results. + Alias(String), +} + +impl Operand { + pub fn column_ref(&self) -> Option<&ColumnRef> { + match self { + Self::Column(c) | Self::Aggregate { of: Some(c), .. } => Some(c), + _ => None, + } + } + + fn column_mut(&mut self) -> Option<&mut ColumnRef> { + match self { + Self::Column(c) | Self::Aggregate { of: Some(c), .. } => Some(c), + _ => None, + } + } + + pub fn reads(&self, column: &ColumnRef) -> bool { + self.column_ref().is_some_and(|c| c.same(column)) + } + + pub fn is_aggregate(&self) -> bool { + matches!(self, Self::Aggregate { .. }) + } + + // An aggregate the builder took apart, or SQL that calls one. + fn aggregates(&self) -> bool { + match self { + Self::Aggregate { .. } => true, + Self::Expr(text) => calls_aggregate(text), + _ => false, + } + } + + // What GROUP BY can take: no aggregate, window, constant or position. + fn groups(&self) -> bool { + match self { + Self::Column(_) => true, + Self::Expr(text) => { + let tokens = select::code_tokens(text, LexRules::of(SqlDialect::Postgres)); + let constant = + matches!(tokens.as_slice(), [one] if matches!(one.kind, TokenKind::Number | TokenKind::String)); + !constant && !calls_aggregate(text) && !tokens.iter().any(|t| t.is_keyword("over")) + } + Self::Aggregate { .. } | Self::Alias(_) => false, + } + } + + // As SQL, with each column written by `column`. + pub fn format_with(&self, column: impl Fn(&ColumnRef) -> String) -> String { + match self { + Self::Column(c) => column(c), + Self::Aggregate { func, of } => { + let arg = of.as_ref().map_or_else(|| "*".to_string(), &column); + match func { + Aggregate::CountDistinct => format!("COUNT(DISTINCT {arg})"), + func => format!("{}({arg})", func.name()), + } + } + Self::Expr(text) | Self::Alias(text) => text.clone(), + } + } +} + +// Aggregates the engines share, and common ones of their own. +const AGGREGATES: &[&str] = &[ + "approx_count_distinct", + "argmax", + "argmin", + "array_agg", + "avg", + "avgif", + "bit_and", + "bit_or", + "bit_xor", + "bool_and", + "bool_or", + "checksum_agg", + "corr", + "count", + "count_big", + "countif", + "covar_pop", + "covar_samp", + "every", + "group_concat", + "grouparray", + "groupuniqarray", + "json_agg", + "json_arrayagg", + "json_object_agg", + "json_objectagg", + "jsonb_agg", + "jsonb_object_agg", + "listagg", + "max", + "maxif", + "median", + "min", + "minif", + "mode", + "percentile_cont", + "percentile_disc", + "quantile", + "quantiles", + "stddev", + "stddev_pop", + "stddev_samp", + "stdev", + "stdevp", + "string_agg", + "sum", + "sumif", + "topk", + "uniq", + "uniqexact", + "var", + "var_pop", + "var_samp", + "variance", + "varp", + "xmlagg", +]; + +// A call to an aggregate that isn't a window function's. +fn calls_aggregate(text: &str) -> bool { + let tokens = select::code_tokens(text, LexRules::of(SqlDialect::Postgres)); + (0..tokens.len()).any(|ix| { + let token = &tokens[ix]; + if token.kind != TokenKind::Ident || !tokens.get(ix + 1).is_some_and(|t| t.is_punct("(")) { + return false; + } + if !AGGREGATES.contains(&token.lower.as_str()) || (ix > 0 && tokens[ix - 1].is_punct(".")) { + return false; + } + let (mut depth, mut commas, mut end) = (0usize, 0usize, tokens.len()); + for (at, token) in tokens.iter().enumerate().skip(ix + 1) { + if token.is_punct("(") { + depth += 1; + } else if token.is_punct(")") { + depth = depth.saturating_sub(1); + if depth == 0 { + end = at; + break; + } + } else if depth == 1 && token.is_punct(",") { + commas += 1; + } + } + // SQLite's MIN(a, b) and MAX(a, b) compare their arguments. + let scalar = matches!(token.lower.as_str(), "min" | "max") && commas > 0; + let mut next = end + 1; + if tokens.get(next).is_some_and(|t| t.is_keyword("filter")) { + next += 1; + let mut depth = 0usize; + while let Some(token) = tokens.get(next) { + next += 1; + depth = match () { + _ if token.is_punct("(") => depth + 1, + _ if token.is_punct(")") => depth.saturating_sub(1), + _ => depth, + }; + if depth == 0 { + break; + } + } + } + !scalar && !tokens.get(next).is_some_and(|t| t.is_keyword("over")) + }) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Item { + // `*`, or one table's `t.*`. + All(Option), + Value { value: Operand, alias: Option }, +} + +impl Item { + pub fn column(column: ColumnRef) -> Self { + Self::Value { value: Operand::Column(column), alias: None } + } + + pub fn value(&self) -> Option<&Operand> { + match self { + Self::Value { value, .. } => Some(value), + Self::All(_) => None, + } + } + + pub fn is_aggregate(&self) -> bool { + self.value().is_some_and(Operand::is_aggregate) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Op { + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + Like, + NotLike, + ILike, + NotILike, + In, + NotIn, + IsNull, + IsNotNull, +} + +impl Op { + pub fn sql(self) -> &'static str { + match self { + Self::Eq => "=", + Self::Ne => "<>", + Self::Lt => "<", + Self::Le => "<=", + Self::Gt => ">", + Self::Ge => ">=", + Self::Like => "LIKE", + Self::NotLike => "NOT LIKE", + Self::ILike => "ILIKE", + Self::NotILike => "NOT ILIKE", + Self::In => "IN", + Self::NotIn => "NOT IN", + Self::IsNull => "IS NULL", + Self::IsNotNull => "IS NOT NULL", + } + } + + pub fn takes_value(self) -> bool { + !matches!(self, Self::IsNull | Self::IsNotNull) + } + + const ALL: [Self; 14] = [ + Self::Eq, + Self::Ne, + Self::Lt, + Self::Le, + Self::Gt, + Self::Ge, + Self::Like, + Self::NotLike, + Self::ILike, + Self::NotILike, + Self::In, + Self::NotIn, + Self::IsNull, + Self::IsNotNull, + ]; + + pub fn offered(dialect: SqlDialect) -> Vec { + let ilike = matches!(dialect, SqlDialect::Postgres | SqlDialect::ClickHouse); + Self::ALL.into_iter().filter(|op| ilike || !matches!(op, Self::ILike | Self::NotILike)).collect() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Condition { + // `value` is SQL as typed, left out of the query while empty. + Compare { left: Operand, op: Op, value: String }, + Raw(String), +} + +impl Condition { + fn left(&self) -> Option<&Operand> { + match self { + Self::Compare { left, .. } => Some(left), + Self::Raw(_) => None, + } + } + + pub fn complete(&self) -> bool { + match self { + Self::Compare { op, value, .. } => !op.takes_value() || !value.trim().is_empty(), + Self::Raw(text) => !text.trim().is_empty(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sort { + pub by: Operand, + pub desc: bool, + // NULLS FIRST and the like, as written. + pub extra: String, +} + +impl Design { + // Another copy of a table gets a numbered alias. + pub fn add_table(&mut self, qualifier: Vec, name: &str) -> usize { + let taken = |key: &str, tables: &[Table]| tables.iter().any(|t| t.key().eq_ignore_ascii_case(key)); + let alias = match taken(name, &self.tables) { + true => (2..).map(|n| format!("{name}{n}")).find(|alias| !taken(alias, &self.tables)), + false => None, + }; + self.tables.push(Table { qualifier, name: name.to_string(), alias, join: None }); + self.tables.len() - 1 + } + + // Takes what reads the table with it. + pub fn remove_table(&mut self, ix: usize) { + if ix >= self.tables.len() { + return; + } + let was = self.aggregated(); + self.tables.remove(ix); + let gone = |operand: &Operand| operand.column_ref().is_some_and(|c| c.table == ix); + self.items.retain(|item| match item { + Item::All(table) => *table != Some(ix), + Item::Value { value, .. } => !gone(value), + }); + for list in [&mut self.filters, &mut self.having] { + list.retain(|condition| !condition.left().is_some_and(&gone)); + } + self.group_by.retain(|key| !gone(key)); + self.order_by.retain(|sort| !gone(&sort.by)); + for table in &mut self.tables { + if let Some(join) = &mut table.join { + join.on.retain(|pair| pair.left.table != ix && pair.right.table != ix); + } + } + self.each_ref(&mut |table| { + if *table > ix { + *table -= 1; + } + }); + if let Some(first) = self.tables.first_mut() { + first.join = None; + } + for table in &mut self.tables { + if table.join.as_ref().is_some_and(Join::is_empty) { + table.join = None; + } + } + self.prune_aliases(); + self.regroup(was); + } + + fn each_ref(&mut self, f: &mut dyn FnMut(&mut usize)) { + fn operand(operand: &mut Operand, f: &mut dyn FnMut(&mut usize)) { + if let Some(column) = operand.column_mut() { + f(&mut column.table); + } + } + for item in &mut self.items { + match item { + Item::All(Some(table)) => f(table), + Item::All(None) => {} + Item::Value { value, .. } => operand(value, f), + } + } + for condition in self.filters.iter_mut().chain(self.having.iter_mut()) { + if let Condition::Compare { left, .. } = condition { + operand(left, f); + } + } + for key in &mut self.group_by { + operand(key, f); + } + for sort in &mut self.order_by { + operand(&mut sort.by, f); + } + for join in self.tables.iter_mut().filter_map(|table| table.join.as_mut()) { + for pair in &mut join.on { + f(&mut pair.left.table); + f(&mut pair.right.table); + } + } + } + + pub fn picked(&self, column: &ColumnRef) -> bool { + self.items.iter().filter_map(Item::value).any(|value| value.reads(column)) + } + + pub fn aggregate_of(&self, column: &ColumnRef) -> Option { + self.items.iter().filter_map(Item::value).find_map(|value| match value { + Operand::Aggregate { func, of: Some(c) } if c.same(column) => Some(*func), + _ => None, + }) + } + + pub fn sort_of(&self, column: &ColumnRef) -> Option { + self.order_by.iter().find(|sort| matches!(&sort.by, Operand::Column(c) if c.same(column))).map(|sort| sort.desc) + } + + pub fn filters_on(&self, column: &ColumnRef) -> bool { + self.filters.iter().chain(&self.having).filter_map(Condition::left).any(|left| left.reads(column)) + } + + // Picked, joined on, filtered, grouped or sorted by. + pub fn uses(&self, column: &ColumnRef) -> bool { + let joined = self.tables.iter().enumerate().any(|(ix, table)| { + table.join.as_ref().is_some_and(|join| { + let using = (column.table == ix || column.table + 1 == ix) + && join.using.iter().any(|name| name.eq_ignore_ascii_case(&column.column)); + using || join.on.iter().any(|pair| pair.left.same(column) || pair.right.same(column)) + }) + }); + joined + || self.picked(column) + || self.filters_on(column) + || self.group_by.iter().any(|key| key.reads(column)) + || self.order_by.iter().any(|sort| sort.by.reads(column)) + } + + // Picks the column, or drops every item that reads it. + pub fn toggle_column(&mut self, column: ColumnRef) { + let was = self.aggregated(); + let before = self.items.len(); + self.items.retain(|item| !item.value().is_some_and(|value| value.reads(&column))); + if self.items.len() == before { + self.items.push(Item::column(column)); + } + self.prune_aliases(); + self.regroup(was); + } + + // Joins the later table on the pair; false if it already is, or both are one table. + pub fn link(&mut self, a: ColumnRef, b: ColumnRef) -> bool { + let len = self.tables.len(); + if a.table == b.table || a.table >= len || b.table >= len { + return false; + } + let (earlier, later) = if a.table < b.table { (a, b) } else { (b, a) }; + // USING joins a table to the one before it on the columns of one name. + let same = earlier.table + 1 == later.table && earlier.column.eq_ignore_ascii_case(&later.column); + let join = self.tables[later.table].join.get_or_insert_with(|| Join { + kind: JoinKind::Inner, + on: vec![], + using: vec![], + extra: vec![], + }); + if same && join.using.iter().any(|name| name.eq_ignore_ascii_case(&later.column)) { + return false; + } + if same && !join.using.is_empty() && join.on.is_empty() { + join.using.push(later.column); + return true; + } + // ON and USING don't mix, so USING's columns become pairs. + for column in std::mem::take(&mut join.using) { + join.on.push(Pair { + left: ColumnRef::new(later.table, &column), + right: ColumnRef::new(later.table - 1, column), + }); + } + let exists = join.on.iter().any(|pair| { + (pair.left.same(&later) && pair.right.same(&earlier)) + || (pair.left.same(&earlier) && pair.right.same(&later)) + }); + if exists { + return false; + } + join.on.push(Pair { left: later, right: earlier }); + true + } + + pub fn set_join_kind(&mut self, table: usize, kind: JoinKind) { + if let Some(join) = self.tables.get_mut(table).and_then(|t| t.join.as_mut()) { + join.kind = kind; + } + } + + // None turns an aggregate back into its column, which COUNT(*) hasn't. + pub fn set_aggregate(&mut self, item: usize, func: Option) { + let was = self.aggregated(); + let Some(Item::Value { value, .. }) = self.items.get_mut(item) else { return }; + let next = match (value.clone(), func) { + (Operand::Column(c) | Operand::Aggregate { of: Some(c), .. }, Some(func)) => { + Operand::Aggregate { func, of: Some(c) } + } + (Operand::Aggregate { of: Some(c), .. }, None) => Operand::Column(c), + _ => return, + }; + *value = next; + self.regroup(was); + } + + pub fn remove_item(&mut self, ix: usize) { + if ix < self.items.len() { + let was = self.aggregated(); + self.items.remove(ix); + self.prune_aliases(); + self.regroup(was); + } + } + + pub fn move_item(&mut self, from: usize, to: usize) { + if shift(&mut self.items, from, to) { + self.regroup(self.aggregated()); + } + } + + pub fn add_item(&mut self, item: Item) { + let was = self.aggregated(); + self.items.push(item); + self.regroup(was); + } + + // Sorts, keys and filters by the old name follow it, or read the value once the name goes. + pub fn set_alias(&mut self, ix: usize, alias: String) { + let Some(Item::Value { value, alias: slot }) = self.items.get_mut(ix) else { return }; + let alias = Some(alias).filter(|alias| !alias.trim().is_empty()); + let (old, value) = (std::mem::replace(slot, alias.clone()), value.clone()); + let Some(old) = old.filter(|old| alias.as_ref() != Some(old)) else { return }; + let to = alias.map_or(value, Operand::Alias); + let named = |operand: &Operand| matches!(operand, Operand::Alias(name) if name.eq_ignore_ascii_case(&old)); + for operand in self.alias_refs() { + if named(operand) { + *operand = to.clone(); + } + } + } + + // Wherever a picked item can be named by its alias. + fn alias_refs(&mut self) -> impl Iterator { + let conditions = + self.filters.iter_mut().chain(self.having.iter_mut()).filter_map(|condition| match condition { + Condition::Compare { left, .. } => Some(left), + Condition::Raw(_) => None, + }); + conditions.chain(self.group_by.iter_mut()).chain(self.order_by.iter_mut().map(|sort| &mut sort.by)) + } + + // Drops what names an alias no item has any more. + fn prune_aliases(&mut self) { + let names: Vec = self + .items + .iter() + .filter_map(|item| match item { + Item::Value { alias: Some(alias), .. } => Some(alias.to_lowercase()), + _ => None, + }) + .collect(); + let stale = + |operand: &Operand| matches!(operand, Operand::Alias(name) if !names.contains(&name.to_lowercase())); + for list in [&mut self.filters, &mut self.having] { + list.retain(|condition| !condition.left().is_some_and(&stale)); + } + self.group_by.retain(|key| !stale(key)); + self.order_by.retain(|sort| !stale(&sort.by)); + } + + // Whether anything aggregates: a picked value, a group filter or a sort. + pub fn aggregated(&self) -> bool { + let having = self.having.iter().any(|condition| match condition { + Condition::Compare { left, .. } => left.aggregates(), + Condition::Raw(text) => calls_aggregate(text), + }); + self.items.iter().filter_map(Item::value).any(Operand::aggregates) + || having + || self.order_by.iter().any(|sort| sort.by.aggregates()) + } + + // Sorts by the column, the other way round, or not at all. + pub fn sort_column(&mut self, column: ColumnRef, desc: Option) { + let at = self.order_by.iter().position(|sort| matches!(&sort.by, Operand::Column(c) if c.same(&column))); + match (at, desc) { + (Some(at), Some(desc)) => self.order_by[at].desc = desc, + (Some(at), None) => { + self.order_by.remove(at); + } + (None, Some(desc)) => self.order_by.push(Sort { by: Operand::Column(column), desc, extra: String::new() }), + (None, None) => {} + } + } + + // Picked values group while anything aggregates; keys no item picks stay. + fn regroup(&mut self, was: bool) { + let now = self.aggregated(); + if !was && !now { + return; + } + let mut plain: Vec = vec![]; + for value in self.items.iter().filter_map(Item::value) { + if value.groups() && !plain.contains(value) { + plain.push(value.clone()); + } + } + let extras: Vec = self.group_by.iter().filter(|key| !plain.contains(key)).cloned().collect(); + self.group_by = if now { plain.into_iter().chain(extras).collect() } else { extras }; + } + + pub fn item_label(&self, item: &Item, driver: &DriverType) -> String { + let render = Render::new(self, driver); + match item { + Item::Value { value, .. } => render.operand(value), + all => render.item(all), + } + } +} + +// Moves the entry at `from` into `to`'s place; false when nothing moves. +pub fn shift(list: &mut Vec, from: usize, to: usize) -> bool { + if from >= list.len() || to >= list.len() || from == to { + return false; + } + let moved = list.remove(from); + list.insert(to, moved); + true +} + +// Items on one line up to here, else one a line. +const LINE: usize = 80; + +pub fn render(design: &Design, driver: &DriverType) -> String { + Render::new(design, driver).query() +} + +struct Render<'a> { + design: &'a Design, + driver: &'a DriverType, + dialect: SqlDialect, +} + +impl<'a> Render<'a> { + fn new(design: &'a Design, driver: &'a DriverType) -> Self { + Self { design, driver, dialect: driver.dialect().unwrap_or(SqlDialect::Postgres) } + } + + fn ident(&self, name: &str) -> String { + format_sql_identifier(name, self.driver) + } + + fn table_name(&self, table: &Table) -> String { + table.qualifier.iter().chain([&table.name]).map(|part| self.ident(part)).collect::>().join(".") + } + + // What table `ix`'s columns are qualified with: its alias, or its name, with the schema if two share it. + fn reference(&self, ix: usize) -> String { + let Some(table) = self.design.tables.get(ix) else { return String::new() }; + if let Some(alias) = &table.alias { + return self.ident(alias); + } + let twin = self + .design + .tables + .iter() + .enumerate() + .any(|(other, t)| other != ix && t.alias.is_none() && t.name.eq_ignore_ascii_case(&table.name)); + if twin { self.table_name(table) } else { self.ident(&table.name) } + } + + fn column(&self, column: &ColumnRef) -> String { + let name = self.ident(&column.column); + match self.design.tables.len() > 1 { + true => format!("{}.{name}", self.reference(column.table)), + false => name, + } + } + + fn operand(&self, operand: &Operand) -> String { + match operand { + Operand::Alias(name) => self.ident(name), + operand => operand.format_with(|column| self.column(column)), + } + } + + fn item(&self, item: &Item) -> String { + match item { + Item::All(None) => "*".into(), + Item::All(Some(table)) => format!("{}.*", self.reference(*table)), + Item::Value { value, alias: Some(alias) } => format!("{} AS {}", self.operand(value), self.ident(alias)), + Item::Value { value, alias: None } => self.operand(value), + } + } + + fn source(&self, table: &Table) -> String { + match &table.alias { + Some(alias) => format!("{} {}", self.table_name(table), self.ident(alias)), + None => self.table_name(table), + } + } + + fn join(&self, table: &Table) -> String { + let source = self.source(table); + let Some(join) = table.join.as_ref().filter(|join| !join.is_empty()) else { + return format!("CROSS JOIN {source}"); + }; + let head = format!("{} JOIN {source}", join.kind.keyword()); + if !join.using.is_empty() { + let columns: Vec = join.using.iter().map(|c| self.ident(c)).collect(); + return format!("{head} USING ({})", columns.join(", ")); + } + let alone = join.on.len() + join.extra.len() == 1; + let pairs = join.on.iter().map(|pair| format!("{} = {}", self.column(&pair.left), self.column(&pair.right))); + let terms: Vec = pairs.chain(join.extra.iter().map(|raw| self.raw(raw, alone))).collect(); + format!("{head} ON {}", terms.join(" AND ")) + } + + fn raw(&self, text: &str, alone: bool) -> String { + if alone || !has_or(text, self.dialect) { text.trim().to_string() } else { format!("({})", text.trim()) } + } + + fn condition(&self, condition: &Condition, alone: bool) -> String { + match condition { + Condition::Compare { left, op, value } => { + let left = self.operand(left); + let value = value.trim(); + match op { + Op::IsNull | Op::IsNotNull => format!("{left} {}", op.sql()), + Op::In | Op::NotIn if !(value.starts_with('(') && value.ends_with(')')) => { + format!("{left} {} ({value})", op.sql()) + } + op => format!("{left} {} {value}", op.sql()), + } + } + Condition::Raw(text) => self.raw(text, alone), + } + } + + fn conditions(&self, head: &str, list: &[Condition]) -> Option { + let shown: Vec<&Condition> = list.iter().filter(|c| c.complete()).collect(); + let alone = shown.len() == 1; + let terms: Vec = shown.into_iter().map(|c| self.condition(c, alone)).collect(); + (!terms.is_empty()).then(|| format!("{head} {}", terms.join("\n AND "))) + } + + fn sort(&self, sort: &Sort) -> String { + let mut out = self.operand(&sort.by); + if sort.desc { + out.push_str(" DESC"); + } + if !sort.extra.is_empty() { + out.push(' '); + out.push_str(&sort.extra); + } + out + } + + fn query(&self) -> String { + let design = self.design; + let tsql = self.dialect == SqlDialect::TSql; + let limit = design.limit.as_deref().map(str::trim).filter(|l| !l.is_empty()); + let offset = design.offset.as_deref().map(str::trim).filter(|o| !o.is_empty()); + let mut head = String::from("SELECT"); + if design.distinct { + head.push_str(" DISTINCT"); + } + if tsql + && offset.is_none() + && let Some(limit) = limit + { + match limit.chars().all(|c| c.is_ascii_digit()) { + true => head.push_str(&format!(" TOP {limit}")), + false => head.push_str(&format!(" TOP ({limit})")), + } + } + // MySQL takes a bare `*` only first, so a later one names each table's. + let every = || match design.tables.is_empty() { + true => "*".to_string(), + false => { + (0..design.tables.len()).map(|ix| format!("{}.*", self.reference(ix))).collect::>().join(", ") + } + }; + let items: Vec = match design.items.is_empty() { + true => vec!["*".into()], + false => design + .items + .iter() + .enumerate() + .map(|(ix, item)| match item { + Item::All(None) if ix > 0 && self.dialect == SqlDialect::MySql => every(), + item => self.item(item), + }) + .collect(), + }; + let mut clauses = vec![list(&head, &items)]; + if let Some((first, rest)) = design.tables.split_first() { + clauses.push(format!("FROM {}", self.source(first))); + clauses.extend(rest.iter().map(|table| self.join(table))); + } + clauses.extend(self.conditions("WHERE", &design.filters)); + if !design.group_by.is_empty() { + let keys: Vec = design.group_by.iter().map(|key| self.operand(key)).collect(); + clauses.push(list("GROUP BY", &keys)); + } + clauses.extend(self.conditions("HAVING", &design.having)); + let mut sorts: Vec = design.order_by.iter().map(|sort| self.sort(sort)).collect(); + // OFFSET needs an ORDER BY, which DISTINCT keeps to the select list. + if tsql && offset.is_some() && sorts.is_empty() { + sorts.push(if design.distinct { "1" } else { "(SELECT NULL)" }.into()); + } + if !sorts.is_empty() { + clauses.push(list("ORDER BY", &sorts)); + } + match (tsql, limit, offset) { + (true, limit, Some(offset)) => { + let fetch = limit.map(|limit| format!(" FETCH NEXT {limit} ROWS ONLY")).unwrap_or_default(); + clauses.push(format!("OFFSET {offset} ROWS{fetch}")); + } + (true, ..) => {} + (false, Some(limit), Some(offset)) => clauses.push(format!("LIMIT {limit} OFFSET {offset}")), + (false, Some(limit), None) => clauses.push(format!("LIMIT {limit}")), + (false, None, Some(offset)) => clauses.push(match self.dialect { + SqlDialect::MySql => format!("LIMIT 18446744073709551615 OFFSET {offset}"), + SqlDialect::Sqlite => format!("LIMIT -1 OFFSET {offset}"), + _ => format!("OFFSET {offset}"), + }), + (false, None, None) => {} + } + clauses.join("\n") + } +} + +fn list(head: &str, items: &[String]) -> String { + let line = format!("{head} {}", items.join(", ")); + match line.len() <= LINE && !line.contains('\n') { + true => line, + false => format!("{head}\n {}", items.join(",\n ")), + } +} + +// An OR at the top, which needs parentheses beside an AND; MySQL's `||` is one too. +fn has_or(text: &str, dialect: SqlDialect) -> bool { + let mut depth = 0usize; + for token in tokenize_with(text, LexRules::of(dialect)) { + if token.is_punct("(") { + depth += 1; + } else if token.is_punct(")") { + depth = depth.saturating_sub(1); + } else if depth == 0 + && (token.is_keyword("or") + || token.is_keyword("xor") + || (dialect == SqlDialect::MySql && token.kind == TokenKind::Op && token.text == "||")) + { + return true; + } + } + false +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ImportError { + // Not one SELECT. + NotQuery, + // Where the parser stopped. + Syntax(usize), + // The SQL that the builder has no way to show, like UNION or a subquery in FROM. + Unsupported(String), +} + +impl From for ImportError { + fn from(error: ParseError) -> Self { + match error { + ParseError::NotQuery => Self::NotQuery, + ParseError::Syntax { at, .. } => Self::Syntax(at), + } + } +} + +fn unsupported(what: &str) -> Result { + Err(ImportError::Unsupported(what.into())) +} + +// `columns` lists a table's columns once they're loaded, to tell which table an unqualified name belongs to. +pub fn import( + sql: &str, + driver: &DriverType, + columns: &dyn Fn(&Table) -> Option>, +) -> Result { + if sql.trim().is_empty() { + return Ok(Design::default()); + } + let dialect = driver.dialect().unwrap_or(SqlDialect::Postgres); + let query = select::parse_query(sql, dialect)?; + if let Some(clause) = query.skipped.first() { + return unsupported(clause); + } + if !query.ctes.is_empty() { + return unsupported("WITH"); + } + if query.limit_by.is_some() { + return unsupported("LIMIT … BY"); + } + let select = match query.body { + SetExpr::Select(select) => *select, + SetExpr::SetOp { op, .. } => { + return unsupported(match op { + SetOp::Union => "UNION", + SetOp::Intersect => "INTERSECT", + SetOp::Except => "EXCEPT", + }); + } + SetExpr::Values { .. } => return unsupported("VALUES"), + SetExpr::Query(_) => return unsupported("(SELECT …)"), + }; + let mut reader = Import { sql, dialect, tables: vec![], columns: vec![], aliases: vec![] }; + let mut joins = vec![]; + for item in select.from { + reader.table(item.factor)?; + for join in item.joins { + if join.natural { + return unsupported("NATURAL JOIN"); + } + if let Some(hint) = &join.hint { + return unsupported(&if hint.ends_with("JOIN") { hint.clone() } else { format!("{hint} JOIN") }); + } + let kind = match join.kind { + select::JoinKind::Inner => Some(JoinKind::Inner), + select::JoinKind::Left => Some(JoinKind::Left), + select::JoinKind::Right => Some(JoinKind::Right), + select::JoinKind::Full => Some(JoinKind::Full), + select::JoinKind::Cross => None, + select::JoinKind::Semi => return unsupported("SEMI JOIN"), + select::JoinKind::Anti => return unsupported("ANTI JOIN"), + select::JoinKind::CrossApply => return unsupported("CROSS APPLY"), + select::JoinKind::OuterApply => return unsupported("OUTER APPLY"), + select::JoinKind::Array | select::JoinKind::LeftArray => return unsupported("ARRAY JOIN"), + }; + reader.table(join.factor)?; + joins.push((reader.tables.len() - 1, kind, join.on, join.using)); + } + } + reader.columns = reader.tables.iter().map(columns).collect(); + for (at, kind, on, using) in joins { + reader.tables[at].join = kind.and_then(|kind| reader.join(kind, on, &using)); + } + let mut design = Design::default(); + if let Some(distinct) = select.distinct { + if !distinct.on.is_empty() { + return unsupported("DISTINCT ON"); + } + design.distinct = true; + } + if select.prewhere.is_some() { + return unsupported("PREWHERE"); + } + if select.qualify.is_some() { + return unsupported("QUALIFY"); + } + if let Some(word) = select.items.iter().find_map(|item| star_modifier(&item.expr, dialect)) { + return unsupported(&format!("* {word}")); + } + design.items = select.items.iter().map(|item| reader.item(item)).collect(); + // A lone `*` is no items. + if design.items == [Item::All(None)] { + design.items.clear(); + } + reader.aliases = design + .items + .iter() + .filter_map(|item| match item { + Item::Value { alias: Some(alias), .. } => Some(alias.clone()), + _ => None, + }) + .collect(); + // Positions in the select list become what they point at. + let ordinal = |operand: Operand| { + let at = match &operand { + Operand::Expr(text) => text.trim().parse::().ok().and_then(|n| n.checked_sub(1)), + _ => None, + }; + match at.and_then(|at| design.items.get(at)) { + Some(Item::Value { value, .. }) => value.clone(), + _ => operand, + } + }; + let filters = select.filter.map(|filter| reader.conditions(filter)).unwrap_or_default(); + let mut group_by = vec![]; + if let Some(keys) = select.group_by { + if keys.all { + return unsupported("GROUP BY ALL"); + } + if let Some(modifier) = keys.modifiers.first() { + return unsupported(&format!("WITH {modifier}")); + } + group_by = keys.keys.iter().map(|key| ordinal(reader.operand(key))).collect(); + } + let having = select.having.map(|having| reader.conditions(having)).unwrap_or_default(); + let order_by: Vec = + query.order_by.iter().map(|key| reader.sort(key)).map(|sort| Sort { by: ordinal(sort.by), ..sort }).collect(); + (design.filters, design.group_by, design.having, design.order_by) = (filters, group_by, having, order_by); + if let Some(top) = select.top { + if top.percent { + return unsupported("TOP … PERCENT"); + } + if top.with_ties { + return unsupported("WITH TIES"); + } + design.limit = Some(top.count.text); + } + if let Some(limit) = query.limit { + if limit.with_ties { + return unsupported("WITH TIES"); + } + design.limit = limit.count.map(|count| count.text).or(design.limit); + design.offset = limit.offset.map(|offset| offset.text); + } + design.tables = reader.tables; + Ok(design) +} + +struct Import<'a> { + sql: &'a str, + dialect: SqlDialect, + tables: Vec
, + // Each table's columns, where they're known. + columns: Vec>>, + // The picked items' names in the results. + aliases: Vec, +} + +impl Import<'_> { + // Postgres folds A-Z in a name without quotes, and nothing else. + fn name(&self, ident: &Ident) -> String { + match self.dialect == SqlDialect::Postgres && !ident.quoted { + true => ident.value.to_ascii_lowercase(), + false => ident.value.clone(), + } + } + + fn table(&mut self, factor: TableFactor) -> Result<(), ImportError> { + let (mut name, alias, span) = match factor { + TableFactor::Table { name, alias, span } => (name, alias, span), + TableFactor::Derived { lateral: true, .. } => return unsupported("LATERAL"), + TableFactor::Derived { .. } => return unsupported("FROM (SELECT …)"), + TableFactor::Nested { .. } => return unsupported("FROM (… JOIN …)"), + TableFactor::Function { .. } => return unsupported("FROM function(…)"), + TableFactor::Arrays { .. } => return unsupported("ARRAY JOIN"), + }; + if alias.as_ref().is_some_and(|alias| !alias.columns.is_empty()) { + return unsupported("AS t (…)"); + } + if let Some(hint) = self.hint(&span, &name, alias.as_ref()) { + return unsupported(&hint); + } + let Some(last) = name.pop() else { return unsupported("FROM") }; + self.tables.push(Table { + qualifier: name.iter().map(|part| self.name(part)).collect(), + name: self.name(&last), + alias: alias.map(|alias| self.name(&alias.name)), + join: None, + }); + Ok(()) + } + + // A word in the table's span besides its name and alias, like FINAL or WITH (NOLOCK), which would be lost. + fn hint(&self, span: &Range, name: &[Ident], alias: Option<&select::Alias>) -> Option { + let (first, last) = (name.first()?.span.start, name.last()?.span.end); + let alias_at = alias.map(|alias| alias.name.span.start); + let tokens = select::code_tokens(&self.sql[span.clone()], LexRules::of(self.dialect)); + let extra = |token: &Token| { + let at = span.start + token.start; + !(first..last).contains(&at) && Some(at) != alias_at && !token.is_keyword("as") + }; + let ix = tokens.iter().position(extra)?; + let word = tokens[ix].text.to_uppercase(); + Some(match tokens.get(ix + 1) { + Some(next) if next.is_punct("(") => format!("{word} (…)"), + Some(next) if next.kind == TokenKind::Ident && extra(next) => { + format!("{word} {}", next.text.to_uppercase()) + } + _ => word, + }) + } + + fn join(&self, kind: JoinKind, on: Option, using: &[Ident]) -> Option { + let mut join = Join { kind, on: vec![], using: using.iter().map(|c| self.name(c)).collect(), extra: vec![] }; + for term in on.map(terms).unwrap_or_default() { + match self.pair(&term) { + Some(pair) => join.on.push(pair), + None => join.extra.push(term.text), + } + } + (!join.is_empty()).then_some(join) + } + + fn pair(&self, term: &Expr) -> Option { + let ExprKind::Compare { left, op, right } = &term.kind else { return None }; + if op != "=" && op != "==" { + return None; + } + Some(Pair { left: self.column_of(left)?, right: self.column_of(right)? }) + } + + fn column_of(&self, expr: &Expr) -> Option { + let ExprKind::Column { qualifier, name } = &expr.kind else { return None }; + self.resolve(qualifier, name) + } + + fn resolve(&self, qualifier: &[Ident], name: &Ident) -> Option { + let column = self.name(name); + let table = match qualifier { + [] if self.tables.len() == 1 => 0, + [] => { + let has = |columns: &Option>| { + columns.as_ref().is_some_and(|list| list.iter().any(|c| c.eq_ignore_ascii_case(&column))) + }; + only(self.columns.iter().enumerate().filter(|(_, columns)| has(columns)).map(|(ix, _)| ix))? + } + [.., schema, table] => { + let (schema, table) = (self.name(schema), self.name(table)); + self.tables.iter().position(|t| { + t.alias.is_none() + && t.name.eq_ignore_ascii_case(&table) + && t.qualifier.last().is_some_and(|s| s.eq_ignore_ascii_case(&schema)) + })? + } + [_] => self.table_named(qualifier)?, + }; + Some(ColumnRef { table, column }) + } + + fn table_named(&self, qualifier: &[Ident]) -> Option { + let key = self.name(qualifier.last()?); + only(self.tables.iter().enumerate().filter(|(_, t)| t.key().eq_ignore_ascii_case(&key)).map(|(ix, _)| ix)) + } + + fn item(&self, item: &select::SelectItem) -> Item { + let alias = item.alias.as_ref().map(|alias| self.name(alias)); + if let (ExprKind::Wildcard(qualifier), None) = (&item.expr.kind, &alias) { + match qualifier.as_slice() { + [] => return Item::All(None), + [_] => { + if let Some(table) = self.table_named(qualifier) { + return Item::All(Some(table)); + } + } + _ => {} + } + } + Item::Value { value: self.operand(&item.expr), alias } + } + + fn operand(&self, expr: &Expr) -> Operand { + self.alias(expr, false).unwrap_or_else(|| self.value(expr)) + } + + fn value(&self, expr: &Expr) -> Operand { + let found = match &expr.kind { + ExprKind::Column { qualifier, name } => self.resolve(qualifier, name).map(Operand::Column), + ExprKind::Call { name, args } if name.len() == 1 && !name[0].quoted => self.aggregate(&name[0].value, args), + _ => None, + }; + found.unwrap_or_else(|| Operand::Expr(expr.text.clone())) + } + + // The picked item a bare name stands for, ahead of a column only in ORDER BY. + fn alias(&self, expr: &Expr, sorting: bool) -> Option { + let ExprKind::Column { qualifier, name } = &expr.kind else { return None }; + if !qualifier.is_empty() { + return None; + } + let name = self.name(name); + let alias = self.aliases.iter().find(|alias| alias.eq_ignore_ascii_case(&name))?; + let column = self.columns.iter().flatten().any(|list| list.iter().any(|c| c.eq_ignore_ascii_case(&name))); + (sorting || !column).then(|| Operand::Alias(alias.clone())) + } + + fn aggregate(&self, name: &str, args: &[Expr]) -> Option { + let [arg] = args else { return None }; + let lower = name.to_ascii_lowercase(); + if lower == "count" && matches!(&arg.kind, ExprKind::Wildcard(q) if q.is_empty()) { + return Some(Operand::Aggregate { func: Aggregate::Count, of: None }); + } + let distinct = arg.text.get(..9).is_some_and(|head| head.eq_ignore_ascii_case("distinct ")); + let (func, arg) = match (lower.as_str(), distinct) { + ("count", true) => (Aggregate::CountDistinct, select::parse_expr(&arg.text[9..], self.dialect).ok()?), + (_, true) => return None, + (name, false) => { + (Aggregate::ALL.into_iter().find(|func| func.name().eq_ignore_ascii_case(name))?, arg.clone()) + } + }; + Some(Operand::Aggregate { func, of: Some(self.column_of(&arg)?) }) + } + + fn conditions(&self, expr: Expr) -> Vec { + // MySQL's `||` is an OR that binds looser than AND, so such a filter stays whole. + if self.dialect == SqlDialect::MySql && has_or(&expr.text, self.dialect) { + return vec![Condition::Raw(expr.text)]; + } + terms(expr).into_iter().map(|term| self.condition(term)).collect() + } + + fn condition(&self, expr: Expr) -> Condition { + if let ExprKind::Compare { left, op, right } = &expr.kind { + let left = self.operand(left); + if !matches!(left, Operand::Expr(_)) + && let Some((op, value)) = compare(op, right) + { + return Condition::Compare { left, op, value }; + } + } + Condition::Raw(expr.text) + } + + fn sort(&self, key: &OrderKey) -> Sort { + let rest = key.text.strip_prefix(key.expr.text.as_str()).unwrap_or_default().trim(); + let rest = match rest.split_once(' ').map_or((rest, ""), |(word, more)| (word, more)) { + (word, more) if word.eq_ignore_ascii_case("asc") || word.eq_ignore_ascii_case("desc") => more, + _ => rest, + }; + let by = self.alias(&key.expr, true).unwrap_or_else(|| self.value(&key.expr)); + Sort { by, desc: key.desc, extra: rest.trim().to_string() } + } +} + +// ClickHouse's `* EXCEPT (…)`, REPLACE or APPLY, which a bare `*` would lose. +fn star_modifier(expr: &Expr, dialect: SqlDialect) -> Option { + let ExprKind::Wildcard(_) = &expr.kind else { return None }; + let tokens = select::code_tokens(&expr.text, LexRules::of(dialect)); + let star = tokens.iter().position(|token| token.kind == TokenKind::Op && token.text == "*")?; + tokens.get(star + 1).filter(|token| token.kind == TokenKind::Ident).map(|token| token.text.to_uppercase()) +} + +// The one index `matches` yields, unless it yields several. +fn only(mut matches: impl Iterator) -> Option { + let first = matches.next()?; + matches.next().is_none().then_some(first) +} + +fn terms(expr: Expr) -> Vec { + match expr.kind { + ExprKind::And(terms) => terms, + _ => vec![expr], + } +} + +fn compare(op: &str, right: &Expr) -> Option<(Op, String)> { + let null = right.text.eq_ignore_ascii_case("null"); + let op = match op { + "=" | "==" => Op::Eq, + "<>" | "!=" => Op::Ne, + "<" => Op::Lt, + "<=" => Op::Le, + ">" => Op::Gt, + ">=" => Op::Ge, + "LIKE" => Op::Like, + "NOT LIKE" => Op::NotLike, + "ILIKE" => Op::ILike, + "NOT ILIKE" => Op::NotILike, + "IN" => Op::In, + "NOT IN" => Op::NotIn, + "IS" if null => return Some((Op::IsNull, String::new())), + "IS NOT" if null => return Some((Op::IsNotNull, String::new())), + _ => return None, + }; + Some((op, right.text.clone())) +} diff --git a/crates/barsql-sql/src/lib.rs b/crates/barsql-sql/src/lib.rs index 4b13539..cb5240f 100644 --- a/crates/barsql-sql/src/lib.rs +++ b/crates/barsql-sql/src/lib.rs @@ -1,6 +1,7 @@ pub mod algebra; pub mod alter; pub mod ddl; +pub mod design; pub mod dialect; pub mod dml; pub mod enum_values; diff --git a/crates/barsql-sql/src/select.rs b/crates/barsql-sql/src/select.rs index 51a6262..2262030 100644 --- a/crates/barsql-sql/src/select.rs +++ b/crates/barsql-sql/src/select.rs @@ -19,6 +19,8 @@ pub struct Query { pub limit_by: Option, pub limit: Option, pub span: Range, + // Clauses read past without keeping, like FOR UPDATE or SETTINGS, for the statement as a whole. + pub skipped: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -170,6 +172,8 @@ pub struct Join { pub using: Vec, // From the joined table to the end of its condition. pub span: Range, + // A word the kind leaves out, like ASOF, GLOBAL or HASH. + pub hint: Option, } impl Join { @@ -264,7 +268,17 @@ impl Tail { fn wrap(self, body: SetExpr, span: Range) -> SetExpr { let Tail { order_by, limit_by, limit } = self; - SetExpr::Query(Box::new(Query { ctes: vec![], recursive: false, body, order_by, limit_by, limit, span })) + let skipped = vec![]; + SetExpr::Query(Box::new(Query { + ctes: vec![], + recursive: false, + body, + order_by, + limit_by, + limit, + span, + skipped, + })) } } @@ -487,6 +501,20 @@ const MYSQL_MODIFIERS: &[&str] = &[ ]; pub fn parse_query(sql: &str, dialect: SqlDialect) -> Result { + parser(sql, dialect)?.statement() +} + +// One expression on its own, read as a WHERE condition is. +pub fn parse_expr(sql: &str, dialect: SqlDialect) -> Result { + let mut parser = parser(sql, dialect)?; + let expr = parser.expr(Ctx::Filter)?; + match parser.peek() { + None => Ok(expr), + Some(_) => Err(parser.error("the end of the expression")), + } +} + +fn parser(sql: &str, dialect: SqlDialect) -> Result, ParseError> { let tokens = code_tokens(sql, LexRules::of(dialect)); if let Some(open) = tokens.iter().find(|t| t.unterminated) { return Err(ParseError::Syntax { expected: "a closing quote", at: open.start }); @@ -494,7 +522,7 @@ pub fn parse_query(sql: &str, dialect: SqlDialect) -> Result if let Some(at) = too_big(&tokens) { return Err(ParseError::Syntax { expected: "a smaller query", at }); } - Parser { tokens, pos: 0, dialect, len: sql.len(), pending: None }.statement() + Ok(Parser { tokens, pos: 0, dialect, len: sql.len(), pending: None, skipped: vec![] }) } fn too_big(tokens: &[Token]) -> Option { @@ -508,7 +536,7 @@ fn too_big(tokens: &[Token]) -> Option { } // Without comments, and with each dollar-quoted body as one string. -fn code_tokens(sql: &str, rules: LexRules) -> Vec> { +pub(crate) fn code_tokens(sql: &str, rules: LexRules) -> Vec> { let mut out = Vec::new(); let mut from = 0; 'text: while from < sql.len() { @@ -667,6 +695,7 @@ struct Parser<'a> { len: usize, // A SELECT's own ORDER BY and LIMIT, for the query around it. pending: Option, + skipped: Vec, } impl<'a> Parser<'a> { @@ -829,7 +858,8 @@ impl<'a> Parser<'a> { } Some(_) => {} } - let query = self.query()?; + let mut query = self.query()?; + query.skipped = std::mem::take(&mut self.skipped); let mut ended = false; while self.eat_punct(";") { ended = true; @@ -860,7 +890,7 @@ impl<'a> Parser<'a> { body = last_with(body, std::mem::take(&mut tail), self.tokens[self.pos - 1].end); } let Tail { order_by, limit_by, limit } = tail; - Ok(Query { ctes, recursive, body, order_by, limit_by, limit, span: self.span(start) }) + Ok(Query { ctes, recursive, body, order_by, limit_by, limit, span: self.span(start), skipped: vec![] }) } fn cte(&mut self) -> Parsed> { @@ -870,6 +900,7 @@ impl<'a> Parser<'a> { self.skip_until(|_, token| token.is_keyword("as")); self.expect_kw("as")?; self.ident("a name")?; + self.skipped.push("WITH".into()); return Ok(None); } let name = self.ident("a name")?; @@ -881,6 +912,7 @@ impl<'a> Parser<'a> { if self.punct("(") && !self.holds_query(self.pos) { // A data-modifying CTE, opaque to the graph. self.skip_parens()?; + self.skipped.push("WITH".into()); return Ok(None); } self.expect_punct("(")?; @@ -1007,6 +1039,7 @@ impl<'a> Parser<'a> { } 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.skipped.push(self.tokens[self.pos].text.to_uppercase()); self.pos += 1; } let mut items = vec![]; @@ -1017,6 +1050,7 @@ impl<'a> Parser<'a> { } } if self.eat_kw("into") { + self.skipped.push("INTO".into()); self.skip_clause(); } let mut from = vec![]; @@ -1031,6 +1065,7 @@ impl<'a> Parser<'a> { 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") { + self.skipped.push("WINDOW".into()); loop { self.ident("a window name")?; self.expect_kw("as")?; @@ -1132,9 +1167,9 @@ impl<'a> Parser<'a> { let factor = self.factor()?; let mut joins: Vec = vec![]; loop { - if let Some((words, kind, natural)) = self.join_words() { + if let Some((words, kind, natural, hint)) = self.join_words() { self.pos += words; - joins.push(self.join(kind, natural)?); + joins.push(self.join(kind, natural, hint)?); continue; } // `a JOIN b JOIN c ON … ON …`: the second ON joins `b JOIN c` as one table. @@ -1147,13 +1182,13 @@ impl<'a> Parser<'a> { 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 }); + joins.push(Join { kind: outer.kind, natural: false, factor, on, using, span, hint: outer.hint }); } 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)> { + fn join_words(&self) -> Option<(usize, JoinKind, bool, Option)> { // 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; @@ -1193,12 +1228,15 @@ impl<'a> Parser<'a> { _ if has("cross") => JoinKind::Cross, _ => JoinKind::Inner, }; - return Some((words.len() + 1, kind, has("natural"))); + let hints = ["any", "all", "asof", "global", "loop", "hash", "merge", "remote"]; + let hint = words.iter().find(|word| hints.contains(word)).copied(); + let hint = hint.or((word == "straight_join").then_some(word)).map(str::to_uppercase); + return Some((words.len() + 1, kind, has("natural"), hint)); } None } - fn join(&mut self, kind: JoinKind, natural: bool) -> Parsed { + fn join(&mut self, kind: JoinKind, natural: bool, hint: Option) -> Parsed { let start = self.pos; let factor = match kind { JoinKind::Array | JoinKind::LeftArray => { @@ -1213,7 +1251,7 @@ impl<'a> Parser<'a> { _ => self.factor()?, }; let (on, using) = self.condition()?; - Ok(Join { kind, natural, factor, on, using, span: self.span(start) }) + Ok(Join { kind, natural, factor, on, using, span: self.span(start), hint }) } fn condition(&mut self) -> Parsed<(Option, Vec)> { @@ -1502,11 +1540,14 @@ impl<'a> Parser<'a> { 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")) + } else if let Some(word) = + self.word().filter(|w| matches!(w.as_str(), "for" | "lock" | "settings" | "format" | "option" | "into")) && self.stops(Ctx::Item) { + // FOR and LOCK by what they lock: FOR UPDATE, LOCK IN. + let next = self.at(1).filter(|t| t.kind == TokenKind::Ident && matches!(word.as_str(), "for" | "lock")); + let what = next.map_or(word.clone(), |next| format!("{word} {}", next.lower)); + self.skipped.push(what.to_uppercase()); self.pos += 1; self.skip_clause(); } else { @@ -1547,7 +1588,7 @@ impl<'a> Parser<'a> { "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"), + "lock" => next("in") && self.kw_at(2, "share"), "prewhere" | "qualify" | "settings" => clickhouse, "format" => clickhouse && !self.punct_at(1, "("), "option" => self.dialect == SqlDialect::TSql && self.punct_at(1, "("), diff --git a/crates/barsql-sql/tests/design.rs b/crates/barsql-sql/tests/design.rs new file mode 100644 index 0000000..df9e8af --- /dev/null +++ b/crates/barsql-sql/tests/design.rs @@ -0,0 +1,463 @@ +use barsql_core::DriverType::{self, ClickHouse, MySql, Postgres, SqlServer, Sqlite}; +use barsql_sql::design::{ + Aggregate, ColumnRef, Condition, Design, ImportError, Item, JoinKind, Op, Operand, Sort, Table, import, render, +}; + +fn columns(table: &Table) -> Option> { + let names: &[&str] = match table.name.as_str() { + "users" => &["id", "name", "active", "created_at"], + "orders" => &["id", "user_id", "total", "status"], + "payments" => &["id", "order_id", "amount"], + _ => return None, + }; + Some(names.iter().map(|name| name.to_string()).collect()) +} + +fn read(sql: &str, driver: &DriverType) -> Design { + import(sql, driver, &columns).unwrap_or_else(|error| panic!("{sql}: {error:?}")) +} + +fn col(table: usize, name: &str) -> ColumnRef { + ColumnRef::new(table, name) +} + +fn with_tables(names: &[&str]) -> Design { + let mut design = Design::default(); + for name in names { + design.add_table(vec![], name); + } + design +} + +fn users_and_orders() -> Design { + let mut design = with_tables(&["users", "orders"]); + assert!(design.link(col(1, "user_id"), col(0, "id"))); + design.set_join_kind(1, JoinKind::Left); + design.toggle_column(col(0, "name")); + design.toggle_column(col(1, "id")); + design.set_aggregate(1, Some(Aggregate::Count)); + design.set_alias(1, "orders".into()); + design.filters.push(Condition::Compare { + left: Operand::Column(col(0, "active")), + op: Op::Eq, + value: "TRUE".into(), + }); + design.having.push(Condition::Compare { + left: Operand::Aggregate { func: Aggregate::Count, of: Some(col(1, "id")) }, + op: Op::Gt, + value: "5".into(), + }); + design.order_by.push(Sort { by: Operand::Alias("orders".into()), desc: true, extra: String::new() }); + design.limit = Some("100".into()); + design +} + +#[test] +fn a_design_reads_as_one_clause_a_line() { + let want = "\ +SELECT users.name, COUNT(orders.id) AS orders +FROM users +LEFT JOIN orders ON orders.user_id = users.id +WHERE users.active = TRUE +GROUP BY users.name +HAVING COUNT(orders.id) > 5 +ORDER BY orders DESC +LIMIT 100"; + assert_eq!(render(&users_and_orders(), &Postgres), want); +} + +#[test] +fn each_engine_limits_and_quotes_its_own_way() { + let mut design = Design::default(); + design.add_table(vec!["sales".into()], "Order"); + design.toggle_column(col(0, "group")); + design.limit = Some("10".into()); + assert_eq!(render(&design, &Postgres), "SELECT \"group\"\nFROM sales.\"Order\"\nLIMIT 10"); + assert_eq!(render(&design, &MySql), "SELECT `group`\nFROM sales.`Order`\nLIMIT 10"); + assert_eq!(render(&design, &SqlServer), "SELECT TOP 10 [group]\nFROM sales.[Order]"); + design.offset = Some("20".into()); + assert_eq!( + render(&design, &SqlServer), + "SELECT [group]\nFROM sales.[Order]\nORDER BY (SELECT NULL)\nOFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY" + ); + design.limit = None; + assert!(render(&design, &Sqlite).ends_with("\nLIMIT -1 OFFSET 20")); + assert!(render(&design, &ClickHouse).ends_with("\nOFFSET 20")); +} + +#[test] +fn one_table_needs_no_qualifier_and_nothing_picked_is_a_star() { + let mut design = with_tables(&["users"]); + assert_eq!(render(&design, &Postgres), "SELECT *\nFROM users"); + design.toggle_column(col(0, "id")); + assert_eq!(render(&design, &Postgres), "SELECT id\nFROM users"); + design.toggle_column(col(0, "ID")); + assert_eq!(render(&design, &Postgres), "SELECT *\nFROM users", "a second toggle takes it back"); +} + +#[test] +fn long_lists_go_one_item_a_line() { + let mut design = with_tables(&["users"]); + for name in ["a_rather_long_column_name", "another_long_column_name", "yet_another_long_column_name"] { + design.toggle_column(col(0, name)); + } + let sql = render(&design, &Postgres); + assert!(sql.starts_with("SELECT\n a_rather_long_column_name,\n another_long_column_name,\n"), "{sql}"); +} + +#[test] +fn what_it_writes_reads_back_the_same() { + let design = users_and_orders(); + for driver in [Postgres, MySql, Sqlite, SqlServer, ClickHouse] { + let sql = render(&design, &driver); + let back = read(&sql, &driver); + assert_eq!(render(&back, &driver), sql, "{driver}"); + assert_eq!(back.tables, design.tables, "{driver}"); + assert_eq!(back.items, design.items, "{driver}"); + } +} + +#[test] +fn hand_written_queries_come_apart_into_the_builders_pieces() { + let sql = "select u.name, count(o.id) as n, upper(u.name) from users u \ + left join orders o on o.user_id = u.id and o.status <> 'void' \ + where u.active and u.created_at >= '2024-01-01' and (u.id = 1 or u.id = 2) \ + group by u.name having count(o.id) > 1 order by n desc nulls last, name limit 5 offset 10"; + let design = read(sql, &Postgres); + assert_eq!(design.tables[1].alias.as_deref(), Some("o")); + let join = design.tables[1].join.as_ref().expect("a join"); + assert_eq!( + (join.kind, join.on.len(), join.extra.as_slice()), + (JoinKind::Left, 1, &["o.status <> 'void'".to_string()][..]) + ); + assert_eq!(design.items[0], Item::column(col(0, "name"))); + assert_eq!( + design.items[1], + Item::Value { + value: Operand::Aggregate { func: Aggregate::Count, of: Some(col(1, "id")) }, + alias: Some("n".into()) + } + ); + assert_eq!(design.items[2], Item::Value { value: Operand::Expr("upper(u.name)".into()), alias: None }); + assert_eq!(design.filters[0], Condition::Raw("u.active".into())); + assert_eq!( + design.filters[1], + Condition::Compare { left: Operand::Column(col(0, "created_at")), op: Op::Ge, value: "'2024-01-01'".into() } + ); + assert_eq!(design.filters[2], Condition::Raw("(u.id = 1 or u.id = 2)".into())); + assert_eq!(design.order_by[0], Sort { by: Operand::Alias("n".into()), desc: true, extra: "nulls last".into() }); + assert_eq!(design.order_by[1].by, Operand::Column(col(0, "name")), "unqualified, but only users has it"); + assert_eq!((design.limit.as_deref(), design.offset.as_deref()), (Some("5"), Some("10"))); + let sql = render(&design, &Postgres); + assert!(sql.contains("LEFT JOIN orders o ON o.user_id = u.id AND o.status <> 'void'"), "{sql}"); + assert!(sql.contains("ORDER BY n DESC nulls last, u.name"), "{sql}"); +} + +#[test] +fn an_or_keeps_its_parentheses_beside_other_conditions() { + let design = read("SELECT * FROM users WHERE id = 1 OR id = 2", &Postgres); + assert_eq!(render(&design, &Postgres), "SELECT *\nFROM users\nWHERE id = 1 OR id = 2"); + let mut design = design; + design.filters.push(Condition::Compare { + left: Operand::Column(col(0, "active")), + op: Op::IsNull, + value: "".into(), + }); + assert_eq!(render(&design, &Postgres), "SELECT *\nFROM users\nWHERE (id = 1 OR id = 2)\n AND active IS NULL"); +} + +#[test] +fn conditions_wait_for_a_value_and_lists_get_parentheses() { + let mut design = with_tables(&["users"]); + design.filters.push(Condition::Compare { left: Operand::Column(col(0, "id")), op: Op::In, value: "1, 2".into() }); + design.filters.push(Condition::Compare { left: Operand::Column(col(0, "name")), op: Op::Like, value: " ".into() }); + assert_eq!(render(&design, &Postgres), "SELECT *\nFROM users\nWHERE id IN (1, 2)"); + let back = read("SELECT * FROM users WHERE id IN (1, 2) AND name IS NOT NULL", &Postgres); + assert_eq!( + back.filters[0], + Condition::Compare { left: Operand::Column(col(0, "id")), op: Op::In, value: "(1, 2)".into() } + ); + assert_eq!( + back.filters[1], + Condition::Compare { left: Operand::Column(col(0, "name")), op: Op::IsNotNull, value: "".into() } + ); +} + +#[test] +fn unqualified_names_need_the_columns_to_find_their_table() { + let sql = "SELECT name, total FROM users JOIN orders ON user_id = users.id"; + let known = read(sql, &Postgres); + assert_eq!(known.items, [Item::column(col(0, "name")), Item::column(col(1, "total"))]); + let pairs = &known.tables[1].join.as_ref().expect("joined").on; + assert_eq!((pairs[0].left.clone(), pairs[0].right.clone()), (col(1, "user_id"), col(0, "id"))); + let unknown = import(sql, &Postgres, &|_| None).expect("reads"); + assert_eq!(unknown.items[0], Item::Value { value: Operand::Expr("name".into()), alias: None }); + assert!(unknown.tables[1].join.as_ref().expect("joined").on.is_empty()); + assert_eq!(render(&unknown, &Postgres), "SELECT name, total\nFROM users\nINNER JOIN orders ON user_id = users.id"); +} + +#[test] +fn names_are_folded_and_quoted_as_each_engine_reads_them() { + let design = read("SELECT U.Name, \"Odd\" FROM Users AS U", &Postgres); + assert_eq!((design.tables[0].name.as_str(), design.tables[0].alias.as_deref()), ("users", Some("u"))); + assert_eq!(render(&design, &Postgres), "SELECT name, \"Odd\"\nFROM users u"); + let design = read("SELECT [Order Id] FROM dbo.Orders o WHERE o.[Order Id] > 1", &SqlServer); + assert_eq!(render(&design, &SqlServer), "SELECT [Order Id]\nFROM dbo.Orders o\nWHERE [Order Id] > 1"); +} + +#[test] +fn tops_stars_and_distinct_come_through() { + let design = read("SELECT DISTINCT TOP (5) o.*, u.name FROM orders o, users u", &SqlServer); + assert!(design.distinct); + assert_eq!(design.items[0], Item::All(Some(0))); + assert_eq!(design.limit.as_deref(), Some("5")); + assert_eq!(design.tables[1].join, None, "a comma is a cross join"); + assert_eq!(render(&design, &SqlServer), "SELECT DISTINCT TOP 5 o.*, u.name\nFROM orders o\nCROSS JOIN users u"); + let design = read("SELECT count(*), count(DISTINCT user_id), sum(total) FROM orders", &MySql); + let funcs: Vec = design + .items + .iter() + .map(|item| match item { + Item::Value { value, .. } => value.clone(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!( + funcs, + [ + Operand::Aggregate { func: Aggregate::Count, of: None }, + Operand::Aggregate { func: Aggregate::CountDistinct, of: Some(col(0, "user_id")) }, + Operand::Aggregate { func: Aggregate::Sum, of: Some(col(0, "total")) }, + ] + ); + let back = read("SELECT * FROM users u JOIN orders o USING (id)", &Postgres); + assert_eq!(back.tables[1].join.as_ref().map(|join| join.using.clone()), Some(vec!["id".to_string()])); + assert!(render(&back, &Postgres).ends_with("INNER JOIN orders o USING (id)")); +} + +#[test] +fn what_the_builder_cannot_show_is_refused_rather_than_dropped() { + let refused = |sql: &str, driver: &DriverType| match import(sql, driver, &columns) { + Err(ImportError::Unsupported(what)) => what, + other => panic!("{sql}: {other:?}"), + }; + let cases: [(&str, DriverType, &str); 19] = [ + ("WITH t AS (SELECT 1) SELECT * FROM t", Postgres, "WITH"), + ("SELECT id FROM users UNION SELECT id FROM orders", Postgres, "UNION"), + ("SELECT * FROM (SELECT 1) t", Postgres, "FROM (SELECT …)"), + ("SELECT * FROM users u, LATERAL (SELECT 1) x", Postgres, "LATERAL"), + ("SELECT * FROM users NATURAL JOIN orders", Postgres, "NATURAL JOIN"), + ("SELECT * FROM users u CROSS APPLY (SELECT 1 AS x) a", SqlServer, "CROSS APPLY"), + ("SELECT DISTINCT ON (id) * FROM users", Postgres, "DISTINCT ON"), + ("SELECT TOP 5 PERCENT * FROM users", SqlServer, "TOP … PERCENT"), + ("SELECT * FROM users FOR UPDATE", Postgres, "FOR UPDATE"), + ("SELECT * FROM users FINAL", ClickHouse, "FINAL"), + ("SELECT * FROM users WITH (NOLOCK)", SqlServer, "WITH (…)"), + ("SELECT * FROM users u USE INDEX (ix) WHERE id = 1", MySql, "USE INDEX"), + ("SELECT * INTO copy FROM users", SqlServer, "INTO"), + ("SELECT count(*) OVER w FROM users WINDOW w AS (ORDER BY id)", Postgres, "WINDOW"), + ("SELECT id, count(*) FROM users GROUP BY id WITH ROLLUP", MySql, "WITH ROLLUP"), + ("SELECT SQL_CALC_FOUND_ROWS * FROM users", MySql, "SQL_CALC_FOUND_ROWS"), + ("SELECT * FROM users SETTINGS max_threads = 1", ClickHouse, "SETTINGS"), + ("SELECT * FROM users OPTION (RECOMPILE)", SqlServer, "OPTION"), + ("SELECT * FROM ONLY users", Postgres, "ONLY"), + ]; + for (sql, driver, what) in cases { + assert_eq!(refused(sql, &driver), what, "{sql}"); + } + assert_eq!(import("UPDATE users SET a = 1", &Postgres, &columns), Err(ImportError::NotQuery)); + assert_eq!(import("SELECT * FROM users WHERE", &Postgres, &columns), Err(ImportError::Syntax(25))); + assert_eq!(import(" ", &Postgres, &columns), Ok(Design::default())); +} + +// Whatever it reads, it writes back as SQL that reads to the same design, so an edit never drifts. +#[test] +fn every_prefix_imports_or_refuses_and_what_imports_is_stable() { + let queries = [ + "SELECT DISTINCT u.name AS \"Name\", count(DISTINCT o.id) n, sum(o.total), upper(u.name) FROM public.users u \ + LEFT JOIN orders o ON o.user_id = u.id AND o.total > 0 RIGHT JOIN payments p USING (id) CROSS JOIN orders o2, \ + users WHERE u.active AND (u.id = 1 OR u.id = 2) AND u.name NOT LIKE 'a%' AND o.status IN ('a', 'b') AND \ + p.amount IS NOT NULL GROUP BY u.name, upper(u.name) HAVING count(*) > 1 AND sum(o.total) >= 10 \ + ORDER BY n DESC NULLS LAST, 1, u.name LIMIT 10 OFFSET 5;", + "SELECT TOP (10) [a].[b], x.* FROM [dbo].[t] x FULL JOIN [u] ON [u].[id] = x.[id] ORDER BY 1 OFFSET 2 ROWS \ + FETCH NEXT 3 ROWS ONLY", + "SELECT `a`, `t`.`b` FROM `t` JOIN u ON u.id = t.id WHERE `c` = 'it''s' LIMIT 5, 10", + "SELECT café, \"ünï\" FROM straße s WHERE s.café <> 'x' ORDER BY café", + "WITH x AS (SELECT 1) SELECT * FROM x UNION SELECT 2 FROM (SELECT 1) t FINAL WHERE a = (SELECT max(b) FROM c)", + ]; + for sql in queries { + for driver in [Postgres, MySql, Sqlite, SqlServer, ClickHouse] { + for end in (0..=sql.len()).filter(|&end| sql.is_char_boundary(end)) { + let Ok(design) = import(&sql[..end], &driver, &columns) else { continue }; + let written = render(&design, &driver); + let again = import(&written, &driver, &columns) + .unwrap_or_else(|error| panic!("{driver}: {:?} wrote {written:?}: {error:?}", &sql[..end])); + assert_eq!(render(&again, &driver), written, "{driver}: {:?}", &sql[..end]); + } + } + } +} + +#[test] +fn removing_a_table_takes_what_reads_it_and_renumbers_the_rest() { + let mut design = with_tables(&["users", "orders", "payments"]); + design.link(col(1, "user_id"), col(0, "id")); + design.link(col(2, "order_id"), col(1, "id")); + design.toggle_column(col(0, "name")); + design.toggle_column(col(2, "amount")); + design.sort_column(col(2, "amount"), Some(true)); + design.remove_table(0); + assert_eq!(design.tables[0].name, "orders"); + assert_eq!(design.tables[0].join, None, "the first table joins nothing"); + assert_eq!(design.items, [Item::column(col(1, "amount"))]); + assert_eq!(design.order_by[0].by, Operand::Column(col(1, "amount"))); + let pairs = &design.tables[1].join.as_ref().expect("still joined").on; + assert_eq!((pairs[0].left.clone(), pairs[0].right.clone()), (col(1, "order_id"), col(0, "id"))); + design.remove_table(0); + assert_eq!(design.tables[0].join, None); + assert_eq!(render(&design, &Postgres), "SELECT amount\nFROM payments\nORDER BY amount DESC"); +} + +#[test] +fn a_column_counts_as_used_wherever_the_query_reads_it() { + let design = read( + "SELECT u.name FROM users u JOIN orders o ON o.user_id = u.id JOIN payments p USING (id) WHERE u.active GROUP BY u.name, u.created_at ORDER BY o.total", + &Postgres, + ); + let used = |table: usize, name: &str| design.uses(&col(table, name)); + assert!(used(0, "name") && used(0, "created_at") && used(1, "total"), "picked, grouped, sorted"); + assert!(used(0, "id") && used(1, "user_id"), "joined on"); + assert!(used(2, "id") && used(1, "id"), "USING names both sides"); + assert!(!used(0, "active"), "a raw condition names no column"); + assert!(!used(2, "amount")); +} + +#[test] +fn a_second_copy_of_a_table_gets_its_own_alias_and_joins_once() { + let mut design = with_tables(&["users", "users"]); + assert_eq!(design.tables[1].alias.as_deref(), Some("users2")); + assert!(design.link(col(0, "id"), col(1, "id"))); + assert!(!design.link(col(1, "id"), col(0, "id")), "already joined that way"); + assert!(!design.link(col(1, "id"), col(1, "name")), "not to itself"); + assert!(render(&design, &Postgres).ends_with("INNER JOIN users users2 ON users2.id = users.id")); + design.tables[1].join = None; + assert!(render(&design, &Postgres).ends_with("CROSS JOIN users users2")); +} + +#[test] +fn an_aggregate_groups_the_rest_and_letting_go_ungroups_them() { + let mut design = with_tables(&["orders"]); + design.toggle_column(col(0, "status")); + design.toggle_column(col(0, "total")); + design.group_by.push(Operand::Column(col(0, "user_id"))); + design.set_aggregate(1, Some(Aggregate::Sum)); + assert_eq!(design.group_by, [Operand::Column(col(0, "status")), Operand::Column(col(0, "user_id"))]); + assert_eq!(design.aggregate_of(&col(0, "total")), Some(Aggregate::Sum)); + design.set_aggregate(1, None); + assert_eq!(design.group_by, [Operand::Column(col(0, "user_id"))], "a key nobody picked stays"); + design.add_item(Item::Value { value: Operand::Aggregate { func: Aggregate::Count, of: None }, alias: None }); + design.set_aggregate(2, None); + assert_eq!(render(&design, &Postgres).lines().next(), Some("SELECT status, total, COUNT(*)")); + design.move_item(2, 0); + assert_eq!(render(&design, &Postgres).lines().next(), Some("SELECT COUNT(*), status, total")); +} + +// Any aggregate groups, one inside SQL or only in HAVING too; a window function doesn't. +#[test] +fn grouping_follows_every_aggregate_the_query_has() { + let status = || Operand::Column(col(0, "status")); + let mut design = read("SELECT status, count(1) AS n FROM orders GROUP BY status", &Postgres); + design.toggle_column(col(0, "total")); + assert_eq!(design.group_by, [status(), Operand::Column(col(0, "total"))]); + let mut design = read("SELECT status FROM orders GROUP BY status HAVING COUNT(*) > 1", &Postgres); + design.toggle_column(col(0, "total")); + assert_eq!(design.group_by, [status(), Operand::Column(col(0, "total"))]); + let mut design = read("SELECT status FROM orders GROUP BY status", &Postgres); + design.toggle_column(col(0, "total")); + assert_eq!(design.group_by, [status()], "grouping to de-duplicate stays"); + let mut design = read("SELECT status, SUM(total) OVER () AS running FROM orders", &Postgres); + design.toggle_column(col(0, "user_id")); + assert!(design.group_by.is_empty(), "a window function doesn't group"); + let sql = "SELECT status, SUM(total) / COUNT(*) AS mean, COUNT(*) FROM orders GROUP BY status"; + let mut design = read(sql, &Postgres); + design.toggle_column(col(0, "user_id")); + assert_eq!(design.group_by, [status(), Operand::Column(col(0, "user_id"))]); + assert!(with_tables(&["orders"]).group_by.is_empty() && !with_tables(&["orders"]).aggregated()); +} + +#[test] +fn positions_in_order_by_and_group_by_follow_their_items() { + let mut design = read("SELECT id, name FROM users ORDER BY 2 DESC", &Postgres); + assert_eq!(design.order_by[0].by, Operand::Column(col(0, "name"))); + design.move_item(1, 0); + assert!(render(&design, &Postgres).ends_with("ORDER BY name DESC")); + let design = read("SELECT status, COUNT(*) FROM orders GROUP BY 1", &Postgres); + assert_eq!(design.group_by, [Operand::Column(col(0, "status"))]); +} + +// A sort by an item's alias follows the alias, and its value once the alias goes. +#[test] +fn a_name_from_the_select_list_stays_a_name() { + let mut design = read("SELECT status, COUNT(*) AS n FROM orders GROUP BY status ORDER BY n DESC", &Postgres); + assert_eq!(design.order_by[0].by, Operand::Alias("n".into())); + design.add_table(vec![], "users"); + assert!(render(&design, &Postgres).ends_with("ORDER BY n DESC"), "not a column of orders"); + design.set_alias(1, "Total".into()); + assert!(render(&design, &Postgres).ends_with("ORDER BY \"Total\" DESC")); + design.set_alias(1, String::new()); + assert!(render(&design, &Postgres).ends_with("ORDER BY COUNT(*) DESC")); + let mut design = read("SELECT name AS who FROM users ORDER BY who", &Postgres); + design.remove_item(0); + assert!(design.order_by.is_empty(), "the sort goes with its item"); +} + +#[test] +fn engine_extras_the_builder_would_drop_are_refused() { + let refused = |sql: &str, driver: &DriverType| match import(sql, driver, &columns) { + Err(ImportError::Unsupported(what)) => what, + other => panic!("{sql}: {other:?}"), + }; + assert_eq!(refused("SELECT * EXCEPT (name) FROM users", &ClickHouse), "* EXCEPT"); + assert_eq!(refused("SELECT * FROM users u ASOF LEFT JOIN orders o ON o.user_id = u.id", &ClickHouse), "ASOF JOIN"); + assert_eq!(refused("SELECT * FROM users u INNER HASH JOIN orders o ON o.user_id = u.id", &SqlServer), "HASH JOIN"); + assert_eq!(refused("WITH 1 AS one SELECT id FROM users", &ClickHouse), "WITH"); + assert_eq!(refused("WITH gone AS (DELETE FROM users RETURNING id) SELECT id FROM gone", &Postgres), "WITH"); + let names = [ + ("SELECT name, format FROM users", ClickHouse), + ("SELECT * FROM settings", ClickHouse), + ("SELECT * FROM users WHERE lock IN (1, 2)", Postgres), + ]; + for (sql, driver) in names { + assert!(import(sql, &driver, &columns).is_ok(), "{sql}: names, not clauses"); + } +} + +#[test] +fn a_using_join_takes_a_pair_it_has_or_one_more_name() { + let mut design = read("SELECT * FROM orders o JOIN payments p USING (id)", &Postgres); + let before = design.clone(); + assert!(!design.link(col(1, "id"), col(0, "id"))); + assert_eq!(design, before, "nothing changes"); + assert!(design.link(col(0, "total"), col(1, "total"))); + assert_eq!(design.tables[1].join.as_ref().map(|join| join.using.clone()), Some(vec!["id".into(), "total".into()])); +} + +#[test] +fn each_engine_gets_sql_it_accepts() { + let mut design = with_tables(&["users"]); + design.toggle_column(col(0, "name")); + design.add_item(Item::All(None)); + assert_eq!(render(&design, &MySql), "SELECT name, users.*\nFROM users", "MySQL takes `*` only first"); + assert_eq!(render(&design, &Postgres), "SELECT name, *\nFROM users"); + let mut design = with_tables(&["users"]); + design.distinct = true; + design.offset = Some("20".into()); + assert!(render(&design, &SqlServer).ends_with("ORDER BY 1\nOFFSET 20 ROWS"), "DISTINCT sorts by the select list"); + let design = read("SELECT * FROM Клиенти", &Postgres); + assert_eq!(design.tables[0].name, "Клиенти", "Postgres folds A-Z only"); + let sql = "SELECT * FROM users WHERE name = 'a' || name = 'b' AND id > 5"; + let mut design = read(sql, &MySql); + assert_eq!(design.filters, [Condition::Raw("name = 'a' || name = 'b' AND id > 5".into())]); + design.filters.push(Condition::Raw("active".into())); + assert!(render(&design, &MySql).ends_with("WHERE (name = 'a' || name = 'b' AND id > 5)\n AND active")); +} diff --git a/crates/barsql-storage/src/lib.rs b/crates/barsql-storage/src/lib.rs index 46981a2..8a6be7b 100644 --- a/crates/barsql-storage/src/lib.rs +++ b/crates/barsql-storage/src/lib.rs @@ -14,7 +14,9 @@ pub use history::{HISTORY_LIMIT, HistoryStore}; pub(crate) use json_file::update; pub use json_file::{load_json_file, save_json_file, write_file_atomic}; pub use saved_queries::SavedQueriesStore; -pub use session::{DiagramRef, EditorSession, EditorTab, SessionStore, StructureRef, TableViewRef}; +pub use session::{ + BuilderRef, DiagramRef, EditorSession, EditorTab, SessionStore, StructureRef, TablePlace, TableViewRef, +}; pub use settings::SettingsStore; pub use shared_folders::{MAX_FILE_BYTES, SharedFolderStore}; diff --git a/crates/barsql-storage/src/session.rs b/crates/barsql-storage/src/session.rs index 3423b63..cabb8a8 100644 --- a/crates/barsql-storage/src/session.rs +++ b/crates/barsql-storage/src/session.rs @@ -31,6 +31,23 @@ pub struct DiagramRef { pub schema: String, } +// A builder tab, with where its tables sit, in tenths of a rem, and whether it shows its SQL. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BuilderRef { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tables: Vec, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub sql_view: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TablePlace { + pub table: String, + pub x: i32, + pub y: i32, +} + // A Structure tab, by the table it shows. A new table's tab has none, so it isn't restored. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -64,6 +81,9 @@ pub struct EditorTab { pub diagram: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub structure: Option, + // Not `builder`, so tabs saved with the earlier in-tab builder open as SQL tabs. + #[serde(default, rename = "builderTab", skip_serializing_if = "Option::is_none")] + pub builder: Option, // Pinned tabs sit first and stay open through Close Others, To the Right and All. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub pinned: bool, @@ -178,6 +198,24 @@ mod tests { assert_eq!(SessionStore::open(tmp.path()).unwrap().get(), session); } + // A builder tab keeps its tables' places; an in-tab builder's entry is ignored. + #[test] + fn a_builder_tab_persists_its_tables() { + let tmp = tempfile::tempdir().unwrap(); + let store = SessionStore::open(tmp.path()).unwrap(); + let builder = BuilderRef { tables: vec![TablePlace { table: "users".into(), x: 15, y: -2 }], sql_view: true }; + let open = EditorTab { id: "q1".into(), sql: "SELECT 1".into(), builder: Some(builder), ..Default::default() }; + let plain = EditorTab { id: "q2".into(), ..Default::default() }; + let session = EditorSession { tabs: vec![open, plain], active_tab: "q1".into() }; + store.save(session.clone()).unwrap(); + let body = fs::read_to_string(tmp.path().join("editor_session.json")).unwrap(); + assert_eq!(body.matches("\"builderTab\"").count(), 1, "{body}"); + assert_eq!(SessionStore::open(tmp.path()).unwrap().get(), session); + let old = r#"{"tabs":[{"id":"q3","sql":"SELECT 1","builder":{"hidden":true}}],"activeTab":"q3"}"#; + fs::write(tmp.path().join("editor_session.json"), old).unwrap(); + assert_eq!(SessionStore::open(tmp.path()).unwrap().get().tabs[0].builder, None); + } + #[test] fn empty_tabs_are_written_as_an_array() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/barsql-ui/locales/bg.json b/crates/barsql-ui/locales/bg.json index 0475e20..81d147e 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -32,6 +32,7 @@ "recentConnections": "Скорошни връзки", "pickEngine": "Или започнете с база данни", "queryTabWithConn": "Заявка {{num}} · {{conn}}", + "builderTabWithConn": "Конструктор {{num}} · {{conn}}", "statusRunning": "Изпълнява се… {{seconds}} s", "statusStreaming_one": "Зареждане… {{count}} ред · {{seconds}} s", "statusStreaming_other": "Зареждане… {{count}} реда · {{seconds}} s", @@ -317,6 +318,7 @@ "shortcuts": { "items": { "showAlgebra": "Показване на заявката като релационна алгебра", + "openQueryBuilder": "Конструктор на заявки", "runSelection": "Изпълни избраното или заявката", "commandPalette": "Палитра с команди", "saveQueryAs": "Запази заявката като" @@ -565,6 +567,77 @@ "rename": "Преименуване" } }, + "queryBuilder": { + "open": "Конструктор", + "openTooltip": "Отвори избраното или заявката при курсора в нов таб на конструктора ({{shortcut}})", + "openInBuilder": "Отвори в конструктора", + "openInEditor": "Отвори в редактора", + "runTooltip": "Изпълни заявката ({{shortcut}})", + "sqlView": "SQL", + "switchTooltip": "Превключи между конструктора и SQL ({{shortcut}})", + "editSql": "Редактирай SQL", + "addTable": "Добави таблица", + "noTables": "Още няма заредени таблици", + "empty": "Плъзнете таблици тук от страничния панел или ги изберете от „Добави таблица“.", + "arrange": "Подреди таблиците", + "hint": "Кликнете колона, за да я изберете · Плъзнете колона върху колона от друга таблица, за да ги съедините · Плъзнете заглавието на таблица, за да я преместите · Плъзнете фона за преместване, {{modifier}}+скрол за мащаб · Десен клик върху колона за агрегати, сортиране и филтри", + "loading": "Зареждане на колоните…", + "unknownTable": "Не е намерена в тази връзка", + "columnsFailed": "Колоните не се заредиха", + "removeTable": "Премахни таблицата", + "setAlias": "Задай псевдоним…", + "aliasTitle": "Псевдоним за {{table}}", + "aliasLabel": "Псевдоним", + "aliasPlaceholder": "псевдоним", + "aliasConfirm": "Задай псевдоним", + "allColumns": "Избери всички колони (*)", + "aggregate": "Агрегат", + "noAggregate": "Без", + "sortAsc": "Сортирай възходящо", + "sortDesc": "Сортирай низходящо", + "noSort": "Без сортиране", + "filterColumn": "Филтрирай по тази колона", + "removeJoin": "Премахни съединението", + "join": { + "inner": "Вътрешно съединение (INNER)", + "left": "Ляво съединение (LEFT)", + "right": "Дясно съединение (RIGHT)", + "full": "Пълно съединение (FULL)" + }, + "notQuery": "В конструктора може да се покаже само SELECT.", + "unsupported": "Конструкторът все още не може да покаже {{what}}.", + "syntax": "Заявката не може да се прочете около „{{near}}“.", + "syntaxEnd": "Заявката свършва, преди да е завършена.", + "hidePanel": "Скрий панела", + "showPanel": "Покажи панела", + "moreColumns": "Още {{count}} колона", + "moreColumns_other": "Още {{count}} колони", + "fewerColumns": "Покажи по-малко", + "columnsEmpty": "Всички колони (*). Кликнете колони в таблиците, за да изберете някои.", + "everyColumn": "Всички колони (*)", + "addExpression": "Израз…", + "expressionTitle": "Добавяне на израз", + "expressionLabel": "SQL израз", + "expressionPlaceholder": "цена * количество", + "distinct": "Само уникални редове", + "add": "Добави", + "remove": "Премахни", + "filters": "Филтри", + "filtersEmpty": "Всички редове.", + "having": "Филтри на групите", + "havingEmpty": "Всички групи.", + "rawCondition": "SQL условие", + "rawPlaceholder": "условие на SQL", + "valuePlaceholder": "стойност", + "groupBy": "Групиране по", + "groupEmpty": "Без групиране.", + "sort": "Сортиране", + "sortEmpty": "Без определен ред.", + "rows": "Редове", + "limit": "Лимит", + "offset": "Отместване", + "everyRow": "всички" + }, "erDiagram": { "exportSvg": "Запазване като SVG", "tables": "{{count}} таблица", diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index 90fcd3d..6d539b5 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -32,6 +32,7 @@ "recentConnections": "Zuletzt verwendete Verbindungen", "pickEngine": "Oder mit einer Engine beginnen", "queryTabWithConn": "Abfrage {{num}} · {{conn}}", + "builderTabWithConn": "Designer {{num}} · {{conn}}", "statusRunning": "Läuft… {{seconds}} s", "statusStreaming_one": "Lädt… {{count}} Zeile · {{seconds}} s", "statusStreaming_other": "Lädt… {{count}} Zeilen · {{seconds}} s", @@ -317,6 +318,7 @@ "shortcuts": { "items": { "showAlgebra": "Die Abfrage als relationale Algebra anzeigen", + "openQueryBuilder": "Abfrage-Designer", "runSelection": "Auswahl oder Anweisung ausführen", "commandPalette": "Befehlspalette", "saveQueryAs": "Abfrage speichern unter" @@ -566,6 +568,77 @@ "rename": "Umbenennung" } }, + "queryBuilder": { + "open": "Designer", + "openTooltip": "Die Auswahl oder die Anweisung an der Einfügemarke in einem neuen Designer-Tab öffnen ({{shortcut}})", + "openInBuilder": "Im Designer öffnen", + "openInEditor": "Im Editor öffnen", + "runTooltip": "Abfrage ausführen ({{shortcut}})", + "sqlView": "SQL", + "switchTooltip": "Zwischen Designer und SQL wechseln ({{shortcut}})", + "editSql": "SQL bearbeiten", + "addTable": "Tabelle hinzufügen", + "noTables": "Noch keine Tabellen geladen", + "empty": "Tabellen aus der Seitenleiste hierher ziehen oder über „Tabelle hinzufügen“ wählen.", + "arrange": "Tabellen anordnen", + "hint": "Spalte anklicken, um sie auszuwählen · Spalte auf die einer anderen Tabelle ziehen, um beide zu verknüpfen · Tabellenkopf ziehen, um die Tabelle zu verschieben · Hintergrund ziehen zum Verschieben, {{modifier}}+Scrollen zum Zoomen · Rechtsklick auf eine Spalte für Aggregate, Sortierung und Filter", + "loading": "Spalten werden geladen…", + "unknownTable": "Auf dieser Verbindung nicht gefunden", + "columnsFailed": "Spalten nicht geladen", + "removeTable": "Tabelle entfernen", + "setAlias": "Alias festlegen…", + "aliasTitle": "Alias für {{table}}", + "aliasLabel": "Alias", + "aliasPlaceholder": "Alias", + "aliasConfirm": "Alias festlegen", + "allColumns": "Alle Spalten auswählen (*)", + "aggregate": "Aggregat", + "noAggregate": "Keins", + "sortAsc": "Aufsteigend sortieren", + "sortDesc": "Absteigend sortieren", + "noSort": "Nicht sortieren", + "filterColumn": "Nach dieser Spalte filtern", + "removeJoin": "Verknüpfung entfernen", + "join": { + "inner": "Inner Join", + "left": "Left Join", + "right": "Right Join", + "full": "Full Join" + }, + "notQuery": "Nur ein SELECT kann im Designer angezeigt werden.", + "unsupported": "Der Designer kann {{what}} noch nicht anzeigen.", + "syntax": "Die Anweisung ist bei „{{near}}“ nicht lesbar.", + "syntaxEnd": "Die Anweisung endet, bevor sie vollständig ist.", + "hidePanel": "Bereich ausblenden", + "showPanel": "Bereich einblenden", + "moreColumns": "{{count}} weitere Spalte", + "moreColumns_other": "{{count}} weitere Spalten", + "fewerColumns": "Weniger zeigen", + "columnsEmpty": "Alle Spalten (*). Spalten in den Tabellen anklicken, um welche auszuwählen.", + "everyColumn": "Alle Spalten (*)", + "addExpression": "Ausdruck…", + "expressionTitle": "Ausdruck hinzufügen", + "expressionLabel": "SQL-Ausdruck", + "expressionPlaceholder": "preis * menge", + "distinct": "Nur eindeutige Zeilen", + "add": "Hinzufügen", + "remove": "Entfernen", + "filters": "Filter", + "filtersEmpty": "Alle Zeilen.", + "having": "Gruppenfilter", + "havingEmpty": "Alle Gruppen.", + "rawCondition": "SQL-Bedingung", + "rawPlaceholder": "eine Bedingung in SQL", + "valuePlaceholder": "Wert", + "groupBy": "Gruppieren nach", + "groupEmpty": "Nicht gruppiert.", + "sort": "Sortierung", + "sortEmpty": "In keiner bestimmten Reihenfolge.", + "rows": "Zeilen", + "limit": "Limit", + "offset": "Offset", + "everyRow": "alle" + }, "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 805fde9..b638f85 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -32,6 +32,7 @@ "recentConnections": "Recent connections", "pickEngine": "Or start with an engine", "queryTabWithConn": "Query {{num}} · {{conn}}", + "builderTabWithConn": "Builder {{num}} · {{conn}}", "statusRunning": "Running… {{seconds}} s", "statusStreaming_one": "Streaming… {{count}} row · {{seconds}} s", "statusStreaming_other": "Streaming… {{count}} rows · {{seconds}} s", @@ -339,6 +340,7 @@ "shortcuts": { "items": { "showAlgebra": "Show the query as relational algebra", + "openQueryBuilder": "Query builder", "runSelection": "Run selection or statement", "commandPalette": "Command palette", "saveQueryAs": "Save query as" @@ -591,6 +593,77 @@ "rename": "Rename" } }, + "queryBuilder": { + "open": "Builder", + "openTooltip": "Open the selection or the statement at the caret in a new builder tab ({{shortcut}})", + "openInBuilder": "Open in builder", + "openInEditor": "Open in editor", + "runTooltip": "Run the query ({{shortcut}})", + "sqlView": "SQL", + "switchTooltip": "Switch between the builder and its SQL ({{shortcut}})", + "editSql": "Edit SQL", + "addTable": "Add table", + "noTables": "No tables loaded yet", + "empty": "Drag tables here from the sidebar, or pick them from Add table.", + "arrange": "Arrange tables", + "hint": "Click a column to pick it · Drag a column onto another table's to join them · Drag a table's header to move it · Drag the background to pan, {{modifier}}+scroll to zoom · Right-click a column for aggregates, sorting and filters", + "loading": "Loading columns…", + "unknownTable": "Not found on this connection", + "columnsFailed": "Columns didn't load", + "removeTable": "Remove table", + "setAlias": "Set alias…", + "aliasTitle": "Alias for {{table}}", + "aliasLabel": "Alias", + "aliasPlaceholder": "alias", + "aliasConfirm": "Set alias", + "allColumns": "Pick all its columns (*)", + "aggregate": "Aggregate", + "noAggregate": "None", + "sortAsc": "Sort ascending", + "sortDesc": "Sort descending", + "noSort": "Don't sort", + "filterColumn": "Filter on this column", + "removeJoin": "Remove join", + "join": { + "inner": "Inner join", + "left": "Left join", + "right": "Right join", + "full": "Full join" + }, + "notQuery": "Only a SELECT can be shown in the builder.", + "unsupported": "The builder can't show {{what}} yet.", + "syntax": "Couldn't read the statement near \"{{near}}\".", + "syntaxEnd": "The statement ends before it's complete.", + "hidePanel": "Hide the panel", + "showPanel": "Show the panel", + "moreColumns": "{{count}} more column", + "moreColumns_other": "{{count}} more columns", + "fewerColumns": "Show fewer", + "columnsEmpty": "Every column (*). Click columns on the tables to pick some.", + "everyColumn": "Every column (*)", + "addExpression": "Expression…", + "expressionTitle": "Add an expression", + "expressionLabel": "SQL expression", + "expressionPlaceholder": "price * quantity", + "distinct": "Only distinct rows", + "add": "Add", + "remove": "Remove", + "filters": "Filters", + "filtersEmpty": "Every row.", + "having": "Group filters", + "havingEmpty": "Every group.", + "rawCondition": "SQL condition", + "rawPlaceholder": "a condition in SQL", + "valuePlaceholder": "value", + "groupBy": "Group by", + "groupEmpty": "Not grouped.", + "sort": "Sort", + "sortEmpty": "In no particular order.", + "rows": "Rows", + "limit": "Limit", + "offset": "Offset", + "everyRow": "all" + }, "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 ce09511..9f8885d 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -32,6 +32,7 @@ "recentConnections": "Conexiones recientes", "pickEngine": "O empieza con un motor", "queryTabWithConn": "Consulta {{num}} · {{conn}}", + "builderTabWithConn": "Constructor {{num}} · {{conn}}", "statusRunning": "Ejecutando… {{seconds}} s", "statusStreaming_one": "Recibiendo… {{count}} fila · {{seconds}} s", "statusStreaming_other": "Recibiendo… {{count}} filas · {{seconds}} s", @@ -317,6 +318,7 @@ "shortcuts": { "items": { "showAlgebra": "Mostrar la consulta como álgebra relacional", + "openQueryBuilder": "Constructor de consultas", "runSelection": "Ejecutar la selección o la sentencia", "commandPalette": "Paleta de comandos", "saveQueryAs": "Guardar consulta como" @@ -575,6 +577,77 @@ "rename": "Renombrar" } }, + "queryBuilder": { + "open": "Constructor", + "openTooltip": "Abrir la selección o la sentencia bajo el cursor en una pestaña nueva del constructor ({{shortcut}})", + "openInBuilder": "Abrir en el constructor", + "openInEditor": "Abrir en el editor", + "runTooltip": "Ejecutar la consulta ({{shortcut}})", + "sqlView": "SQL", + "switchTooltip": "Cambiar entre el constructor y su SQL ({{shortcut}})", + "editSql": "Editar SQL", + "addTable": "Añadir tabla", + "noTables": "Aún no hay tablas cargadas", + "empty": "Arrastra tablas aquí desde la barra lateral o elígelas en Añadir tabla.", + "arrange": "Ordenar tablas", + "hint": "Haz clic en una columna para elegirla · Arrastra una columna sobre la de otra tabla para unirlas · Arrastra la cabecera de una tabla para moverla · Arrastra el fondo para desplazarte, {{modifier}}+rueda para acercar · Clic derecho en una columna para agregados, orden y filtros", + "loading": "Cargando columnas…", + "unknownTable": "No se encontró en esta conexión", + "columnsFailed": "No se cargaron las columnas", + "removeTable": "Quitar tabla", + "setAlias": "Poner alias…", + "aliasTitle": "Alias de {{table}}", + "aliasLabel": "Alias", + "aliasPlaceholder": "alias", + "aliasConfirm": "Poner alias", + "allColumns": "Elegir todas sus columnas (*)", + "aggregate": "Agregado", + "noAggregate": "Ninguno", + "sortAsc": "Orden ascendente", + "sortDesc": "Orden descendente", + "noSort": "Sin orden", + "filterColumn": "Filtrar por esta columna", + "removeJoin": "Quitar la unión", + "join": { + "inner": "Unión interna (INNER)", + "left": "Unión izquierda (LEFT)", + "right": "Unión derecha (RIGHT)", + "full": "Unión completa (FULL)" + }, + "notQuery": "Solo una consulta SELECT puede mostrarse en el constructor.", + "unsupported": "El constructor aún no puede mostrar {{what}}.", + "syntax": "No se pudo leer la sentencia cerca de \"{{near}}\".", + "syntaxEnd": "La sentencia termina antes de estar completa.", + "hidePanel": "Ocultar el panel", + "showPanel": "Mostrar el panel", + "moreColumns": "{{count}} columna más", + "moreColumns_other": "{{count}} columnas más", + "fewerColumns": "Mostrar menos", + "columnsEmpty": "Todas las columnas (*). Haz clic en columnas de las tablas para elegir algunas.", + "everyColumn": "Todas las columnas (*)", + "addExpression": "Expresión…", + "expressionTitle": "Añadir una expresión", + "expressionLabel": "Expresión SQL", + "expressionPlaceholder": "precio * cantidad", + "distinct": "Solo filas distintas", + "add": "Añadir", + "remove": "Quitar", + "filters": "Filtros", + "filtersEmpty": "Todas las filas.", + "having": "Filtros de grupo", + "havingEmpty": "Todos los grupos.", + "rawCondition": "Condición SQL", + "rawPlaceholder": "una condición en SQL", + "valuePlaceholder": "valor", + "groupBy": "Agrupar por", + "groupEmpty": "Sin agrupar.", + "sort": "Orden", + "sortEmpty": "Sin un orden concreto.", + "rows": "Filas", + "limit": "Límite", + "offset": "Desplazamiento", + "everyRow": "todas" + }, "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 02af546..8eef1b5 100644 --- a/crates/barsql-ui/src/actions.rs +++ b/crates/barsql-ui/src/actions.rs @@ -55,6 +55,7 @@ actions!( ExplainQuery, ExplainAnalyze, ShowAlgebra, + OpenQueryBuilder, NextTab, PrevTab, FormatQuery, diff --git a/crates/barsql-ui/src/algebra_graph.rs b/crates/barsql-ui/src/algebra_graph.rs index c37d98e..2123e15 100644 --- a/crates/barsql-ui/src/algebra_graph.rs +++ b/crates/barsql-ui/src/algebra_graph.rs @@ -931,7 +931,6 @@ impl Render for AlgebraGraph { 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); @@ -941,8 +940,6 @@ impl Render for AlgebraGraph { let content = div() .relative() .flex_none() - .ml(margin.x) - .mt(margin.y) .w(rems(layout.width)) .h(rems(layout.height)) .child( @@ -957,7 +954,7 @@ impl Render for AlgebraGraph { this.select(None, cx); } })) - .child(zoom::zoomed(self.viewport.zoom, content)); + .child(zoom::stage(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() diff --git a/crates/barsql-ui/src/assets.rs b/crates/barsql-ui/src/assets.rs index 021985c..bbc869e 100644 --- a/crates/barsql-ui/src/assets.rs +++ b/crates/barsql-ui/src/assets.rs @@ -16,6 +16,7 @@ icon_assets!( Activity, ArrowDownAZ, Binary, + Blocks, Bookmark, BookmarkPlus, Box, diff --git a/crates/barsql-ui/src/command_palette.rs b/crates/barsql-ui/src/command_palette.rs index 6dd6ecc..baab589 100644 --- a/crates/barsql-ui/src/command_palette.rs +++ b/crates/barsql-ui/src/command_palette.rs @@ -36,6 +36,7 @@ fn catalog(cx: &App) -> Vec<(String, Box)> { (item("shortcuts.items.explainQuery"), Box::new(ExplainQuery)), (item("shortcuts.items.explainAnalyze"), Box::new(ExplainAnalyze)), (item("shortcuts.items.showAlgebra"), Box::new(ShowAlgebra)), + (item("shortcuts.items.openQueryBuilder"), Box::new(OpenQueryBuilder)), (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/completion.rs b/crates/barsql-ui/src/completion.rs index affb977..3a72e19 100644 --- a/crates/barsql-ui/src/completion.rs +++ b/crates/barsql-ui/src/completion.rs @@ -237,13 +237,18 @@ impl Completion { // A name starting opens the list and typing it refilters. Backspace inside it does too. Anything else closes it. fn changed(&mut self, window: &mut Window, cx: &mut Context) { - let (text, cursor) = { + let (text, cursor, focused) = { let state = self.editor.read(cx); - (state.value().to_string(), state.cursor()) + (state.value().to_string(), state.cursor(), state.focus_handle(cx).is_focused(window)) }; if text == self.text && cursor == self.cursor { return; } + // Written from elsewhere, like a builder tab's canvas, so not typed. + if !focused { + (self.text, self.cursor) = (text, cursor); + return self.hide(cx); + } let grown = text.len().saturating_sub(self.text.len()); let removed = self.text.len().saturating_sub(text.len()); let was_open = self.open diff --git a/crates/barsql-ui/src/editor_commands.rs b/crates/barsql-ui/src/editor_commands.rs index 9e46413..d979d48 100644 --- a/crates/barsql-ui/src/editor_commands.rs +++ b/crates/barsql-ui/src/editor_commands.rs @@ -178,7 +178,7 @@ fn edit( } // Unlike selecting the range and calling `replace`, this leaves the caret where it was for undo to put back. -fn replace_range( +pub(crate) fn replace_range( state: &mut EditorState, range: Range, new: String, diff --git a/crates/barsql-ui/src/er_diagram.rs b/crates/barsql-ui/src/er_diagram.rs index 77fcb13..a39b23a 100644 --- a/crates/barsql-ui/src/er_diagram.rs +++ b/crates/barsql-ui/src/er_diagram.rs @@ -1,4 +1,4 @@ -mod layout; +pub(crate) mod layout; pub(crate) mod search; pub(crate) mod svg; #[cfg(test)] @@ -402,7 +402,6 @@ impl ErDiagram { let content = div() .relative() .flex_none() - .m_auto() .w(rems(layout.width)) .h(rems(layout.height)) .child( @@ -419,7 +418,7 @@ impl ErDiagram { .absolute() .inset_0(), ); - zoom::zoomed(self.viewport.zoom, content) + zoom::stage(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 @@ -552,7 +551,7 @@ impl ErDiagram { } // Doubling the spacing keeps zoomed-out dots from crowding. -fn paint_dots(bounds: Bounds, offset: Point, zoom: f32, color: Hsla, window: &mut Window) { +pub(crate) fn paint_dots(bounds: Bounds, offset: Point, zoom: f32, color: Hsla, window: &mut Window) { let mut step = 20. * zoom; while step < 12. { step *= 2.; diff --git a/crates/barsql-ui/src/er_diagram/layout.rs b/crates/barsql-ui/src/er_diagram/layout.rs index b342182..8397425 100644 --- a/crates/barsql-ui/src/er_diagram/layout.rs +++ b/crates/barsql-ui/src/er_diagram/layout.rs @@ -9,8 +9,8 @@ pub const BOX_W: f32 = 16.923; pub const HEADER_H: f32 = 2.154; pub const ROW_H: f32 = 1.692; const GAP_X: f32 = 6.154; -const GAP_Y: f32 = 1.846; -const MARGIN: f32 = 1.538; +pub const GAP_Y: f32 = 1.846; +pub const MARGIN: f32 = 1.538; // The layout aims for a diagram this much wider than tall, like the dialog it opens in. const ASPECT: f32 = 1.6; // Rounds of reordering, each one across the columns and back. @@ -92,35 +92,43 @@ pub struct EdgePath { pub head: [Spot; 3], } +// A line between rows of two boxes at the given corners: its ends, its controls, and its bend, 1 rightwards, -1 +// leftwards or 0 looping out on the right from boxes in one column. It leaves the facing sides, level at both ends. +pub fn route(from: (Spot, Option), to: (Spot, Option)) -> (Spot, Spot, (Spot, Spot), f32) { + let row_y = |(_, y): Spot, row: Option| match row { + Some(row) => y + HEADER_H + ROW_H * (row as f32 + 0.5), + None => y + HEADER_H / 2., + }; + let ((a, a_row), (b, b_row)) = (from, to); + let (y1, y2) = (row_y(a, a_row), row_y(b, b_row)); + let (x1, x2, bend) = if b.0 + BOX_W <= a.0 { + (a.0, b.0 + BOX_W, -1.) + } else if b.0 >= a.0 + BOX_W { + (a.0 + BOX_W, b.0, 1.) + } else { + (a.0 + BOX_W, b.0 + BOX_W, 0.) + }; + let reach = ((x2 - x1).abs() / 2.).max(2.308); + let controls = match bend { + 0. => ((x1 + reach, y1), (x2 + reach, y2)), + _ => ((x1 + reach * bend, y1), (x2 - reach * bend, y2)), + }; + ((x1, y1), (x2, y2), controls, bend) +} + impl Layout { - // From the side facing the other box, with horizontal tangents. Both ends in the same column loop out on the right. pub fn path(&self, edge: &Edge) -> EdgePath { - let row_y = |placed: Placed, row: Option| match row { - Some(row) => placed.y + HEADER_H + ROW_H * (row as f32 + 0.5), - None => placed.y + HEADER_H / 2., - }; let (from, to) = (self.boxes[edge.from.0], self.boxes[edge.to.0]); - let (y1, y2) = (row_y(from, edge.from.1), row_y(to, edge.to.1)); + let ((x1, y1), (x2, y2), controls, bend) = route(((from.x, from.y), edge.from.1), ((to.x, to.y), edge.to.1)); // `inward` is the way the line arrives: +1 into a box's left side, -1 into its right. - let (x1, x2, bend, inward) = if to.x + BOX_W <= from.x { - (from.x, to.x + BOX_W, -1., -1.) - } else if to.x >= from.x + BOX_W { - (from.x + BOX_W, to.x, 1., 1.) - } else { - (from.x + BOX_W, to.x + BOX_W, 0., -1.) - }; - let reach = ((x2 - x1).abs() / 2.).max(2.308); - let (c1, c2) = match bend { - 0. => (x1 + reach, x2 + reach), - _ => (x1 + reach * bend, x2 - reach * bend), - }; + let inward = if bend > 0. { 1. } else { -1. }; // The prongs meet outside the box and spread to its side. A loop leaves to the right. let (out, foot, half) = (if bend == 0. { 1. } else { bend }, 0.692, 0.346); let (bar, back) = (x2 - inward * 0.462, x2 - inward * foot); EdgePath { from: (x1, y1), to: (x2, y2), - controls: ((c1, y1), (c2, y2)), + controls, prongs: [-half, 0., half].map(|dy| ((x1 + out * foot, y1), (x1, y1 + dy))), bar: ((bar, y2 - half), (bar, y2 + half)), head: [(x2, y2), (back, y2 - half), (back, y2 + half)], diff --git a/crates/barsql-ui/src/er_diagram/tests.rs b/crates/barsql-ui/src/er_diagram/tests.rs index a800678..7c2f78a 100644 --- a/crates/barsql-ui/src/er_diagram/tests.rs +++ b/crates/barsql-ui/src/er_diagram/tests.rs @@ -188,6 +188,32 @@ fn command_wheel_zooms_around_the_pointer_and_a_plain_wheel_scrolls(cx: &mut Tes assert!(offset(&view, cx).y < scrolled.y, "it scrolls"); } +// Zoomed in until it's taller than the view, it still scrolls up to its first tables. +#[gpui_kit::test] +fn a_zoomed_in_diagram_scrolls_up_to_its_top(cx: &mut TestAppContext) { + let (view, _, cx) = diagram(cx, small()); + cx.simulate_resize(size(px(1200.), px(160.))); + cx.update(|window, cx| { + view.update(cx, |view, cx| { + view.viewport.zoom_to(zoom::MAX, None, window.rem_size()); + view.viewport.scroll.set_offset(point(px(0.), px(0.))); + cx.notify(); + }) + }); + let (area, rem) = (bounds(cx, "er-diagram"), cx.update(|window, _| window.rem_size())); + let content = view.read_with(cx, |view, _| view.viewport.content(rem, view.viewport.zoom)); + assert!(content.height > area.size.height * 1.5, "{content:?} overflows {area:?}"); + let tables = ["er-table-0", "er-table-1", "er-table-2", "er-table-3"].map(|table| bounds(cx, table)); + let top = tables.iter().map(|table| table.top()).fold(area.bottom(), |a, b| a.min(b)); + assert!(top >= area.top(), "the first tables start at {top:?}, above the view's top {:?}", area.top()); + let expected = view.read_with(cx, |view, _| { + let at = view.layout.boxes[0]; + view.viewport.in_window((at.x, at.y), rem) + }); + let drawn = tables[0].origin; + assert!((drawn - expected).x.abs() < px(1.) && (drawn - expected).y.abs() < px(1.), "{drawn:?}, not {expected:?}"); +} + #[gpui_kit::test] fn a_pinch_zooms(cx: &mut TestAppContext) { let (view, _, cx) = diagram(cx, small()); diff --git a/crates/barsql-ui/src/er_diagram/zoom.rs b/crates/barsql-ui/src/er_diagram/zoom.rs index 8b2635b..e450589 100644 --- a/crates/barsql-ui/src/er_diagram/zoom.rs +++ b/crates/barsql-ui/src/er_diagram/zoom.rs @@ -275,6 +275,11 @@ pub fn buttons( ) } +// At least the view's size, centring smaller content; Taffy shares overflow with auto margins, hiding the top. +pub fn stage(content: impl IntoElement) -> Div { + div().flex_none().self_start().min_w_full().min_h_full().flex().items_center().justify_center().child(content) +} + pub struct Zoomed { zoom: f32, rem: Pixels, diff --git a/crates/barsql-ui/src/form.rs b/crates/barsql-ui/src/form.rs index 9eb578d..e4e44c5 100644 --- a/crates/barsql-ui/src/form.rs +++ b/crates/barsql-ui/src/form.rs @@ -37,6 +37,11 @@ pub fn filter_input(state: &Entity, window: &Window, cx: &App) -> In field(state, rems(0.923), rems(0.615), window, cx) } +// As tall as a tool button or select_small. Input's own `h` sizes only multi-line editors. +pub fn tool_input(state: &Entity, window: &Window, cx: &App) -> Input { + Styled::h(field(state, TEXT_XS, rems(0.615), window, cx), rems(TOOL_REM)) +} + // Focus thickens the border to 2px, so the padding drops 1px to keep the text still. fn field(state: &Entity, text: Rems, padding: Rems, window: &Window, cx: &App) -> Input { let theme = cx.theme(); @@ -390,6 +395,36 @@ pub fn checkbox( .child(div().flex_1().min_w_0().text_size(TEXT_BASE).font_medium().child(label.into())) } +// A check box: filled with the colour and ticked when on. +pub fn check_mark(on: Option, cx: &App) -> Div { + let theme = cx.theme(); + div().flex_none().size(rems(1.077)).flex().items_center().justify_center().rounded(RADIUS_SM).border_1().map(|el| { + match on { + Some(color) => el + .bg(color) + .border_color(color) + .child(Icon::new(IconName::Check).size(ICON_2XS).text_color(theme.primary_foreground)), + None => el.border_color(theme.muted_foreground.opacity(TINT_BORDER)), + } + }) +} + +// A warning strip across a view, its buttons after the message. +pub fn warning_bar(message: impl Into, cx: &App) -> Div { + let theme = cx.theme(); + h_flex() + .flex_none() + .gap(rems(0.462)) + .px(rems(0.769)) + .py(rems(0.308)) + .bg(theme.warning.opacity(TINT)) + .border_b_1() + .border_color(theme.warning.opacity(TINT_BORDER)) + .text_size(TEXT_SM) + .child(Icon::new(IconName::TriangleAlert).size(ICON_XS).text_color(theme.warning)) + .child(div().flex_1().min_w_0().truncate().child(message.into())) +} + // A 24px row of a column list, which toggles as a whole: a check box filled with the colour when on, the name, and // the type faintly after it. The name takes the row's text colour. A row that isn't `enabled` dims. pub fn pick_row( @@ -401,20 +436,11 @@ pub fn pick_row( cx: &App, ) -> Stateful
{ let theme = cx.theme(); - let (hover, check, muted) = (theme.accent, theme.primary_foreground, theme.muted_foreground); + let (hover, muted) = (theme.accent, theme.muted_foreground); let group = SharedString::from(format!("{id}-row")); let type_name: SharedString = type_name.into(); - let mark = - div().flex_none().size(rems(1.077)).flex().items_center().justify_center().rounded(RADIUS_SM).border_1().map( - |el| match on { - Some(color) => { - el.bg(color).border_color(color).child(Icon::new(IconName::Check).size(ICON_2XS).text_color(check)) - } - None => el - .border_color(muted.opacity(TINT_BORDER)) - .when(enabled, |el| el.group_hover(group.clone(), |style| style.border_color(muted))), - }, - ); + let mark = check_mark(on, cx) + .when(on.is_none() && enabled, |el| el.group_hover(group.clone(), |style| style.border_color(muted))); h_flex() .id(ElementId::Name(id)) .group(group) diff --git a/crates/barsql-ui/src/lib.rs b/crates/barsql-ui/src/lib.rs index 55ad3fa..972f8bb 100644 --- a/crates/barsql-ui/src/lib.rs +++ b/crates/barsql-ui/src/lib.rs @@ -33,6 +33,7 @@ mod occurrences; mod params_dialog; mod plan_tree; mod plan_view; +mod query_builder; mod query_tab; mod quick_search; mod relative_time; @@ -147,6 +148,7 @@ pub fn run(bar: BarApp, options: LaunchOptions) { schema_tree::init(cx); list_nav::init(cx); editor_commands::init(cx); + query_builder::init(cx); completion::init(cx); shortcuts::init(cx); cx.on_app_quit(move |_| { diff --git a/crates/barsql-ui/src/list_nav.rs b/crates/barsql-ui/src/list_nav.rs index 56637b6..394bf56 100644 --- a/crates/barsql-ui/src/list_nav.rs +++ b/crates/barsql-ui/src/list_nav.rs @@ -34,7 +34,7 @@ pub fn group_header( .child(div().flex_none().child(count.to_string())) } -pub fn drag_chip(label: SharedString, cx: &App) -> Div { +pub fn drag_chip(content: impl IntoElement, cx: &App) -> Div { let theme = cx.theme(); div() .px(rems(0.462)) @@ -45,7 +45,7 @@ pub fn drag_chip(label: SharedString, cx: &App) -> Div { .bg(theme.popover) .text_size(TEXT_SM) .opacity(0.9) - .child(label) + .child(content) } pub fn drop_ring(style: StyleRefinement, cx: &App) -> StyleRefinement { diff --git a/crates/barsql-ui/src/query_builder.rs b/crates/barsql-ui/src/query_builder.rs new file mode 100644 index 0000000..40471da --- /dev/null +++ b/crates/barsql-ui/src/query_builder.rs @@ -0,0 +1,1289 @@ +mod geometry; +mod panel; +#[cfg(test)] +mod tests; + +use std::collections::{HashMap, HashSet}; + +use barsql_core::capabilities::DefaultSchema; +use barsql_core::{ColumnInfo, ConnectionConfig, SqlDialect, TableInfo, scope}; +use barsql_sql::Dialect; +use barsql_sql::design::{ + self, Aggregate, ColumnRef, Condition, Design, ImportError, Item, JoinKind, Op, Operand, Table, +}; +use barsql_sql::display_type; +use gpui_kit::assets::IconName as Lucide; +use gpui_kit::component::button::{Button, ButtonVariants}; +use gpui_kit::component::menu::{ContextMenuExt, DropdownMenu, PopupMenu, PopupMenuItem}; +use gpui_kit::component::scroll::ScrollbarAxis; +use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, Sizable, StyledExt, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +pub(crate) use self::geometry::Place; +use self::geometry::{CARD_W, Curve, HEADER_H, ROW_H, arrange, beside, card_height, curve, extent}; +use crate::er_diagram::zoom::{self, Viewport}; +use crate::form::{self, ToolButton as _}; +use crate::i18n::{t, t_with}; +use crate::scrollbars::HoverScrollbar as _; +use crate::spinner::Spinner; +use crate::state::{set_setting_bool, setting_bool}; +use crate::tokens::{DIMMED, ICON_XS, RADIUS, TEXT_2XS, TEXT_SM, TEXT_XS}; +use crate::{dialogs, er_diagram, list_nav, schema, theme}; + +// A table dragged from the schema tree onto the canvas. +#[derive(Clone)] +pub struct TableDrag { + pub connection_id: String, + pub schema: String, + pub table: String, +} + +impl Render for TableDrag { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + chip(self.table.clone().into(), Lucide::Table2, cx) + } +} + +// A column dragged onto another table's, to join on them. +#[derive(Clone)] +struct LinkDrag(ColumnRef, SharedString); + +impl Render for LinkDrag { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + chip(self.1.clone(), Lucide::Link, cx) + } +} + +// A card, dragged by its header. +#[derive(Clone)] +struct MoveDrag; + +impl Render for MoveDrag { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Empty + } +} + +fn chip(label: SharedString, icon: Lucide, cx: &App) -> impl IntoElement + use<> { + let icon = Icon::new(icon).size(ICON_XS).text_color(cx.theme().muted_foreground); + list_nav::drag_chip(h_flex().gap(rems(0.385)).child(icon).child(label), cx) +} + +// A click that edits the design. +fn on_edit( + this: &WeakEntity, + change: impl Fn(&mut Design) + 'static, +) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { + let this = this.clone(); + move |_, _, cx| { + let _ = this.update(cx, |this, cx| this.edit(cx, &change)); + } +} + +// A card's row: a column, or a note in place of them. +fn card_row() -> Div { + h_flex().h(rems(ROW_H)).flex_none().px(rems(0.615)).gap(rems(0.462)) +} + +pub enum BuilderEvent { + // The new SQL, and the SQL it was made from. + Changed { base: String, sql: String }, + // Cards moved, which the session keeps. + Moved, + // The SQL view, to fix SQL the canvas can't show. + EditSql, +} + +struct Moving { + ix: usize, + from: Point, + place: Place, +} + +// Fitting stops here, so names stay readable; the rest scrolls. +const FIT_MIN: f32 = 0.7; +// Whether the panel beside the canvas shows, for every builder. +const PANEL_KEY: &str = "barsql-builder-panel"; + +const CONTEXT: &str = "QueryBuilder"; + +// Undo and Redo on the canvas step through the tab's history; its fields keep their own. +pub fn init(cx: &mut App) { + use gpui_kit::component::input::{Redo, Undo}; + let context = Some(CONTEXT); + cx.bind_keys([ + crate::actions::os_binding("secondary-z", Undo, context, cx), + crate::actions::os_binding("secondary-shift-z", Redo, context, cx), + ]); + if !cfg!(target_os = "macos") { + cx.bind_keys([KeyBinding::new("ctrl-y", Redo, context)]); + } +} + +// The columns a card lists, by index, and whether it offers more or fewer. +struct Rows { + shown: Vec, + toggle: bool, +} + +impl Rows { + fn lines(&self) -> usize { + self.shown.len() + usize::from(self.toggle) + } +} + +// Each table's columns once loaded, with the rows its card lists, worked out once a frame. +type Cards = Vec>; + +fn card_heights(cards: &Cards) -> Vec { + cards.iter().map(|card| card_height(card.as_ref().map_or(1, |(_, rows)| rows.lines()))).collect() +} + +// The row a column's card lists it on. +fn row_of(column: &ColumnRef, cards: &Cards) -> Option { + let (columns, rows) = cards.get(column.table)?.as_ref()?; + let at = columns.iter().position(|c| c.name.eq_ignore_ascii_case(&column.column))?; + rows.shown.iter().position(|&shown| shown == at) +} + +// A builder tab's query as tables on a canvas. +pub struct QueryBuilder { + connection: ConnectionConfig, + focus: FocusHandle, + design: Design, + // The SQL last read or written, read again as more columns load. + source: String, + problem: Option, + places: Vec, + // Places of tables a reread may bring back. + remembered: HashMap, + // Each table's schema and name in the schema cache. + found: Vec>, + // Tables with columns loaded, to read the SQL again when more are. + known: usize, + // Tables added here, to join by their foreign keys once their columns load. + unjoined: Vec, + viewport: Viewport, + // The zoom fitted to the view and that view's size, kept fitted till something else zooms. + fitted: Option<(f32, Size)>, + // Laid out by Arrange and not moved since, so laid out again as cards grow. + auto: bool, + moving: Option, + // The column dragged to another, and the pointer. + linking: Option<(ColumnRef, Point)>, + // Cards that list every column, by table. + expanded: HashSet, + // Columns a card has listed since the SQL was read, kept so a row doesn't vanish when unticked. + sticky: HashSet<(String, String)>, + panel: panel::Panel, + // Keeps the panel's width once a drag has paused. + width_save: Task<()>, + // Columns asked for that haven't come; a failed load waits for a reload. + asked: HashSet<(String, String)>, + // A frame was asked for to measure a canvas with no room. + measuring: bool, + _subscriptions: Vec, +} + +impl EventEmitter for QueryBuilder {} + +impl QueryBuilder { + pub(crate) fn new(connection: ConnectionConfig, places: Vec<(String, Place)>, cx: &mut Context) -> Self { + let subscriptions = vec![cx.observe_global::(|this, cx| this.schema_changed(cx))]; + schema::ensure_loaded(&connection.id, connection.driver.clone(), cx); + Self { + connection, + focus: cx.focus_handle(), + design: Design::default(), + source: String::new(), + problem: None, + places: vec![], + remembered: places.into_iter().map(|(key, place)| (key.to_lowercase(), place)).collect(), + found: vec![], + known: 0, + unjoined: vec![], + viewport: Viewport::new(1., 1.), + fitted: None, + auto: false, + moving: None, + linking: None, + expanded: HashSet::new(), + sticky: HashSet::new(), + panel: panel::Panel::default(), + width_save: Task::ready(()), + asked: HashSet::new(), + measuring: false, + _subscriptions: subscriptions, + } + } + + fn dialect(&self) -> SqlDialect { + self.connection.driver.dialect().unwrap_or(SqlDialect::Postgres) + } + + pub(crate) fn focus_handle(&self) -> FocusHandle { + self.focus.clone() + } + + // The SQL last read or written. + pub(crate) fn source(&self) -> &str { + &self.source + } + + // Nothing once every table and item is gone. + fn sql(&self) -> String { + match self.design.tables.is_empty() && self.design.items.is_empty() { + true => String::new(), + false => design::render(&self.design, &self.connection.driver), + } + } + + // By table name, for the session; none for a layout of its own, which is laid out again. + pub(crate) fn places(&self) -> Vec<(String, Place)> { + if self.auto { + return Vec::new(); + } + let mut places = self.remembered.clone(); + for (table, place) in self.design.tables.iter().zip(&self.places) { + places.insert(table.key().to_lowercase(), *place); + } + let mut places: Vec<(String, Place)> = places.into_iter().collect(); + places.sort_by(|a, b| a.0.cmp(&b.0)); + places + } + + pub(crate) fn set_connection(&mut self, connection: ConnectionConfig, cx: &mut Context) { + if connection.id != self.connection.id { + self.found.clear(); + self.asked.clear(); + } + self.connection = connection; + self.resolve(cx); + cx.notify(); + } + + // One it can't read keeps the last design, greyed out. + pub(crate) fn load(&mut self, sql: &str, cx: &mut Context) { + self.source = sql.to_string(); + self.asked.clear(); + let named = barsql_sql::lang::qualifiers(sql, Some(&self.connection.driver)); + schema::load_named_schemas(&self.connection.id, &named, cx); + match self.import(sql, cx) { + Ok(design) => { + self.problem = None; + self.set_design(design, cx); + } + Err(problem) => self.problem = Some(problem), + } + cx.notify(); + } + + fn import(&self, sql: &str, cx: &App) -> Result { + let columns = |table: &Table| { + let (schema, name) = self.find(table, cx)?; + let columns = schema::get(cx, &self.connection.id)?.columns(&schema, &name)?; + Some(columns.iter().map(|c| c.name.clone()).collect()) + }; + design::import(sql, &self.connection.driver, &columns) + } + + // Tables it already had keep their places, and what the schema cache found for them. + fn set_design(&mut self, design: Design, cx: &mut Context) { + for (table, place) in self.design.tables.iter().zip(&self.places) { + self.remembered.insert(table.key().to_lowercase(), *place); + } + let same = |a: &Table, b: &Table| a.name.eq_ignore_ascii_case(&b.name) && a.qualifier == b.qualifier; + let found: Vec> = design + .tables + .iter() + .map(|table| { + let old = self.design.tables.iter().position(|old| same(old, table))?; + self.found.get(old).cloned().flatten() + }) + .collect(); + let keys = |design: &Design| design.tables.iter().map(|t| t.key().to_lowercase()).collect::>(); + let unchanged = keys(&self.design) == keys(&design); + self.design = design; + self.found = found; + self.sticky.clear(); + self.resolve(cx); + let kept: Vec> = + self.design.tables.iter().map(|t| self.remembered.get(&t.key().to_lowercase()).copied()).collect(); + self.auto = kept.iter().all(Option::is_none) || (self.auto && unchanged); + if self.auto { + self.places = arrange(&self.design, &self.heights(cx)); + return; + } + let mut placed: Vec = kept.iter().flatten().copied().collect(); + self.places = kept + .into_iter() + .map(|place| { + place.unwrap_or_else(|| { + let place = beside(&placed); + placed.push(place); + place + }) + }) + .collect(); + } + + fn edit(&mut self, cx: &mut Context, change: impl FnOnce(&mut Design)) { + if self.problem.is_some() { + return; + } + let before = self.design.clone(); + change(&mut self.design); + if self.design == before { + return; + } + self.places.resize(self.design.tables.len(), Place::default()); + self.found.resize(self.design.tables.len(), None); + let sql = self.sql(); + let base = std::mem::replace(&mut self.source, sql.clone()); + cx.emit(BuilderEvent::Changed { base, sql }); + cx.notify(); + } + + // The keys leave the panel's fields first, so typing can't land in the next row. + fn remove(&mut self, window: &mut Window, cx: &mut Context, change: impl FnOnce(&mut Design)) { + window.focus(&self.focus, cx); + self.edit(cx, change); + } + + // The table as the schema cache lists it: in its own schema, else the default one first. + fn find(&self, table: &Table, cx: &App) -> Option<(String, String)> { + let mut loaded: Vec<(&str, &[TableInfo])> = schema::get(cx, &self.connection.id)?.loaded_tables(); + let wanted = table.qualifier.last().filter(|schema| !schema.is_empty()); + let default = self.connection.default_browse_schema(); + loaded.sort_by_key(|(schema, _)| !schema.eq_ignore_ascii_case(&default)); + loaded.into_iter().find_map(|(schema, tables)| { + if wanted.is_some_and(|wanted| !wanted.eq_ignore_ascii_case(schema)) { + return None; + } + let found = tables.iter().find(|t| t.name.eq_ignore_ascii_case(&table.name))?; + Some((schema.to_string(), found.name.clone())) + }) + } + + // Only tables not found yet ask for columns: each ask wakes the cache's observers, this one included. + fn resolve(&mut self, cx: &mut Context) { + let id = self.connection.id.clone(); + let mut unknown = vec![]; + self.found.resize(self.design.tables.len(), None); + for ix in 0..self.design.tables.len() { + if self.found[ix].is_none() { + self.found[ix] = self.find(&self.design.tables[ix], cx); + } + let Some(key) = self.found[ix].clone() else { + unknown.extend(self.design.tables[ix].qualifier.last().cloned()); + continue; + }; + let entry = schema::get(cx, &id); + if entry.is_some_and(|entry| entry.columns(&key.0, &key.1).is_some()) { + self.asked.remove(&key); + } else if !entry.is_some_and(|entry| entry.columns_loading(&key.0, &key.1)) + && self.asked.insert(key.clone()) + { + drop(schema::columns(&id, &key.0, &key.1, cx)); + } + } + schema::load_named_schemas(&id, &unknown, cx); + } + + fn columns_failed(&self, ix: usize, cx: &App) -> bool { + let Some(key) = self.found.get(ix).cloned().flatten() else { return false }; + let loading = schema::get(cx, &self.connection.id).is_some_and(|entry| entry.columns_loading(&key.0, &key.1)); + self.asked.contains(&key) && !loading + } + + fn schema_changed(&mut self, cx: &mut Context) { + self.resolve(cx); + let known = (0..self.design.tables.len()).filter(|&ix| self.columns(ix, cx).is_some()).count(); + if known == self.known { + return; + } + self.known = known; + // More columns can tell which table an unqualified name belongs to. + if self.problem.is_none() + && let Ok(mut design) = self.import(&self.source, cx) + { + design.filters = keep_unfinished(&self.design.filters, design.filters); + design.having = keep_unfinished(&self.design.having, design.having); + if design != self.design { + self.set_design(design, cx); + } + } + if self.auto { + self.places = arrange(&self.design, &self.heights(cx)); + // Fitted to cards that had yet to grow, it fits them again. + if self.fitted.is_some_and(|(zoom, _)| zoom == self.viewport.zoom) { + self.fitted = None; + } + cx.emit(BuilderEvent::Moved); + } + self.join_new_tables(cx); + cx.notify(); + } + + fn columns(&self, ix: usize, cx: &App) -> Option { + let (schema, name) = self.found.get(ix)?.as_ref()?; + schema::get(cx, &self.connection.id)?.columns(schema, name).cloned() + } + + fn cards(&self, cx: &App) -> Cards { + (0..self.design.tables.len()) + .map(|ix| { + let columns = self.columns(ix, cx)?; + let rows = self.rows(ix, &columns)?; + Some((columns, rows)) + }) + .collect() + } + + fn heights(&self, cx: &App) -> Vec { + card_heights(&self.cards(cx)) + } + + // A layout of its own follows the cards as they grow and go. + fn rearrange(&mut self, cx: &App) { + if self.auto { + self.places = arrange(&self.design, &self.heights(cx)); + } + } + + // Every column of an expanded card; else its keys and what the query uses. + fn rows(&self, ix: usize, columns: &[ColumnInfo]) -> Option { + let key = self.design.tables.get(ix)?.key().to_lowercase(); + let wanted: Vec = (0..columns.len()) + .filter(|&c| { + let column = &columns[c]; + column.is_primary + || column.is_foreign + || self.design.uses(&ColumnRef::new(ix, &column.name)) + || self.sticky.contains(&(key.clone(), column.name.to_lowercase())) + }) + .collect(); + let toggle = wanted.len() < columns.len(); + Some(match self.expanded.contains(&key) { + true => Rows { shown: (0..columns.len()).collect(), toggle }, + false => Rows { shown: wanted, toggle }, + }) + } + + // What a folded card lists stays listed until it's folded again. + fn remember_rows(&mut self, cards: &Cards) { + for (ix, card) in cards.iter().enumerate() { + let Some((columns, rows)) = card else { continue }; + let key = self.design.tables[ix].key().to_lowercase(); + if !self.expanded.contains(&key) { + self.sticky.extend(rows.shown.iter().map(|&c| (key.clone(), columns[c].name.to_lowercase()))); + } + } + } + + fn toggle_rows(&mut self, ix: usize, cx: &mut Context) { + let Some(table) = self.design.tables.get(ix) else { return }; + let key = table.key().to_lowercase(); + if !self.expanded.remove(&key) { + self.expanded.insert(key); + } else { + self.sticky.retain(|(table, _)| *table != key); + } + self.rearrange(cx); + cx.notify(); + } + + // A table from the tree or the menu, at `at` or beside the rest, joined by its foreign keys once they load. + pub(crate) fn add_table(&mut self, schema: &str, name: &str, at: Option, cx: &mut Context) { + if self.problem.is_some() { + return; + } + let elsewhere = Dialect::for_driver(&self.connection.driver).qualify_tables + && !schema.eq_ignore_ascii_case(&self.connection.default_browse_schema()); + let qualifier = if elsewhere { vec![schema.to_string()] } else { vec![] }; + let place = at.unwrap_or_else(|| beside(&self.places)); + let mut key = String::new(); + self.edit(cx, |design| { + let ix = design.add_table(qualifier, name); + key = design.tables[ix].key().to_string(); + }); + self.expanded.insert(key.to_lowercase()); + if let Some(last) = self.places.last_mut() { + *last = place; + } + self.auto &= at.is_none(); + self.rearrange(cx); + self.unjoined.push(key); + self.resolve(cx); + self.join_new_tables(cx); + cx.emit(BuilderEvent::Moved); + } + + // Joins each table added here to the others on the first foreign key between them, either way. + fn join_new_tables(&mut self, cx: &mut Context) { + let mut links = vec![]; + for key in std::mem::take(&mut self.unjoined) { + let Some(new) = self.design.tables.iter().position(|t| t.key() == key) else { continue }; + let Some(columns) = self.columns(new, cx) else { + self.unjoined.push(key); + continue; + }; + for other in (0..self.design.tables.len()).filter(|&other| other != new) { + let Some(theirs) = self.columns(other, cx) else { continue }; + let (name, other_name) = (&self.design.tables[new].name, &self.design.tables[other].name); + let out = first_key(key_pairs(&columns, other_name, &theirs)); + let pairs: Vec<(ColumnRef, ColumnRef)> = match out.is_empty() { + false => out.into_iter().map(|(a, b)| (ColumnRef::new(new, a), ColumnRef::new(other, b))).collect(), + true => first_key(key_pairs(&theirs, name, &columns)) + .into_iter() + .map(|(a, b)| (ColumnRef::new(other, a), ColumnRef::new(new, b))) + .collect(), + }; + links.extend(pairs); + } + } + if !links.is_empty() { + self.edit(cx, |design| { + for (a, b) in links { + design.link(a, b); + } + }); + } + } + + fn remove_table(&mut self, ix: usize, cx: &mut Context) { + if self.problem.is_some() || ix >= self.design.tables.len() { + return; + } + if ix < self.places.len() { + let place = self.places.remove(ix); + self.remembered.insert(self.design.tables[ix].key().to_lowercase(), place); + } + if ix < self.found.len() { + self.found.remove(ix); + } + self.edit(cx, |design| design.remove_table(ix)); + self.rearrange(cx); + } + + fn arrange(&mut self, cx: &mut Context) { + self.auto = true; + self.places = arrange(&self.design, &self.heights(cx)); + self.viewport.scroll.set_offset(point(px(0.), px(0.))); + cx.emit(BuilderEvent::Moved); + cx.notify(); + } + + fn viewport(this: &mut Self) -> &mut Viewport { + &mut this.viewport + } + + fn fit(&mut self, rem: Pixels, cx: &App) { + let (width, height) = extent(&self.places, &self.heights(cx)); + let view = self.viewport.scroll.bounds().size; + self.viewport.zoom = zoom::fit(size(rem * width, rem * height), view); + self.viewport.scroll.set_offset(point(px(0.), px(0.))); + } + + // A point in the window as one on the canvas, in rems. + fn on_canvas(&self, at: Point, rem: Pixels) -> Place { + let origin = self.viewport.in_window((0., 0.), rem); + let scale = rem * self.viewport.zoom; + Place::new(((at.x - origin.x) / scale).max(0.), ((at.y - origin.y) / scale).max(0.)) + } + + // From this database, or where databases are schemas, from another on the same server. + fn dropped_table(&mut self, drag: &TableDrag, window: &Window, cx: &mut Context) { + let by_database = self.connection.driver.capabilities().default_schema == DefaultSchema::Database; + let here = drag.connection_id == self.connection.id + || (by_database && scope::same_connection(&drag.connection_id, &self.connection.id)); + if !here { + return; + } + let at = self.on_canvas(window.mouse_position(), window.rem_size()); + let place = Place::new((at.x - CARD_W / 2.).max(0.), (at.y - HEADER_H / 2.).max(0.)); + self.add_table(&drag.schema, &drag.table, Some(place), cx); + } + + fn drag_card(&mut self, at: Point, rem: Pixels, cx: &mut Context) { + let Some(moving) = &self.moving else { return }; + let scale = rem * self.viewport.zoom; + let (dx, dy) = ((at.x - moving.from.x) / scale, (at.y - moving.from.y) / scale); + let place = Place::new((moving.place.x + dx).max(0.), (moving.place.y + dy).max(0.)); + if let Some(slot) = self.places.get_mut(moving.ix) { + *slot = place; + self.auto = false; + cx.emit(BuilderEvent::Moved); + cx.notify(); + } + } + + fn set_alias(&mut self, ix: usize, window: &mut Window, cx: &mut Context) { + let Some(table) = self.design.tables.get(ix) else { return }; + let prompt = dialogs::Prompt { + title: t_with(cx, "queryBuilder.aliasTitle", &[("table", &table.name)]), + description: None, + label: t(cx, "queryBuilder.aliasLabel"), + placeholder: t(cx, "queryBuilder.aliasPlaceholder"), + initial: table.alias.clone().unwrap_or_default(), + confirm: t(cx, "queryBuilder.aliasConfirm"), + }; + let this = cx.entity().downgrade(); + dialogs::prompt(prompt, window, cx, move |alias, _, cx| { + let _ = this.update(cx, |this, cx| { + let alias = Some(alias.trim().to_string()).filter(|alias| !alias.is_empty()); + this.edit(cx, |design| { + if let Some(table) = design.tables.get_mut(ix) { + table.alias = alias; + } + }); + }); + }); + } + + // For the tab's toolbar, after the view switch; the picker goes first so help stays above the panel's buttons. + pub(crate) fn tools(&self, picker: Option, cx: &mut Context) -> impl IntoElement + use<> { + let modifier = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl" }; + let panel = setting_bool(cx, PANEL_KEY, true); + let panel_icon = if panel { IconName::PanelRightClose } else { IconName::PanelRightOpen }; + // As the ER diagram's toolbar has them. + let tool = |id: &'static str, icon: Icon| form::filter_button(id, icon).debug_selector(move || id.into()); + h_flex() + .debug_selector(|| "qb-toolbar".into()) + .flex_1() + .min_w_0() + .gap(rems(0.615)) + .child(self.add_table_button(cx)) + .child(div().flex_1()) + .children(picker) + .child(zoom::buttons("qb", &self.viewport, true, Self::viewport, cx)) + .child(tool("qb-fit", Icon::new(Lucide::Scan)).tooltip(t(cx, "erDiagram.fitTooltip")).on_click( + cx.listener(|this, _, window, cx| { + this.fit(window.rem_size(), cx); + cx.notify(); + }), + )) + .child( + tool("qb-arrange", Icon::new(IconName::LayoutDashboard)) + .tooltip(t(cx, "queryBuilder.arrange")) + .on_click(cx.listener(|this, _, _, cx| this.arrange(cx))), + ) + .child( + tool("qb-panel-toggle", Icon::new(panel_icon)) + .tooltip(t(cx, if panel { "queryBuilder.hidePanel" } else { "queryBuilder.showPanel" })) + .on_click(cx.listener(move |_, _, _, cx| { + set_setting_bool(cx, PANEL_KEY, !panel); + cx.notify(); + })), + ) + .child(tool("qb-help", Icon::new(Lucide::CircleQuestionMark)).ghost().tooltip(t_with( + cx, + "queryBuilder.hint", + &[("modifier", modifier)], + ))) + } + + // The connection's tables: the default schema's in the menu, each other loaded schema's in its own. + fn add_table_button(&self, cx: &mut Context) -> impl IntoElement + use<> { + let this = cx.entity().downgrade(); + let (id, default) = (self.connection.id.clone(), self.connection.default_browse_schema()); + Button::new("qb-add-table") + .debug_selector(|| "qb-add-table".into()) + .tool(Icon::new(IconName::Plus), ICON_XS, t(cx, "queryBuilder.addTable")) + .disabled(self.problem.is_some()) + .dropdown_menu(move |mut menu, window, cx| { + let loaded: Vec<(String, Vec)> = schema::get(cx, &id) + .map(|entry| entry.loaded_tables()) + .unwrap_or_default() + .into_iter() + .map(|(schema, tables)| (schema.to_string(), tables.iter().map(|t| t.name.clone()).collect())) + .filter(|(_, tables): &(String, Vec)| !tables.is_empty()) + .collect(); + if loaded.is_empty() { + return menu.item(PopupMenuItem::new(t(cx, "queryBuilder.noTables")).disabled(true)); + } + let (own, others): (Vec<_>, Vec<_>) = + loaded.into_iter().partition(|(schema, _)| schema.eq_ignore_ascii_case(&default)); + for (schema, tables) in own { + for table in tables { + menu = menu.item(table_item(this.clone(), schema.clone(), table)); + } + } + for (schema, tables) in others { + let this = this.clone(); + menu = menu.submenu(schema.clone(), window, cx, move |menu, _, _| { + let items = tables.iter().map(|table| table_item(this.clone(), schema.clone(), table.clone())); + items.fold(menu, PopupMenu::item).scrollable(true) + }); + } + menu.scrollable(true) + }) + } + + // SQL the canvas can't show greys it out until the SQL is fixed. + fn problem_bar(&self, cx: &mut Context) -> Option> { + let problem = self.problem.as_ref()?; + Some( + form::warning_bar(problem_text(problem, &self.source, cx), cx) + .debug_selector(|| "qb-problem".into()) + .child( + Button::new("qb-problem-edit") + .debug_selector(|| "qb-problem-edit".into()) + .small() + .label(t(cx, "queryBuilder.editSql")) + .on_click(cx.listener(|_, _, _, cx| cx.emit(BuilderEvent::EditSql))), + ), + ) + } + + // Each join's lines: column to column, or header to header for a condition with no pair. + fn curves(&self, cards: &Cards) -> Vec<(usize, Curve)> { + let mut out = vec![]; + for (ix, table) in self.design.tables.iter().enumerate() { + let Some(join) = &table.join else { continue }; + let end = |column: &ColumnRef| Some((*self.places.get(column.table)?, row_of(column, cards))); + for pair in &join.on { + if let (Some(a), Some(b)) = (end(&pair.left), end(&pair.right)) { + out.push((ix, curve(a, b))); + } + } + let before = ix.checked_sub(1).and_then(|prev| self.places.get(prev).copied()); + if let (Some(prev), Some(&place)) = (before, self.places.get(ix)) { + for column in &join.using { + let row = |table: usize| row_of(&ColumnRef::new(table, column), cards); + out.push((ix, curve((place, row(ix)), (prev, row(ix - 1))))); + } + if join.on.is_empty() && join.using.is_empty() { + out.push((ix, curve((place, None), (prev, None)))); + } + } + } + out + } + + fn card(&self, ix: usize, cards: &Cards, cx: &mut Context) -> AnyElement { + let theme = cx.theme().clone(); + let table = &self.design.tables[ix]; + let place = self.places.get(ix).copied().unwrap_or_default(); + let dialect = self.connection.driver.dialect(); + let failed = self.columns_failed(ix, cx); + let loading = !failed + && (self.found.get(ix).is_some_and(Option::is_some) + || schema::get(cx, &self.connection.id) + .is_none_or(|entry| entry.loading() || entry.schemas().is_none())); + let note = match (loading, failed) { + (true, _) => "queryBuilder.loading", + (false, true) => "queryBuilder.columnsFailed", + (false, false) => "queryBuilder.unknownTable", + }; + let card = cards.get(ix).and_then(Option::as_ref); + let rows: Vec = match card { + Some((columns, listed)) => { + let mut rows: Vec = + listed.shown.iter().map(|&c| self.column_row(ix, c, &columns[c], dialect, cx)).collect(); + if listed.toggle { + rows.push(self.more_row(ix, columns.len() - listed.shown.len(), cx)); + } + rows + } + _ => vec![ + card_row() + .debug_selector(move || format!("qb-note-{ix}")) + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .when(loading, |el| el.child(Spinner::new(ICON_XS))) + .child(t(cx, note)) + .into_any_element(), + ], + }; + let height = card_height(card.map_or(1, |(_, listed)| listed.lines())); + let target = self.linking.as_ref().is_some_and(|(from, _)| from.table != ix); + let alias = table.alias.clone().map(|alias| { + div() + .flex_none() + .max_w(rems(4.615)) + .truncate() + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .child(alias) + }); + let header = h_flex() + .id(("qb-header", ix)) + .debug_selector(move || format!("qb-header-{ix}")) + .h(rems(HEADER_H)) + .flex_none() + .px(rems(0.615)) + .gap(rems(0.462)) + .bg(theme.secondary) + .border_b_1() + .border_color(theme.border) + .cursor_grab() + .child(Icon::new(Lucide::Table2).size(ICON_XS).text_color(theme.muted_foreground)) + .child(div().flex_1().min_w_0().truncate().font_semibold().child(table.name.clone())) + .children(alias) + .child( + Button::new(("qb-remove", ix)) + .debug_selector(move || format!("qb-remove-{ix}")) + .ghost() + .tool_icon(Icon::new(Lucide::X), ICON_XS) + .tooltip(t(cx, "queryBuilder.removeTable")) + .on_click(cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + window.focus(&this.focus, cx); + this.remove_table(ix, cx); + })), + ) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, _| { + if let Some(&place) = this.places.get(ix) { + this.moving = Some(Moving { ix, from: event.position, place }); + } + }), + ) + .on_drag(MoveDrag, |drag, _, _, cx| cx.new(|_| drag.clone())) + .context_menu(self.table_menu(ix, cx)); + v_flex() + .id(("qb-card", ix)) + .debug_selector(move || format!("qb-card-{ix}")) + .absolute() + .left(rems(place.x)) + .top(rems(place.y)) + .w(rems(CARD_W)) + .h(rems(height)) + .overflow_hidden() + .rounded(RADIUS) + .border_1() + .border_color(if target { theme.primary.opacity(0.5) } else { theme.border }) + .bg(theme::opaque(theme.background)) + .text_size(TEXT_SM) + .child(header) + .children(rows) + .into_any_element() + } + + fn table_menu( + &self, + ix: usize, + cx: &Context, + ) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { + let this = cx.entity().downgrade(); + move |menu, _, cx| { + let (alias, remove) = (this.clone(), this.clone()); + let all = on_edit(&this, move |design| design.add_item(Item::All(Some(ix)))); + menu.item(PopupMenuItem::new(t(cx, "queryBuilder.setAlias")).on_click(move |_, window, cx| { + let _ = alias.update(cx, |this, cx| this.set_alias(ix, window, cx)); + })) + .item(PopupMenuItem::new(t(cx, "queryBuilder.allColumns")).on_click(all)) + .separator() + .item(PopupMenuItem::new(t(cx, "queryBuilder.removeTable")).on_click(move |_, _, cx| { + let _ = remove.update(cx, |this, cx| this.remove_table(ix, cx)); + })) + } + } + + // "+N columns" on a folded card, "Show fewer" on an unfolded one. + fn more_row(&self, ix: usize, hidden: usize, cx: &mut Context) -> AnyElement { + let (icon, label) = match hidden { + 0 => (IconName::ChevronUp, t(cx, "queryBuilder.fewerColumns")), + n => (IconName::ChevronDown, crate::i18n::t_count(cx, "queryBuilder.moreColumns", n as i64, &[])), + }; + let theme = cx.theme(); + let hover = theme.accent; + card_row() + .id(("qb-more", ix)) + .debug_selector(move || format!("qb-more-{ix}")) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .child(Icon::new(icon).size(ICON_XS)) + .child(label) + .on_click(cx.listener(move |this, _, _, cx| this.toggle_rows(ix, cx))) + .into_any_element() + } + + // A click picks the column, a drag onto another table's column joins them, and the menu has the rest. + fn column_row( + &self, + ix: usize, + row: usize, + column: &ColumnInfo, + dialect: Option, + cx: &mut Context, + ) -> AnyElement { + let target = ColumnRef::new(ix, &column.name); + let picked = self.design.picked(&target); + let aggregate = self.design.aggregate_of(&target); + let sort = self.design.sort_of(&target); + let filtered = self.design.filters_on(&target); + let label: SharedString = self.shown(&Operand::Column(target.clone())).into(); + let theme = cx.theme(); + let key = match (column.is_primary, column.is_foreign) { + (true, _) => Some(Icon::new(Lucide::KeyRound).size(ICON_XS).text_color(theme.warning)), + (false, true) => Some(Icon::new(Lucide::Link).size(ICON_XS).text_color(theme.primary)), + _ => None, + }; + let mark = form::check_mark(picked.then_some(theme.primary), cx); + let badge = aggregate.map(|func| form::badge(func.name(), theme.primary).flex_none()); + let arrow = sort.map(|desc| { + let arrow = if desc { IconName::ArrowDown } else { IconName::ArrowUp }; + Icon::new(arrow).size(ICON_XS).text_color(theme.primary) + }); + let hover = theme.accent; + let (toggled, dropped) = (target.clone(), target.clone()); + card_row() + .id(("qb-column", ix * 10_000 + row)) + .debug_selector(move || format!("qb-column-{ix}-{row}")) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .drag_over::(|style, _, _, cx| style.bg(cx.theme().primary.opacity(0.2))) + .child(mark) + .child(div().flex_1().min_w_0().truncate().child(column.name.clone())) + .children(badge) + .children(arrow) + .when(filtered, |el| el.child(Icon::new(Lucide::Funnel).size(ICON_XS).text_color(theme.primary))) + .children(key) + .child( + div() + .flex_none() + .max_w(rems(5.385)) + .truncate() + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .child(display_type(dialect, &column.data_type)), + ) + .on_click(cx.listener(move |this, _, _, cx| { + let target = toggled.clone(); + this.edit(cx, |design| design.toggle_column(target)); + })) + .on_drag(LinkDrag(target.clone(), label), |drag, _, _, cx| cx.new(|_| drag.clone())) + .on_drop(cx.listener(move |this, drag: &LinkDrag, _, cx| { + this.linking = None; + let (from, to) = (drag.0.clone(), dropped.clone()); + this.edit(cx, |design| { + design.link(from, to); + }); + cx.notify(); + })) + .context_menu(self.column_menu(target, cx)) + .into_any_element() + } + + fn column_menu( + &self, + target: ColumnRef, + cx: &Context, + ) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { + let this = cx.entity().downgrade(); + let (current, sort) = (self.design.aggregate_of(&target), self.design.sort_of(&target)); + move |menu, window, cx| { + let (weak, column) = (this.clone(), target.clone()); + let menu = menu.submenu(t(cx, "queryBuilder.aggregate"), window, cx, move |menu, _, cx| { + let aggregate = |func: Option| { + let column = column.clone(); + on_edit(&weak, move |design| aggregate_column(design, &column, func)) + }; + let none = PopupMenuItem::new(t(cx, "queryBuilder.noAggregate")).checked(current.is_none()); + Aggregate::ALL.into_iter().fold(menu.item(none.on_click(aggregate(None))), |menu, func| { + let item = PopupMenuItem::new(func.name()).checked(current == Some(func)); + menu.item(item.on_click(aggregate(Some(func)))) + }) + }); + let sorted = |desc: Option| { + let target = target.clone(); + on_edit(&this, move |design| design.sort_column(target.clone(), desc)) + }; + let filter = { + let target = target.clone(); + on_edit(&this, move |design| { + let left = Operand::Column(target.clone()); + design.filters.push(Condition::Compare { left, op: Op::Eq, value: String::new() }) + }) + }; + let sorts = [ + (Some(false), "queryBuilder.sortAsc"), + (Some(true), "queryBuilder.sortDesc"), + (None, "queryBuilder.noSort"), + ]; + sorts + .into_iter() + .fold(menu.separator(), |menu, (desc, key)| { + menu.item(PopupMenuItem::new(t(cx, key)).checked(sort == desc).on_click(sorted(desc))) + }) + .separator() + .item(PopupMenuItem::new(t(cx, "queryBuilder.filterColumn")).on_click(filter)) + } + } + + // The join's kind on its first line, with a menu to change it or drop the join. + fn join_label(&self, table: usize, at: (f32, f32), cx: &mut Context) -> Option { + let kind = self.design.tables.get(table)?.join.as_ref()?.kind; + let this = cx.entity().downgrade(); + let offered = JoinKind::offered(self.dialect()); + let button = Button::new(("qb-join", table)) + .debug_selector(move || format!("qb-join-{table}")) + .xsmall() + .bg(theme::opaque(cx.theme().background)) + .child(div().text_size(TEXT_2XS).font_semibold().child(kind.keyword())) + .dropdown_menu(move |menu, _, cx| { + let menu = offered.iter().fold(menu, |menu, &choice| { + let label = t(cx, &format!("queryBuilder.join.{}", choice.keyword().to_lowercase())); + let pick = on_edit(&this, move |design| design.set_join_kind(table, choice)); + menu.item(PopupMenuItem::new(label).checked(choice == kind).on_click(pick)) + }); + let remove = on_edit(&this, move |design| { + if let Some(table) = design.tables.get_mut(table) { + table.join = None; + } + }); + menu.separator().item(PopupMenuItem::new(t(cx, "queryBuilder.removeJoin")).on_click(remove)) + }); + // Centred on the curve, whatever the label's width. + let (w, h) = (6.154, 1.538); + Some( + h_flex() + .absolute() + .left(rems(at.0 - w / 2.)) + .top(rems(at.1 - h / 2.)) + .w(rems(w)) + .h(rems(h)) + .justify_center() + .child(button) + .into_any_element(), + ) + } + + fn canvas_area(&mut self, cards: &Cards, window: &mut Window, cx: &mut Context) -> impl IntoElement + use<> { + let theme = cx.theme().clone(); + let rem = window.rem_size(); + let view = self.viewport.scroll.bounds().size; + let (width, height) = extent(&self.places, &card_heights(cards)); + let refit = self.fitted.is_none_or(|(zoom, seen)| zoom == self.viewport.zoom && seen != view); + if refit && !self.places.is_empty() { + match view.width > px(0.) && view.height > px(0.) { + true => { + self.viewport.zoom = zoom::fit(size(rem * width, rem * height), view).clamp(FIT_MIN, 1.); + if self.fitted.is_none() { + self.viewport.scroll.set_offset(point(px(0.), px(0.))); + } + self.fitted = Some((self.viewport.zoom, view)); + self.measuring = false; + } + // Once, for the first layout; a canvas squeezed to nothing waits for room instead. + false if !self.measuring => { + self.measuring = true; + window.request_animation_frame(); + } + false => {} + } + } + // Never smaller than the view, so the cards stay put as it grows. + let scale = rem * self.viewport.zoom; + let (width, height) = (width.max(view.width / scale), height.max(view.height / scale)); + self.viewport.resize(width, height, false); + if !cx.has_active_drag() { + self.linking = None; + } + let curves = self.curves(cards); + let mut labelled = HashSet::new(); + let labels: Vec = curves + .iter() + .filter(|(table, _)| labelled.insert(*table)) + .filter_map(|(table, curve)| self.join_label(*table, curve.middle(), cx)) + .collect(); + let pending = self.linking.as_ref().and_then(|(from, at)| { + let place = *self.places.get(from.table)?; + Some((curve((place, row_of(from, cards)), (place, None)).from, self.on_canvas(*at, rem))) + }); + let (edge, accent) = (theme.muted_foreground.opacity(0.6), theme.primary); + let boxes: Vec = (0..self.design.tables.len()).map(|ix| self.card(ix, cards, cx)).collect(); + let content = div() + .relative() + .flex_none() + .w(rems(width)) + .h(rems(height)) + .child( + canvas( + |_, _, _| {}, + move |bounds, _, window, _| paint_curves(&curves, pending, edge, accent, bounds, window), + ) + .absolute() + .inset_0(), + ) + .children(boxes) + .children(labels); + let area = zoom::area("qb-canvas", &self.viewport, Self::viewport, cx) + .debug_selector(|| "qb-canvas".into()) + .drag_over::(|style, _, _, cx| style.bg(cx.theme().primary.opacity(0.06))) + .on_drop(cx.listener(|this, drag: &TableDrag, window, cx| this.dropped_table(drag, window, cx))) + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, window, cx| { + this.drag_card(event.event.position, window.rem_size(), cx) + })) + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { + this.linking = Some((event.drag(cx).0.clone(), event.event.position)); + cx.notify(); + })) + .child(zoom::zoomed(self.viewport.zoom, content)); + let (scroll, zoomed, dot) = (self.viewport.scroll.clone(), self.viewport.zoom, theme.border); + let dots = canvas( + |_, _, _| {}, + move |bounds, _, window, _| er_diagram::paint_dots(bounds, scroll.offset(), zoomed, dot, window), + ) + .absolute() + .inset_0(); + let empty = self.design.tables.is_empty() && self.problem.is_none(); + div() + .relative() + .flex_1() + .min_w_0() + .h_full() + .child(dots) + .child(area) + .child(zoom::wheel_zoom(Self::viewport, cx)) + .when(empty, |el| { + el.child( + div() + .debug_selector(|| "qb-empty".into()) + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .child(form::empty_state(Some(Icon::new(Lucide::Blocks)), t(cx, "queryBuilder.empty"), cx)), + ) + }) + .hover_scrollbar(&self.viewport.scroll, ScrollbarAxis::Both) + } +} + +pub(crate) fn problem_text(problem: &ImportError, sql: &str, cx: &App) -> SharedString { + match problem { + ImportError::NotQuery => t(cx, "queryBuilder.notQuery"), + ImportError::Unsupported(what) => t_with(cx, "queryBuilder.unsupported", &[("what", what)]), + ImportError::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, "queryBuilder.syntaxEnd"), + false => t_with(cx, "queryBuilder.syntax", &[("near", &near)]), + } + } + } +} + +fn table_item(this: WeakEntity, schema: String, table: String) -> PopupMenuItem { + PopupMenuItem::new(table.clone()).icon(Icon::new(Lucide::Table2)).on_click(move |_, _, cx| { + let _ = this.update(cx, |this, cx| this.add_table(&schema, &table, None, cx)); + }) +} + +// Picks the column if it isn't, then sets or clears its aggregate. +fn aggregate_column(design: &mut Design, target: &ColumnRef, func: Option) { + if !design.picked(target) { + design.toggle_column(target.clone()); + } + if let Some(item) = design.items.iter().position(|item| item.value().is_some_and(|value| value.reads(target))) { + design.set_aggregate(item, func); + } +} + +// The joins' lines, and one from a dragged column to the pointer. +fn paint_curves( + curves: &[(usize, Curve)], + pending: Option<((f32, f32), Place)>, + color: Hsla, + accent: 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 (_, curve) in curves { + let mut line = PathBuilder::stroke(px(1.5)); + line.move_to(at(curve.from)); + line.cubic_bezier_to(at(curve.to), at(curve.controls.0), at(curve.controls.1)); + if let Ok(line) = line.build() { + window.paint_path(line, color); + } + } + if let Some((from, to)) = pending { + let mut line = PathBuilder::stroke(px(2.)); + line.move_to(at(from)); + line.line_to(at((to.x, to.y))); + if let Ok(line) = line.build() { + window.paint_path(line, accent); + } + } +} + +// Each foreign key of `from`'s columns that points at `to`: its name, the column and the one it references. +fn key_pairs(from: &[ColumnInfo], to: &str, theirs: &[ColumnInfo]) -> Vec<(String, String, String)> { + let primary = theirs.iter().find(|c| c.is_primary).map(|c| c.name.clone()); + from.iter() + .filter(|c| c.is_foreign && c.foreign_table.eq_ignore_ascii_case(to)) + .filter_map(|c| { + let target = match c.foreign_column.is_empty() { + true => primary.clone()?, + false => c.foreign_column.clone(), + }; + Some((c.foreign_key.clone(), c.name.clone(), target)) + }) + .collect() +} + +// Rows still being filled in, which the SQL leaves out, keep their places. +fn keep_unfinished(was: &[Condition], read: Vec) -> Vec { + let mut read = read.into_iter(); + let mut out: Vec = was + .iter() + .filter_map(|condition| if condition.complete() { read.next() } else { Some(condition.clone()) }) + .collect(); + out.extend(read); + out +} + +// Two keys to one table, like created_by and updated_by, are two joins. +fn first_key(pairs: Vec<(String, String, String)>) -> Vec<(String, String)> { + let Some(first) = pairs.first().map(|(key, ..)| key.clone()) else { return vec![] }; + pairs.into_iter().filter(|(key, ..)| *key == first).map(|(_, column, target)| (column, target)).collect() +} + +impl Render for QueryBuilder { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + let blocked = self.problem.is_some(); + let cards = self.cards(cx); + self.remember_rows(&cards); + let canvas = self.canvas_area(&cards, window, cx); + let panel = setting_bool(cx, PANEL_KEY, true).then(|| self.panel(window, cx)); + v_flex() + .debug_selector(|| "query-builder".into()) + .key_context("QueryEditor QueryBuilder") + .track_focus(&self.focus) + .size_full() + .bg(theme.background) + .children(self.problem_bar(cx)) + .child( + h_flex() + .relative() + .flex_1() + .min_h_0() + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, window, cx| { + panel::drag_width(event.bounds, event.event.position.x, window.rem_size(), cx); + this.width_save = cx.spawn(async move |_, cx| { + cx.background_executor().timer(panel::WIDTH_SAVE).await; + cx.update(panel::keep_width); + }); + cx.notify(); + })) + .child(canvas) + .children(panel) + .when(blocked, |el| { + el.opacity(DIMMED) + .child(div().debug_selector(|| "qb-blocked".into()).absolute().inset_0().occlude()) + }), + ) + } +} diff --git a/crates/barsql-ui/src/query_builder/geometry.rs b/crates/barsql-ui/src/query_builder/geometry.rs new file mode 100644 index 0000000..2629e38 --- /dev/null +++ b/crates/barsql-ui/src/query_builder/geometry.rs @@ -0,0 +1,191 @@ +use barsql_sql::design::Design; + +pub use crate::er_diagram::layout::{BOX_W as CARD_W, HEADER_H, MARGIN, ROW_H, Spot}; +use crate::er_diagram::layout::{GAP_Y, route}; + +// The ER diagram's sizes, with columns of cards closer together. +const GAP_X: f32 = 4.615; + +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Place { + pub x: f32, + pub y: f32, +} + +impl Place { + pub fn new(x: f32, y: f32) -> Self { + Self { x, y } + } +} + +// A card shows a row even while its columns load. +pub fn card_height(rows: usize) -> f32 { + HEADER_H + ROW_H * rows.max(1) as f32 +} + +pub struct Curve { + pub from: Spot, + pub to: Spot, + pub controls: (Spot, Spot), +} + +impl Curve { + // The middle of the curve, where its join's label sits. + pub fn middle(&self) -> Spot { + let (a, b, c, d) = (self.from, self.controls.0, self.controls.1, self.to); + ((a.0 + 3. * b.0 + 3. * c.0 + d.0) / 8., (a.1 + 3. * b.1 + 3. * c.1 + d.1) / 8.) + } +} + +// Rows meet a line on the column's row, or on the header for one the card doesn't list. +pub fn curve(from: (Place, Option), to: (Place, Option)) -> Curve { + let ((a, a_row), (b, b_row)) = (from, to); + let (from, to, controls, _) = route(((a.x, a.y), a_row), ((b.x, b.y), b_row)); + Curve { from, to, controls } +} + +// Left to right by how many joins a table is from the first of its group; a column stacks only as high as the +// tallest card, as the canvas is wider than tall. +pub fn arrange(design: &Design, heights: &[f32]) -> Vec { + let count = design.tables.len(); + let mut near = vec![vec![]; count]; + let mut link = |a: usize, b: usize| { + if a != b && a < count && b < count { + near[a].push(b); + near[b].push(a); + } + }; + for (ix, table) in design.tables.iter().enumerate() { + let Some(join) = &table.join else { continue }; + for pair in &join.on { + link(pair.left.table, pair.right.table); + } + if !join.using.is_empty() && ix > 0 { + link(ix, ix - 1); + } + } + let mut depth = vec![usize::MAX; count]; + for root in 0..count { + if depth[root] != usize::MAX { + continue; + } + depth[root] = 0; + let mut queue = std::collections::VecDeque::from([root]); + while let Some(at) = queue.pop_front() { + for &next in &near[at] { + if depth[next] == usize::MAX { + depth[next] = depth[at] + 1; + queue.push_back(next); + } + } + } + } + let height = |ix: usize| heights.get(ix).copied().unwrap_or(HEADER_H); + let limit = (0..count).map(height).fold(0f32, f32::max); + let levels = depth.iter().copied().max().map_or(0, |d| d + 1); + let mut columns: Vec>> = vec![vec![]; levels]; + for (level, stacks) in columns.iter_mut().enumerate() { + let mut top = MARGIN; + for ix in (0..count).filter(|&ix| depth[ix] == level) { + match stacks.last_mut().filter(|_| top + height(ix) <= MARGIN + limit) { + Some(stack) => stack.push(ix), + None => { + stacks.push(vec![ix]); + top = MARGIN; + } + } + top += height(ix) + GAP_Y; + } + } + // The first tables' neighbours go either side of them, so no line runs behind a card. + let mut order: Vec> = vec![]; + let mut levels = columns.into_iter(); + let (first, near) = (levels.next().unwrap_or_default(), levels.next().unwrap_or_default()); + let (right, left): (Vec<_>, Vec<_>) = near.into_iter().enumerate().partition(|(n, _)| n % 2 == 0); + order.extend(left.into_iter().rev().map(|(_, column)| column)); + order.extend(first); + order.extend(right.into_iter().map(|(_, column)| column)); + order.extend(levels.flatten()); + let mut places = vec![Place::default(); count]; + for (column, stack) in order.iter().enumerate() { + let mut top = MARGIN; + for &ix in stack { + places[ix] = Place::new(MARGIN + column as f32 * (CARD_W + GAP_X), top); + top += height(ix) + GAP_Y; + } + } + places +} + +// Right of everything already there, at the top. +pub fn beside(places: &[Place]) -> Place { + match places.iter().map(|place| place.x).reduce(f32::max) { + Some(right) => Place::new(right + CARD_W + GAP_X, MARGIN), + None => Place::new(MARGIN, MARGIN), + } +} + +// How far the cards reach, with a margin past them. +pub fn extent(places: &[Place], heights: &[f32]) -> (f32, f32) { + places.iter().zip(heights).fold((0f32, 0f32), |(w, h), (place, height)| { + (w.max(place.x + CARD_W + MARGIN), h.max(place.y + height + MARGIN)) + }) +} + +#[cfg(test)] +mod tests { + use barsql_sql::design::{ColumnRef, Design}; + + use super::*; + + #[test] + fn joined_tables_go_a_column_further_and_the_rest_stack() { + let mut design = Design::default(); + for name in ["users", "orders", "payments", "notes"] { + design.add_table(vec![], name); + } + design.link(ColumnRef::new(1, "user_id"), ColumnRef::new(0, "id")); + design.link(ColumnRef::new(2, "order_id"), ColumnRef::new(1, "id")); + let step = CARD_W + GAP_X; + let places = arrange(&design, &[5., 12., 4., 3.]); + assert_eq!(places[0], Place::new(MARGIN, MARGIN)); + assert_eq!(places[3], Place::new(MARGIN, MARGIN + 5. + GAP_Y), "an unjoined table starts its own group"); + assert_eq!(places[1].x, MARGIN + step, "a join further"); + assert_eq!(places[2].x, MARGIN + 2. * step); + let places = arrange(&design, &[12., 6., 4., 3.]); + assert_eq!(places[3], Place::new(MARGIN + step, MARGIN), "too tall to stack, so it goes beside"); + } + + // A table joined to two tall ones has one on each side. + #[test] + fn a_tables_neighbours_go_either_side_of_it() { + let mut design = Design::default(); + for name in ["posts", "users", "categories"] { + design.add_table(vec![], name); + } + design.link(ColumnRef::new(1, "id"), ColumnRef::new(0, "author_id")); + design.link(ColumnRef::new(2, "id"), ColumnRef::new(0, "category_id")); + let places = arrange(&design, &[10., 12., 6.]); + let step = CARD_W + GAP_X; + assert_eq!(places.iter().map(|p| p.x).collect::>(), [MARGIN + step, MARGIN + 2. * step, MARGIN]); + } + + #[test] + fn curves_leave_from_the_sides_that_face_each_other() { + let (left, right) = (Place::new(0., 0.), Place::new(30., 10.)); + let back = curve((right, Some(0)), (left, None)); + assert_eq!(back.from, (30., 10. + HEADER_H + ROW_H / 2.)); + assert_eq!(back.to, (CARD_W, HEADER_H / 2.)); + let stacked = curve((left, Some(1)), (Place::new(2., 20.), Some(0))); + assert!(stacked.controls.0.0 > stacked.from.0 && stacked.controls.1.0 > stacked.to.0, "loops out on the right"); + let middle = super::curve((left, None), (right, None)).middle(); + assert!(middle.0 > CARD_W && middle.0 < 30.); + } + + #[test] + fn new_cards_go_right_of_the_rest() { + assert_eq!(beside(&[]), Place::new(MARGIN, MARGIN)); + assert_eq!(beside(&[Place::new(4., 9.), Place::new(10., 2.)]), Place::new(10. + CARD_W + GAP_X, MARGIN)); + assert_eq!(extent(&[Place::new(1., 2.)], &[3.]), (1. + CARD_W + MARGIN, 5. + MARGIN)); + } +} diff --git a/crates/barsql-ui/src/query_builder/panel.rs b/crates/barsql-ui/src/query_builder/panel.rs new file mode 100644 index 0000000..3e14f8e --- /dev/null +++ b/crates/barsql-ui/src/query_builder/panel.rs @@ -0,0 +1,867 @@ +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; +use std::time::Duration; + +use barsql_sql::design::{Aggregate, ColumnRef, Condition, Design, Item, Op, Operand, Sort, shift}; +use gpui_kit::assets::IconName as Lucide; +use gpui_kit::base::{HandleEdge, resize_handle}; +use gpui_kit::component::button::{Button, ButtonVariants}; +use gpui_kit::component::input::{InputEvent, InputState}; +use gpui_kit::component::menu::{DropdownMenu, PopupMenu, PopupMenuItem}; +use gpui_kit::component::scroll::ScrollbarAxis; +use gpui_kit::component::tooltip::Tooltip; +use gpui_kit::component::{ActiveTheme, Icon, IconName, InteractiveElementExt as _, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +use super::{QueryBuilder, on_edit}; +use crate::form::{self, ToolButton as _}; +use crate::i18n::t; +use crate::scrollbars::HoverScrollbar as _; +use crate::state::{set_setting, setting}; +use crate::tokens::{ICON_XS, RADIUS, STRIP_PAD, TEXT_XS}; +use crate::{dialogs, list_nav}; + +// The panel's width in rems (default, least, most), the same in every builder. +const WIDTHS: (f32, f32, f32) = (27.692, 18.462, 46.154); +const WIDTH_KEY: &str = "barsql-builder-panel-w"; +pub(super) const WIDTH_SAVE: Duration = Duration::from_millis(500); +// A drag leaves the canvas at least this many rems. +const CANVAS_LEAST: f32 = 15.385; +const CAPTION_H: f32 = 2.154; +// The panel's padding; a row keeps RING of it inside its drop ring. +const INSET: f32 = 0.923; +const RING: f32 = 0.462; +// Add and remove buttons centre this far from the right, under the toolbar's help button. +const BUTTON_MID: f32 = STRIP_PAD.0 + form::FIELD_REM / 2.; + +struct PanelWidth(f32); + +impl Global for PanelWidth {} + +fn width(cx: &App) -> f32 { + let stored = || setting(cx, WIDTH_KEY).and_then(|value| value.parse().ok()); + cx.try_global::().map(|width| width.0).or_else(stored).unwrap_or(WIDTHS.0).clamp(WIDTHS.1, WIDTHS.2) +} + +#[derive(Clone)] +pub(super) struct PanelDrag; + +impl Render for PanelDrag { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Empty + } +} + +// The panel's left edge follows the pointer across `bounds`, the canvas's and the panel's. +pub(super) fn drag_width(bounds: Bounds, x: Pixels, rem: Pixels, cx: &mut App) { + let most = (bounds.size.width / rem - CANVAS_LEAST).clamp(WIDTHS.1, WIDTHS.2); + cx.set_global(PanelWidth(((bounds.right() - x) / rem).clamp(WIDTHS.1, most))); +} + +pub(super) fn keep_width(cx: &mut App) { + set_setting(cx, WIDTH_KEY, &format!("{:.3}", width(cx))); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum Clause { + Where, + Having, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum Field { + Alias(usize), + Value(Clause, usize), + Raw(Clause, usize), + Limit, + Offset, +} + +#[derive(Default)] +pub(super) struct Panel { + inputs: HashMap, Subscription)>, + used: HashSet, + // A row just added, whose field takes the keys once it's drawn. + focus_next: Option, + scroll: ScrollHandle, +} + +// A picked item, a filter or a sort, dragged to another place in its list. +#[derive(Clone)] +struct ItemDrag(usize, SharedString); + +impl Render for ItemDrag { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + super::chip(self.1.clone(), Lucide::Columns3, cx) + } +} + +#[derive(Clone)] +struct ConditionDrag(Clause, usize, SharedString); + +impl Render for ConditionDrag { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + super::chip(self.2.clone(), Lucide::Funnel, cx) + } +} + +#[derive(Clone)] +struct SortDrag(usize, SharedString); + +impl Render for SortDrag { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + super::chip(self.1.clone(), Lucide::ArrowDownAZ, cx) + } +} + +fn grip(id: impl Into, drag: T, cx: &App) -> Stateful
{ + div() + .id(id) + .flex_none() + .cursor_grab() + .child(Icon::new(IconName::EllipsisVertical).size(ICON_XS).text_color(cx.theme().muted_foreground)) + .on_drag(drag, |drag, _, _, cx| cx.new(|_| drag.clone())) +} + +fn remove_at(list: &mut Vec, ix: usize) { + if ix < list.len() { + list.remove(ix); + } +} + +fn list(design: &mut Design, clause: Clause) -> &mut Vec { + match clause { + Clause::Where => &mut design.filters, + Clause::Having => &mut design.having, + } +} + +fn conditions(design: &Design, clause: Clause) -> &Vec { + match clause { + Clause::Where => &design.filters, + Clause::Having => &design.having, + } +} + +// The columns a menu offers: each table by its name in the query, and its columns once they've loaded. +type Choices = Rc>)>>; +type Pick = Rc; + +// Read when the menu opens, not on every frame. +fn choices_of(this: &WeakEntity, cx: &App) -> Choices { + this.upgrade().map(|this| this.read(cx).choices(cx)).unwrap_or_default() +} + +fn aggregates_of(this: &WeakEntity, cx: &App) -> Vec<(SharedString, Operand)> { + this.upgrade().map(|this| this.read(cx).aggregate_choices()).unwrap_or_default() +} + +fn operands_menu(menu: PopupMenu, operands: &[(SharedString, Operand)], pick: &Pick) -> PopupMenu { + operands.iter().fold(menu, |menu, (label, operand)| { + let (pick, operand) = (pick.clone(), operand.clone()); + menu.item(PopupMenuItem::new(label.clone()).on_click(move |_, _, cx| pick(operand.clone(), cx))) + }) +} + +// A caption with its add button, a hint while there are no rows, then the rows. +fn section(title: SharedString, add: AnyElement, empty: SharedString, rows: Vec, cx: &App) -> Div { + v_flex() + .child(caption(title, Some(add), cx)) + .when(rows.is_empty(), |el| el.child(hint(empty, cx))) + .child(v_flex().px(rems(INSET - RING)).gap(rems(0.154)).children(rows)) +} + +// A row that reorders by its grip. +fn list_row() -> Div { + h_flex().h(rems(form::FIELD_REM)).px(rems(RING)).gap(rems(0.385)).rounded(RADIUS) +} + +fn caption(text: SharedString, add: Option, cx: &App) -> Div { + h_flex() + .flex_none() + .h(rems(CAPTION_H)) + .gap(rems(0.615)) + .justify_between() + .px(rems(INSET)) + .child(form::caption(text, cx)) + .children(add) +} + +fn hint(text: SharedString, cx: &App) -> Div { + div().px(rems(INSET)).pb(rems(0.308)).text_size(TEXT_XS).text_color(cx.theme().muted_foreground).child(text) +} + +fn remove_button(id: String, cx: &App) -> Button { + Button::new(SharedString::from(id.clone())) + .debug_selector(move || id) + .ghost() + .tool_icon(Icon::new(Lucide::X), ICON_XS) + .tooltip(t(cx, "queryBuilder.remove")) +} + +// A row's or caption's last button, centred at BUTTON_MID. +fn end_button(button: Button) -> Button { + button.w(rems(2. * (BUTTON_MID - INSET))).px_0() +} + +fn add_button(id: &'static str, cx: &App) -> Button { + end_button( + Button::new(id) + .debug_selector(move || id.into()) + .ghost() + .tool_icon(Icon::new(IconName::Plus), ICON_XS) + .tooltip(t(cx, "queryBuilder.add")), + ) +} + +// form::select_small's frame, with a label cut short to fit its row. +fn row_select(id: impl Into, label: SharedString, cx: &App) -> Button { + let theme = cx.theme(); + Button::new(id).outline().h(rems(form::TOOL_REM)).pl(rems(0.615)).pr(rems(0.462)).bg(theme.background).child( + h_flex() + .w_full() + .gap(rems(0.462)) + .text_size(TEXT_XS) + .child(div().flex_1().min_w_0().truncate().child(label)) + .child(Icon::new(IconName::ChevronDown).size(ICON_XS).text_color(theme.muted_foreground)), + ) +} + +fn columns_menu( + mut menu: PopupMenu, + choices: &Choices, + pick: &Pick, + window: &mut Window, + cx: &mut Context, +) -> PopupMenu { + let item = |table: usize, column: &str, pick: &Pick| { + let (pick, column_name) = (pick.clone(), column.to_string()); + PopupMenuItem::new(column.to_string()) + .on_click(move |_, _, cx| pick(Operand::Column(ColumnRef::new(table, column_name.clone())), cx)) + }; + if let [(_, columns)] = choices.as_slice() { + return match columns { + Some(columns) => columns.iter().fold(menu, |menu, column| menu.item(item(0, column, pick))), + None => menu.item(PopupMenuItem::new(t(cx, "queryBuilder.loading")).disabled(true)), + }; + } + for (table, (key, columns)) in choices.iter().enumerate() { + let (columns, pick) = (columns.clone(), pick.clone()); + menu = menu.submenu(key.clone(), window, cx, move |menu, _, cx| match &columns { + Some(columns) => { + columns.iter().fold(menu, |menu, column| menu.item(item(table, column, &pick))).scrollable(true) + } + None => menu.item(PopupMenuItem::new(t(cx, "queryBuilder.loading")).disabled(true)), + }); + } + menu +} + +impl QueryBuilder { + fn choices(&self, cx: &App) -> Choices { + let tables = self.design.tables.iter().enumerate(); + let choices = tables.map(|(ix, table)| { + let columns = self.columns(ix, cx).map(|columns| columns.iter().map(|c| c.name.clone()).collect()); + (table.key().to_string(), columns) + }); + Rc::new(choices.collect()) + } + + fn picker(&self, cx: &Context, then: impl Fn(&mut Design, Operand) + 'static) -> Pick { + let this = cx.entity().downgrade(); + let then = Rc::new(then); + Rc::new(move |operand, cx| { + let then = then.clone(); + let _ = this.update(cx, |this, cx| this.edit(cx, |design| then(design, operand))); + }) + } + + // Made on first use, showing the design's text unless it's being typed in. + fn input( + &mut self, + field: Field, + value: &str, + placeholder: SharedString, + window: &mut Window, + cx: &mut Context, + ) -> Entity { + self.panel.used.insert(field); + let state = match self.panel.inputs.get(&field) { + Some((state, _)) => state.clone(), + None => { + let state = + cx.new(|cx| InputState::new(window, cx).placeholder(placeholder).default_value(value.to_string())); + let typed = cx.subscribe(&state, move |this, state, event: &InputEvent, cx| { + if matches!(event, InputEvent::Change) { + let text = state.read(cx).value().to_string(); + this.typed(field, text, cx); + } + }); + self.panel.inputs.insert(field, (state.clone(), typed)); + state + } + }; + let focused = state.read(cx).focus_handle(cx).is_focused(window); + if !focused && *state.read(cx).value() != *value { + state.update(cx, |state, cx| state.set_value(value.to_string(), window, cx)); + } + if self.panel.focus_next == Some(field) { + self.panel.focus_next = None; + state.update(cx, |state, cx| state.focus(window, cx)); + } + state + } + + pub(super) fn typed(&mut self, field: Field, text: String, cx: &mut Context) { + let filled = |text: String| Some(text).filter(|text| !text.trim().is_empty()); + self.edit(cx, |design| match field { + Field::Alias(ix) => design.set_alias(ix, text), + Field::Value(clause, ix) => { + if let Some(Condition::Compare { value, .. }) = list(design, clause).get_mut(ix) { + *value = text; + } + } + Field::Raw(clause, ix) => { + if let Some(Condition::Raw(raw)) = list(design, clause).get_mut(ix) { + *raw = text; + } + } + Field::Limit => design.limit = filled(text), + Field::Offset => design.offset = filled(text), + }); + } + + fn groups(&self) -> bool { + let design = &self.design; + design.aggregated() || !design.group_by.is_empty() || !design.having.is_empty() + } + + pub(super) fn panel(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement + use<> { + self.panel.used.clear(); + let theme = cx.theme().clone(); + let items = self.items_section(window, cx); + let filters = self.conditions_section(Clause::Where, window, cx); + let grouping = self.groups().then(|| { + let keys = self.group_section(cx); + let having = self.conditions_section(Clause::Having, window, cx); + v_flex().child(keys).child(having) + }); + let sort = self.sort_section(cx); + let rows = self.rows_section(window, cx); + let Panel { inputs, used, .. } = &mut self.panel; + inputs.retain(|field, _| used.contains(field)); + div() + .debug_selector(|| "qb-panel".into()) + .relative() + .flex_none() + .w(rems(width(cx))) + .h_full() + .bg(theme.sidebar) + .child( + v_flex() + .id("qb-panel-scroll") + .size_full() + .overflow_y_scroll() + .track_scroll(&self.panel.scroll) + .pb(rems(0.923)) + .child(items) + .child(filters) + .children(grouping) + .child(sort) + .child(rows), + ) + .child( + resize_handle::("qb-panel-resize", Axis::Horizontal) + .inside(HandleEdge::Leading) + .on_drag(PanelDrag, |drag, _, _, cx| { + cx.stop_propagation(); + cx.new(|_| drag.clone()) + }) + .on_double_click(cx.listener(|_, _, _, cx| { + cx.set_global(PanelWidth(WIDTHS.0)); + keep_width(cx); + cx.notify(); + })), + ) + .hover_scrollbar(&self.panel.scroll, ScrollbarAxis::Vertical) + } + + fn table_prefix(&self, table: usize) -> Option { + let several = self.design.tables.len() > 1; + several.then(|| self.design.tables.get(table).map(|table| table.key().to_string())).flatten() + } + + // As the panel names a column: unquoted, after its table's name when there are several tables. + pub(super) fn shown(&self, operand: &Operand) -> String { + operand.format_with(|column| match self.table_prefix(column.table) { + Some(table) => format!("{table}.{}", column.column), + None => column.column.clone(), + }) + } + + // What an item picks, its table's name dimmed and cut short first, and its SQL on hover. + fn item_name(&self, ix: usize, item: &Item, sql: SharedString, cx: &App) -> AnyElement { + let theme = cx.theme(); + let (table, name) = match item { + Item::Value { value: Operand::Column(column) | Operand::Aggregate { of: Some(column), .. }, .. } => { + (self.table_prefix(column.table), column.column.clone()) + } + Item::Value { value: Operand::Aggregate { of: None, .. }, .. } => (None, "*".to_string()), + Item::Value { value: Operand::Expr(text) | Operand::Alias(text), .. } => (None, text.clone()), + Item::All(table) => (table.and_then(|table| self.table_prefix(table)), "*".to_string()), + }; + h_flex() + .id(("qb-item-name", ix)) + .flex_1() + .min_w_0() + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_XS) + .children(table.map(|table| { + div() + .flex_none() + .max_w(rems(6.154)) + .truncate() + .text_color(theme.muted_foreground) + .child(format!("{table}.")) + })) + .child(div().flex_1().min_w_0().truncate().child(name)) + .tooltip(move |window, cx| Tooltip::new(sql.clone()).build(window, cx)) + .into_any_element() + } + + fn items_section(&mut self, window: &mut Window, cx: &mut Context) -> Div { + let theme = cx.theme().clone(); + let this = cx.entity().downgrade(); + let add = add_button("qb-add-item", cx).dropdown_menu(move |menu, _, cx| { + let expression = this.clone(); + let count = on_edit(&this, |design| { + let value = Operand::Aggregate { func: Aggregate::Count, of: None }; + design.add_item(Item::Value { value, alias: None }) + }); + menu.item(PopupMenuItem::new("COUNT(*)").on_click(count)) + .item( + PopupMenuItem::new(t(cx, "queryBuilder.everyColumn")) + .on_click(on_edit(&this, |design| design.add_item(Item::All(None)))), + ) + .item(PopupMenuItem::new(t(cx, "queryBuilder.addExpression")).on_click(move |_, window, cx| { + let _ = expression.update(cx, |this, cx| this.ask_expression(window, cx)); + })) + }); + let count = self.design.items.len(); + let rows: Vec = (0..count).map(|ix| self.item_row(ix, window, cx)).collect(); + let distinct = self.design.distinct; + let (title, empty) = (t(cx, "common.columns"), t(cx, "queryBuilder.columnsEmpty")); + section(title, add.into_any_element(), empty, rows, cx) + .child( + div().px(rems(INSET - RING)).child( + form::pick_row( + "qb-distinct".into(), + distinct.then_some(theme.primary), + true, + t(cx, "queryBuilder.distinct"), + "", + cx, + ) + .debug_selector(|| "qb-distinct".into()) + .text_size(TEXT_XS) + .on_click(cx.listener(|this, _, _, cx| this.edit(cx, |design| design.distinct = !design.distinct))), + ), + ) + .text_color(theme.foreground) + } + + fn ask_expression(&mut self, window: &mut Window, cx: &mut Context) { + let prompt = dialogs::Prompt { + title: t(cx, "queryBuilder.expressionTitle"), + description: None, + label: t(cx, "queryBuilder.expressionLabel"), + placeholder: t(cx, "queryBuilder.expressionPlaceholder"), + initial: String::new(), + confirm: t(cx, "queryBuilder.add"), + }; + let this = cx.entity().downgrade(); + dialogs::prompt(prompt, window, cx, move |text, _, cx| { + let text = text.trim().to_string(); + if !text.is_empty() { + let _ = this.update(cx, |this, cx| { + this.edit(cx, |design| design.add_item(Item::Value { value: Operand::Expr(text), alias: None })) + }); + } + }); + } + + fn item_row(&mut self, ix: usize, window: &mut Window, cx: &mut Context) -> AnyElement { + let item = self.design.items[ix].clone(); + let label: SharedString = self.design.item_label(&item, &self.connection.driver).into(); + let name = self.item_name(ix, &item, label.clone(), cx); + let grip = grip(("qb-grip", ix), ItemDrag(ix, label), cx); + let aggregate = match &item { + Item::Value { value: Operand::Column(_), .. } | Item::Value { value: Operand::Aggregate { .. }, .. } => { + Some(self.aggregate_select(ix, &item, cx)) + } + _ => None, + }; + let alias = match &item { + Item::Value { alias, .. } => { + let state = self.input( + Field::Alias(ix), + alias.as_deref().unwrap_or_default(), + t(cx, "queryBuilder.aliasPlaceholder"), + window, + cx, + ); + Some( + div() + .debug_selector(move || format!("qb-alias-{ix}")) + .flex_none() + .w(rems(5.385)) + .child(form::tool_input(&state, window, cx)), + ) + } + Item::All(_) => None, + }; + list_row() + .id(("qb-item", ix)) + .debug_selector(move || format!("qb-item-{ix}")) + .drag_over::(|style, _, _, cx| list_nav::drop_ring(style, cx)) + .on_drop(cx.listener(move |this, drag: &ItemDrag, _, cx| { + let from = drag.0; + this.edit(cx, |design| design.move_item(from, ix)); + })) + .child(grip) + .child(name) + .children(aggregate) + .children(alias) + .child(end_button(remove_button(format!("qb-item-remove-{ix}"), cx)).on_click( + cx.listener(move |this, _, window, cx| this.remove(window, cx, |design| design.remove_item(ix))), + )) + .into_any_element() + } + + fn aggregate_select(&self, ix: usize, item: &Item, cx: &mut Context) -> AnyElement { + let current = match item { + Item::Value { value: Operand::Aggregate { func, .. }, .. } => Some(*func), + _ => None, + }; + let star = matches!(item, Item::Value { value: Operand::Aggregate { of: None, .. }, .. }); + let label: SharedString = current.map_or_else(|| "Σ".into(), |func| func.name().into()); + let this = cx.entity().downgrade(); + row_select(("qb-aggregate", ix), label, cx) + .debug_selector(move || format!("qb-aggregate-{ix}")) + .w(rems(6.154)) + .tooltip(t(cx, "queryBuilder.aggregate")) + .dropdown_menu(move |mut menu, _, cx| { + let set = |func: Option| on_edit(&this, move |design| design.set_aggregate(ix, func)); + menu = menu.item( + PopupMenuItem::new(t(cx, "queryBuilder.noAggregate")) + .checked(current.is_none()) + .disabled(star) + .on_click(set(None)), + ); + for func in Aggregate::ALL { + let item = PopupMenuItem::new(func.name()).checked(current == Some(func)); + menu = menu.item(item.disabled(star && func != Aggregate::Count).on_click(set(Some(func)))); + } + menu + }) + .into_any_element() + } + + fn conditions_section(&mut self, clause: Clause, window: &mut Window, cx: &mut Context) -> Div { + let (key, empty, id) = match clause { + Clause::Where => ("queryBuilder.filters", "queryBuilder.filtersEmpty", "qb-add-filter"), + Clause::Having => ("queryBuilder.having", "queryBuilder.havingEmpty", "qb-add-having"), + }; + let count = conditions(&self.design, clause).len(); + let add = self.add_condition(clause, id, cx); + let rows: Vec = (0..count).map(|ix| self.condition_row(clause, ix, window, cx)).collect(); + section(t(cx, key), add, t(cx, empty), rows, cx) + } + + // A column, or for HAVING an aggregate, to compare; or a condition in SQL. + fn add_condition(&self, clause: Clause, id: &'static str, cx: &mut Context) -> AnyElement { + let this = cx.entity().downgrade(); + let pick = self.picker(cx, move |design, left| { + list(design, clause).push(Condition::Compare { left, op: Op::Eq, value: String::new() }) + }); + let focus = this.clone(); + let pick: Pick = Rc::new(move |operand: Operand, cx: &mut App| { + pick(operand, cx); + let _ = focus.update(cx, |this, _| { + let ix = conditions(&this.design, clause).len().saturating_sub(1); + this.panel.focus_next = Some(Field::Value(clause, ix)); + }); + }); + add_button(id, cx) + .dropdown_menu(move |menu, window, cx| { + let menu = match clause { + Clause::Having => operands_menu(menu, &aggregates_of(&this, cx), &pick), + Clause::Where => columns_menu(menu, &choices_of(&this, cx), &pick, window, cx), + }; + let this = this.clone(); + menu.separator().item(PopupMenuItem::new(t(cx, "queryBuilder.rawCondition")).on_click( + move |_, _, cx| { + let _ = this.update(cx, |this, cx| { + let ix = conditions(&this.design, clause).len(); + this.edit(cx, |design| list(design, clause).push(Condition::Raw(String::new()))); + this.panel.focus_next = Some(Field::Raw(clause, ix)); + cx.notify(); + }); + }, + )) + }) + .into_any_element() + } + + // COUNT(*) and the picked aggregates, as HAVING compares them. + fn aggregate_choices(&self) -> Vec<(SharedString, Operand)> { + let mut out: Vec<(SharedString, Operand)> = + vec![("COUNT(*)".into(), Operand::Aggregate { func: Aggregate::Count, of: None })]; + for item in &self.design.items { + if let Item::Value { value, .. } = item + && value.is_aggregate() + && !out.iter().any(|(_, known)| known == value) + { + out.push((self.shown(value).into(), value.clone())); + } + } + out + } + + fn condition_row(&mut self, clause: Clause, ix: usize, window: &mut Window, cx: &mut Context) -> AnyElement { + let condition = conditions(&self.design, clause)[ix].clone(); + let tag = match clause { + Clause::Where => "where", + Clause::Having => "having", + }; + let remove = end_button(remove_button(format!("qb-{tag}-remove-{ix}"), cx)).on_click(cx.listener( + move |this, _, window, cx| this.remove(window, cx, |design| remove_at(list(design, clause), ix)), + )); + let label: SharedString = match &condition { + Condition::Raw(text) => text.clone().into(), + Condition::Compare { left, op, value } => format!("{} {} {value}", self.shown(left), op.sql()).into(), + }; + let grip = grip(SharedString::from(format!("qb-{tag}-grip-{ix}")), ConditionDrag(clause, ix, label), cx) + .debug_selector(move || format!("qb-{tag}-grip-{ix}")); + // WHERE and HAVING keep their own conditions. + let row = list_row() + .debug_selector(move || format!("qb-{tag}-{ix}")) + .drag_over::(move |style, drag, _, cx| match drag.0 == clause { + true => list_nav::drop_ring(style, cx), + false => style, + }) + .on_drop(cx.listener(move |this, drag: &ConditionDrag, _, cx| { + let (to, from) = (drag.0, drag.1); + if to == clause { + this.edit(cx, |design| { + shift(list(design, clause), from, ix); + }); + } + })) + .child(grip); + let row = match &condition { + Condition::Raw(text) => { + let state = self.input(Field::Raw(clause, ix), text, t(cx, "queryBuilder.rawPlaceholder"), window, cx); + row.child(div().flex_1().min_w_0().child(form::tool_input(&state, window, cx))) + } + Condition::Compare { left, op, value } => { + let left_select = self.operand_select(clause, ix, left, cx); + let op_select = self.op_select(clause, ix, *op, cx); + let value_field = op.takes_value().then(|| { + let state = + self.input(Field::Value(clause, ix), value, t(cx, "queryBuilder.valuePlaceholder"), window, cx); + div().flex_1().min_w_0().child(form::tool_input(&state, window, cx)) + }); + row.child(div().flex_1().min_w_0().child(left_select)).child(op_select).children(value_field) + } + }; + row.child(remove).into_any_element() + } + + fn operand_select(&self, clause: Clause, ix: usize, left: &Operand, cx: &mut Context) -> AnyElement { + let label: SharedString = self.shown(left).into(); + let this = cx.entity().downgrade(); + let pick = self.picker(cx, move |design, operand| { + if let Some(Condition::Compare { left, .. }) = list(design, clause).get_mut(ix) { + *left = operand; + } + }); + row_select(SharedString::from(format!("qb-left-{clause:?}-{ix}")), label, cx) + .w_full() + .font_family(cx.theme().mono_font_family.clone()) + .dropdown_menu(move |menu, window, cx| match clause { + Clause::Having => operands_menu(menu, &aggregates_of(&this, cx), &pick), + Clause::Where => columns_menu(menu, &choices_of(&this, cx), &pick, window, cx), + }) + .into_any_element() + } + + fn op_select(&self, clause: Clause, ix: usize, op: Op, cx: &mut Context) -> AnyElement { + let offered = Op::offered(self.dialect()); + let this = cx.entity().downgrade(); + row_select(SharedString::from(format!("qb-op-{clause:?}-{ix}")), op.sql().into(), cx) + .flex_none() + .w(rems(4.923)) + .dropdown_menu(move |mut menu, _, _| { + for &choice in &offered { + let pick = on_edit(&this, move |design| { + if let Some(Condition::Compare { op, .. }) = list(design, clause).get_mut(ix) { + *op = choice; + } + }); + menu = menu.item(PopupMenuItem::new(choice.sql()).checked(choice == op).on_click(pick)); + } + menu.scrollable(true) + }) + .into_any_element() + } + + fn group_section(&mut self, cx: &mut Context) -> Div { + let theme = cx.theme().clone(); + let this = cx.entity().downgrade(); + let pick = self.picker(cx, |design, key| { + if !design.group_by.contains(&key) { + design.group_by.push(key); + } + }); + let add = add_button("qb-add-group", cx) + .dropdown_menu(move |menu, window, cx| columns_menu(menu, &choices_of(&this, cx), &pick, window, cx)) + .into_any_element(); + let keys: Vec = self + .design + .group_by + .iter() + .enumerate() + .map(|(ix, key)| { + h_flex() + .debug_selector(move || format!("qb-group-{ix}")) + .flex_none() + .h(rems(form::TOOL_REM)) + .pl(rems(0.615)) + .gap(rems(0.154)) + .rounded(RADIUS) + .border_1() + .border_color(theme.border) + .bg(theme.background) + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_XS) + .child(self.shown(key)) + .child(remove_button(format!("qb-group-remove-{ix}"), cx).on_click(cx.listener( + move |this, _, window, cx| { + this.remove(window, cx, |design| remove_at(&mut design.group_by, ix)) + }, + ))) + .into_any_element() + }) + .collect(); + v_flex() + .child(caption(t(cx, "queryBuilder.groupBy"), Some(add), cx)) + .when(keys.is_empty(), |el| el.child(hint(t(cx, "queryBuilder.groupEmpty"), cx))) + .child(h_flex().flex_wrap().px(rems(INSET)).gap(rems(0.308)).children(keys)) + } + + // What's picked, by its name in the results, then any column. + fn sort_section(&mut self, cx: &mut Context) -> Div { + let theme = cx.theme().clone(); + let this = cx.entity().downgrade(); + let named: Vec<(SharedString, Operand)> = self + .design + .items + .iter() + .filter_map(|item| match item { + Item::Value { alias: Some(alias), .. } => Some((alias.clone().into(), Operand::Alias(alias.clone()))), + Item::Value { value, alias: None } if value.is_aggregate() => { + Some((self.shown(value).into(), value.clone())) + } + _ => None, + }) + .collect(); + let add_sort = |design: &mut Design, by: Operand| { + if !design.order_by.iter().any(|sort| sort.by == by) { + design.order_by.push(Sort { by, desc: false, extra: String::new() }); + } + }; + let pick = self.picker(cx, add_sort); + let add = add_button("qb-add-sort", cx) + .dropdown_menu(move |menu, window, cx| { + let menu = operands_menu(menu, &named, &pick).separator(); + columns_menu(menu, &choices_of(&this, cx), &pick, window, cx) + }) + .into_any_element(); + let rows: Vec = self + .design + .order_by + .iter() + .enumerate() + .map(|(ix, sort)| { + let (arrow, word) = match sort.desc { + true => (IconName::ArrowDown, "DESC"), + false => (IconName::ArrowUp, "ASC"), + }; + let label: SharedString = self.shown(&sort.by).into(); + list_row() + .debug_selector(move || format!("qb-sort-{ix}")) + .drag_over::(|style, _, _, cx| list_nav::drop_ring(style, cx)) + .on_drop(cx.listener(move |this, drag: &SortDrag, _, cx| { + let from = drag.0; + this.edit(cx, |design| { + shift(&mut design.order_by, from, ix); + }); + })) + .child( + grip(("qb-sort-grip", ix), SortDrag(ix, label.clone()), cx) + .debug_selector(move || format!("qb-sort-grip-{ix}")), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_XS) + .child(label), + ) + .child( + Button::new(("qb-sort-direction", ix)) + .debug_selector(move || format!("qb-sort-direction-{ix}")) + .tool(Icon::new(arrow), ICON_XS, word) + .on_click(cx.listener(move |this, _, _, cx| { + this.edit(cx, |design| { + if let Some(sort) = design.order_by.get_mut(ix) { + sort.desc = !sort.desc; + } + }) + })), + ) + .child(end_button(remove_button(format!("qb-sort-remove-{ix}"), cx)).on_click(cx.listener( + move |this, _, window, cx| { + this.remove(window, cx, |design| remove_at(&mut design.order_by, ix)) + }, + ))) + .into_any_element() + }) + .collect(); + section(t(cx, "queryBuilder.sort"), add, t(cx, "queryBuilder.sortEmpty"), rows, cx) + } + + fn rows_section(&mut self, window: &mut Window, cx: &mut Context) -> Div { + let limit = self.design.limit.clone().unwrap_or_default(); + let offset = self.design.offset.clone().unwrap_or_default(); + let limit = self.input(Field::Limit, &limit, t(cx, "queryBuilder.everyRow"), window, cx); + let offset = self.input(Field::Offset, &offset, "0".into(), window, cx); + let field = + |label: SharedString, state: &Entity, selector: &'static str, window: &Window, cx: &App| { + form::group(label, form::tool_input(state, window, cx), cx) + .flex_1() + .debug_selector(move || selector.into()) + }; + v_flex().child(caption(t(cx, "queryBuilder.rows"), None, cx)).child( + h_flex() + .px(rems(INSET)) + .gap(rems(0.615)) + .child(field(t(cx, "queryBuilder.limit"), &limit, "qb-limit", window, cx)) + .child(field(t(cx, "queryBuilder.offset"), &offset, "qb-offset", window, cx)), + ) + } +} diff --git a/crates/barsql-ui/src/query_builder/tests.rs b/crates/barsql-ui/src/query_builder/tests.rs new file mode 100644 index 0000000..4e08736 --- /dev/null +++ b/crates/barsql-ui/src/query_builder/tests.rs @@ -0,0 +1,645 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use barsql_app::{BuilderRef, EditorTab}; +use barsql_sql::design::{Condition, ImportError, Item}; +use gpui_kit::component::RopeExt; +use gpui_kit::{Entity, Focusable as _, Modifiers, MouseButton, TestAppContext, VisualTestContext, px, size}; + +use super::{Place, QueryBuilder}; +use crate::query_tab::{QueryTab, QueryTabEvent, new_tab_id}; +use crate::results::ResultStatus; +use crate::schema; +use crate::test_support::{Env, chord, settle}; + +fn window<'a>(env: &Env, cx: &'a mut TestAppContext, tab: EditorTab) -> (Entity, &'a mut VisualTestContext) { + let connection = env.connection.clone(); + let (tab, cx) = cx.add_window_view(|window, cx| QueryTab::new(tab, connection, window, cx)); + cx.simulate_resize(size(px(1400.), px(900.))); + cx.update(|window, cx| tab.update(cx, |tab, cx| tab.focus_editor(window, cx))); + draw(cx); + (tab, cx) +} + +// A builder tab on `sql`. +fn open<'a>( + env: &Env, + cx: &'a mut TestAppContext, + sql: &str, +) -> (Entity, Entity, &'a mut VisualTestContext) { + let tab = EditorTab { + id: new_tab_id(), + connection_id: env.connection.id.clone(), + sql: sql.into(), + builder: Some(BuilderRef::default()), + ..Default::default() + }; + let (tab, cx) = window(env, cx, tab); + let builder = cx.update(|_, cx| tab.read(cx).builder()).expect("a builder tab"); + (tab, builder, cx) +} + +fn open_sql<'a>(env: &Env, cx: &'a mut TestAppContext, sql: &str) -> (Entity, &'a mut VisualTestContext) { + let tab = + EditorTab { id: new_tab_id(), connection_id: env.connection.id.clone(), sql: sql.into(), ..Default::default() }; + window(env, cx, tab) +} + +fn seed(env: &Env, sql: &str) { + env.runtime.block_on(env.bar.execute_query(&env.connection.id, sql)).unwrap(); +} + +fn text(tab: &Entity, cx: &mut VisualTestContext) -> String { + cx.update(|_, cx| tab.read(cx).sql(cx).to_string()) +} + +fn type_sql(tab: &Entity, sql: &str, cx: &mut VisualTestContext) { + cx.update(|window, cx| { + let editor = tab.read(cx).editor(); + editor.update(cx, |state, cx| state.replace_all(sql.to_string(), window, cx)); + }); + draw(cx); +} + +fn show_sql(tab: &Entity, show: bool, cx: &mut VisualTestContext) { + cx.update(|window, cx| tab.update(cx, |tab, cx| tab.show_builder_sql(show, window, cx))); + draw(cx); +} + +fn draw(cx: &mut VisualTestContext) { + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); +} + +// Waits for the tables' columns, which the cards list. +fn columns_of(builder: &Entity, tables: usize, cx: &mut VisualTestContext) { + settle(cx, |cx| cx.update(|_, cx| (0..tables).all(|ix| builder.read(cx).columns(ix, cx).is_some()))); + draw(cx); +} + +// The SQL the tab hands on to a new SQL tab. +fn opened_sql(tab: &Entity, cx: &mut VisualTestContext) -> Rc>> { + let opened = Rc::new(RefCell::new(Vec::new())); + let seen = opened.clone(); + cx.update(|_, cx| { + cx.subscribe(tab, move |_, event: &QueryTabEvent, _| { + if let QueryTabEvent::OpenSql(sql) = event { + seen.borrow_mut().push(sql.clone()); + } + }) + .detach() + }); + opened +} + +#[gpui_kit::test] +fn a_sql_tab_hands_the_builder_its_selection_or_the_statement_at_the_caret(cx: &mut TestAppContext) { + let env = Env::new(cx); + let sql = "SELECT 1;\n\n-- the things\nSELECT id, name FROM things WHERE id > 5;\n\nSELECT 1 UNION SELECT 2"; + let (tab, cx) = open_sql(&env, cx, sql); + let at = |offset: usize, cx: &mut VisualTestContext| { + cx.update(|window, cx| { + let editor = tab.read(cx).editor(); + editor + .update(cx, |state, cx| state.set_cursor_position(state.text().offset_to_position(offset), window, cx)); + tab.read(cx).builder_source(cx) + }) + }; + assert_eq!(at(40, cx).as_deref(), Ok("SELECT id, name FROM things WHERE id > 5"), "less its comment and `;`"); + let union = at(sql.len(), cx).expect_err("the builder can't show a UNION"); + assert!(union.contains("UNION"), "{union}"); + let selected = cx.update(|_, cx| { + let editor = tab.read(cx).editor(); + editor.update(cx, |state, cx| state.set_selected_range(25..52, cx)); + tab.read(cx).builder_source(cx) + }); + assert_eq!(selected.as_deref(), Ok("SELECT id, name FROM things"), "a selection goes as it is"); + let (empty, cx) = open_sql(&env, cx, ""); + assert_eq!(cx.update(|_, cx| empty.read(cx).builder_source(cx)).as_deref(), Ok("")); +} + +#[gpui_kit::test] +fn a_builder_tab_draws_its_query_in_the_editors_place(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (_, builder, cx) = open(&env, cx, "SELECT id, name FROM things WHERE id > 5"); + let design = cx.update(|_, cx| builder.read(cx).design.clone()); + assert_eq!((design.tables.len(), design.items.len(), design.filters.len()), (1, 2, 1)); + assert!(cx.debug_bounds("qb-card-0").is_some(), "the table is on the canvas"); + assert!(cx.debug_bounds("view-sql").is_some(), "its SQL is a switch away"); + assert_eq!(cx.debug_bounds("query-editor").map(|b| b.size.height), Some(px(0.)), "no SQL to edit"); + let focused = cx.update(|window, cx| builder.read(cx).focus.contains_focused(window, cx)); + assert!(focused, "keys go to the canvas, not the hidden editor"); + assert!(cx.debug_bounds("run").is_some() && cx.debug_bounds("qb-toolbar").is_some(), "one toolbar has both"); + for absent in ["run-all", "open-builder", "save-query", "begin-txn"] { + assert!(cx.debug_bounds(absent).is_none(), "{absent} is a SQL tab's"); + } +} + +#[gpui_kit::test] +fn picks_on_the_canvas_rewrite_the_query_and_undo_reads_it_back(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, ""); + assert!(cx.debug_bounds("qb-empty").is_some(), "an empty canvas says how to start"); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.add_table("main", "things", None, cx))); + assert_eq!(text(&tab, cx), "SELECT *\nFROM things"); + columns_of(&builder, 1, cx); + let name = cx.debug_bounds("qb-column-0-1").expect("the name column is drawn"); + cx.simulate_click(name.center(), Modifiers::default()); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT name\nFROM things"); + cx.simulate_keystrokes(&chord("mod-z")); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT *\nFROM things"); + assert!(cx.update(|_, cx| builder.read(cx).design.items.is_empty()), "the canvas follows its undo"); + cx.simulate_keystrokes(&chord("mod-shift-z")); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT name\nFROM things"); +} + +#[gpui_kit::test] +fn run_takes_the_whole_query(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, _, cx) = open(&env, cx, "SELECT name\nFROM things\nWHERE id <= 3"); + let run = cx.debug_bounds("run").expect("Run is drawn"); + cx.simulate_click(run.center(), Modifiers::default()); + settle(cx, |cx| cx.update(|_, cx| tab.read(cx).idle(cx))); + let rows = cx.update(|_, cx| match tab.read(cx).results().read(cx).status(cx) { + ResultStatus::Rows { count } => Some(count), + _ => None, + }); + assert_eq!(rows, Some(3)); +} + +#[gpui_kit::test] +fn the_sql_view_edits_the_query_and_the_canvas_follows(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT name\nFROM things"); + let opened = opened_sql(&tab, cx); + let switch = cx.debug_bounds("view-sql").expect("the switch is drawn"); + cx.simulate_click(switch.center(), Modifiers::default()); + draw(cx); + let height = cx.debug_bounds("query-editor").map(|bounds| bounds.size.height); + assert!(height.is_some_and(|h| h > px(100.)) && cx.debug_bounds("qb-canvas").is_none(), "in the canvas's place"); + assert!(cx.update(|window, cx| tab.read(cx).editor_has_focus(window, cx)), "keys go to the SQL"); + let copy = cx.debug_bounds("copy-sql").expect("Copy is drawn"); + cx.simulate_click(copy.center(), Modifiers::default()); + let copied = cx.update(|_, cx| cx.read_from_clipboard().and_then(|item| item.text())); + assert_eq!(copied.as_deref(), Some("SELECT name\nFROM things")); + let open = cx.debug_bounds("open-sql").expect("Open in editor is drawn"); + cx.simulate_click(open.center(), Modifiers::default()); + cx.run_until_parked(); + assert_eq!(*opened.borrow(), ["SELECT name\nFROM things"]); + cx.update(|window, cx| { + let editor = tab.read(cx).editor(); + editor.update(cx, |state, cx| { + let end = state.text().offset_to_position(state.value().len()); + state.set_cursor_position(end, window, cx); + state.focus(window, cx); + }); + }); + cx.simulate_input(" WHERE id > 5"); + draw(cx); + assert!(cx.update(|_, cx| builder.read(cx).design.filters.is_empty()), "the canvas waits till it shows"); + cx.update(|window, cx| tab.update(cx, |tab, cx| tab.toggle_builder_view(window, cx))); + draw(cx); + assert!(cx.debug_bounds("qb-canvas").is_some()); + assert_eq!(cx.update(|_, cx| builder.read(cx).design.filters.len()), 1, "redrawn from the edit"); + cx.simulate_keystrokes(&chord("mod-z")); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT name\nFROM things", "undo on the canvas takes the edit back"); + assert!(cx.update(|_, cx| builder.read(cx).design.filters.is_empty())); +} + +// SQL the canvas can't show greys it out, and Edit SQL goes back to fix it. +#[gpui_kit::test] +fn sql_the_canvas_cannot_show_waits_to_be_fixed(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT id FROM things"); + show_sql(&tab, true, cx); + let sql = "SELECT id FROM things UNION SELECT 1"; + type_sql(&tab, sql, cx); + show_sql(&tab, false, cx); + let problem = cx.update(|_, cx| builder.read(cx).problem.clone()); + assert_eq!(problem, Some(ImportError::Unsupported("UNION".into()))); + assert!(cx.debug_bounds("qb-problem").is_some() && cx.debug_bounds("qb-blocked").is_some()); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.add_table("main", "things", None, cx))); + assert_eq!(text(&tab, cx), sql, "nothing is written over SQL it can't read"); + let edit = cx.debug_bounds("qb-problem-edit").expect("the bar offers the SQL"); + cx.simulate_click(edit.center(), Modifiers::default()); + draw(cx); + assert!(cx.update(|_, cx| tab.read(cx).shows_sql())); + type_sql(&tab, "SELECT id FROM things", cx); + show_sql(&tab, false, cx); + assert!(cx.update(|_, cx| builder.read(cx).problem.is_none()), "fixed, it draws again"); +} + +#[gpui_kit::test] +fn a_table_joins_the_others_by_its_foreign_key(cx: &mut TestAppContext) { + let env = Env::new(cx); + seed(&env, "CREATE TABLE owners (id INTEGER PRIMARY KEY, name TEXT)"); + seed(&env, "CREATE TABLE pets (id INTEGER PRIMARY KEY, owner_id INTEGER REFERENCES owners(id), name TEXT)"); + let (tab, builder, cx) = open(&env, cx, ""); + settle(cx, |cx| cx.update(|_, cx| schema::get(cx, &env.connection.id).is_some_and(|s| s.tables("main").is_some()))); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.add_table("main", "owners", None, cx))); + columns_of(&builder, 1, cx); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.add_table("main", "pets", None, cx))); + settle(cx, |_| true); + columns_of(&builder, 2, cx); + settle(cx, |cx| text(&tab, cx).contains("JOIN")); + assert_eq!(text(&tab, cx), "SELECT *\nFROM owners\nINNER JOIN pets ON pets.owner_id = owners.id"); + assert!(cx.debug_bounds("qb-join-1").is_some(), "the join's kind sits on its line"); +} + +#[gpui_kit::test] +fn a_column_dragged_onto_another_tables_joins_them(cx: &mut TestAppContext) { + let env = Env::new(cx); + seed(&env, "CREATE TABLE tags (id INTEGER PRIMARY KEY, thing INTEGER, label TEXT)"); + let (tab, builder, cx) = open(&env, cx, "SELECT * FROM things CROSS JOIN tags"); + columns_of(&builder, 2, cx); + assert!(cx.debug_bounds("qb-column-1-1").is_none(), "a folded card lists only keys and used columns"); + for more in ["qb-more-0", "qb-more-1"] { + let row = cx.debug_bounds(more).expect("a folded card offers the rest"); + cx.simulate_click(row.center(), Modifiers::default()); + draw(cx); + } + let from = cx.debug_bounds("qb-column-1-1").expect("tags.thing is drawn"); + let to = cx.debug_bounds("qb-column-0-0").expect("things.id is drawn"); + cx.simulate_mouse_down(from.center(), MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(from.center() + gpui_kit::point(px(10.), px(0.)), MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(to.center(), MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_up(to.center(), MouseButton::Left, Modifiers::default()); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT *\nFROM things\nINNER JOIN tags ON tags.thing = things.id"); +} + +// Laid out before their columns load, two cards in one column are laid out again once they have. +#[gpui_kit::test] +fn cards_laid_out_before_their_columns_load_never_overlap(cx: &mut TestAppContext) { + let env = Env::new(cx); + seed(&env, "CREATE TABLE tags (id INTEGER PRIMARY KEY, thing INTEGER, label TEXT, a TEXT, b TEXT, c TEXT)"); + let sql = "SELECT * FROM things t JOIN tags a ON a.thing = t.id JOIN tags b ON b.thing = t.id"; + let (tab, builder, cx) = open(&env, cx, sql); + columns_of(&builder, 3, cx); + let (places, heights) = cx.update(|_, cx| (builder.read(cx).places.clone(), builder.read(cx).heights(cx))); + assert!(!overlap(&places, &heights), "{places:?} {heights:?}"); + // Reopened with the tab, before the schema has loaded. + let stored = cx.update(|_, cx| tab.read(cx).stored(cx)); + cx.update(|_, cx| schema::forget(&env.connection.id, cx)); + let connection = env.connection.clone(); + let (again, cx) = cx.add_window_view(|window, cx| QueryTab::new(stored, connection, window, cx)); + let builder = cx.update(|_, cx| again.read(cx).builder()).expect("reopened as a builder tab"); + columns_of(&builder, 3, cx); + let (places, heights) = cx.update(|_, cx| (builder.read(cx).places.clone(), builder.read(cx).heights(cx))); + assert!(!overlap(&places, &heights), "{places:?} {heights:?}"); +} + +fn overlap(places: &[Place], heights: &[f32]) -> bool { + let apart = |a: usize, b: usize| { + let (p, q) = (places[a], places[b]); + p.x + super::CARD_W <= q.x || q.x + super::CARD_W <= p.x || p.y + heights[a] <= q.y || q.y + heights[b] <= p.y + }; + (0..places.len()).any(|a| (a + 1..places.len()).any(|b| !apart(a, b))) +} + +#[gpui_kit::test] +fn the_session_keeps_a_builder_tab_with_its_tables_where_they_were(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT name FROM things"); + let laid_out = cx.update(|_, cx| tab.read(cx).stored(cx)).builder.expect("a builder tab"); + assert!(laid_out.tables.is_empty(), "its own layout is laid out again, not kept"); + cx.update(|_, cx| { + builder.update(cx, |builder, _| { + builder.places[0] = Place::new(12.3, 4.); + builder.auto = false; + }) + }); + show_sql(&tab, true, cx); + let stored = cx.update(|_, cx| tab.read(cx).stored(cx)); + let kept = stored.builder.clone().expect("still a builder tab"); + let places = &kept.tables; + assert_eq!((places[0].table.as_str(), places[0].x, places[0].y, kept.sql_view), ("things", 123, 40, true)); + let connection = env.connection.clone(); + let (again, cx) = cx.add_window_view(|window, cx| QueryTab::new(stored, connection, window, cx)); + let reopened = cx.update(|_, cx| again.read(cx).builder()).expect("reopened as a builder tab"); + let (place, sql) = cx.update(|_, cx| (reopened.read(cx).places[0], again.read(cx).shows_sql())); + assert_eq!((place, sql), (Place::new(12.3, 4.), true), "where it was, on the SQL"); +} + +#[gpui_kit::test] +fn the_panel_names_items_and_filters_as_they_are_typed(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT name FROM things WHERE id > 1"); + let alias = cx.debug_bounds("qb-item-0").expect("the item's row is drawn"); + assert!(alias.size.width > px(0.)); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.typed(super::panel::Field::Alias(0), "n".into(), cx))); + cx.update(|_, cx| { + builder.update(cx, |builder, cx| { + builder.typed(super::panel::Field::Value(super::panel::Clause::Where, 0), "10".into(), cx) + }) + }); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.typed(super::panel::Field::Limit, "5".into(), cx))); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT name AS n\nFROM things\nWHERE id > 10\nLIMIT 5"); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.edit(cx, |design| design.items.push(Item::All(None))))); + draw(cx); + assert!(text(&tab, cx).starts_with("SELECT name AS n, *")); +} + +// What the canvas writes isn't typing, wherever the SQL view left the caret. +#[gpui_kit::test] +fn typing_in_the_panel_never_opens_the_sql_suggestions(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, _, cx) = open(&env, cx, "SELECT name FROM things"); + let id = env.connection.id.clone(); + settle(cx, |cx| cx.update(|_, cx| schema::catalog(cx, &id).is_some())); + show_sql(&tab, true, cx); + cx.update(|window, cx| { + let editor = tab.read(cx).editor(); + editor.update(cx, |state, cx| { + let on_name = state.text().offset_to_position("SELECT na".len()); + state.set_cursor_position(on_name, window, cx); + }) + }); + show_sql(&tab, false, cx); + let alias = cx.debug_bounds("qb-alias-0").expect("the alias field is drawn").center(); + cx.simulate_click(alias, Modifiers::default()); + for key in ["n", "m"] { + cx.simulate_input(key); + draw(cx); + } + assert!(text(&tab, cx).contains("name AS nm"), "{}", text(&tab, cx)); + let completion = cx.update(|_, cx| tab.read(cx).completion()); + assert_eq!(cx.update(|_, cx| completion.read(cx).labels(cx)), Vec::::new()); +} + +#[test] +fn the_first_foreign_key_between_two_tables_is_the_join() { + use barsql_core::ColumnInfo; + let column = |name: &str, key: &str, table: &str, target: &str| ColumnInfo { + name: name.into(), + is_foreign: !table.is_empty(), + foreign_table: table.into(), + foreign_column: target.into(), + foreign_key: key.into(), + ..Default::default() + }; + let posts = + [column("id", "", "", ""), column("author", "fk1", "users", "id"), column("editor", "fk2", "users", "id")]; + let users = [ColumnInfo { name: "id".into(), is_primary: true, ..Default::default() }]; + let pairs = super::first_key(super::key_pairs(&posts, "USERS", &users)); + assert_eq!(pairs, [("author".to_string(), "id".to_string())], "editor is another join"); + let implicit = [column("owner", "0", "users", "")]; + assert_eq!(super::first_key(super::key_pairs(&implicit, "users", &users)), [("owner".into(), "id".into())]); +} + +#[gpui_kit::test] +fn a_folded_card_keeps_a_row_it_listed_until_it_folds_again(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT name FROM things"); + columns_of(&builder, 1, cx); + assert!(cx.debug_bounds("qb-column-0-1").is_some() && cx.debug_bounds("qb-column-0-0").is_none()); + let name = cx.debug_bounds("qb-column-0-1").expect("drawn"); + cx.simulate_click(name.center(), Modifiers::default()); + draw(cx); + assert_eq!(text(&tab, cx), "SELECT *\nFROM things"); + assert!(cx.debug_bounds("qb-column-0-1").is_some(), "unticked, it stays where it was"); + let more = cx.debug_bounds("qb-more-0").expect("drawn"); + cx.simulate_click(more.center(), Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("qb-column-0-0").is_some(), "unfolded, it lists every column"); + let fewer = cx.debug_bounds("qb-more-0").expect("drawn"); + cx.simulate_click(fewer.center(), Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("qb-column-0-1").is_none(), "folded again, only what the query uses"); +} + +#[gpui_kit::test] +fn the_panel_names_columns_plainly_and_by_table_once_there_are_several(cx: &mut TestAppContext) { + let env = Env::new(cx); + seed(&env, "CREATE TABLE \"Tags\" (id INTEGER PRIMARY KEY, thing INTEGER, \"Label\" TEXT)"); + let sql = "SELECT t.\"Label\", COUNT(DISTINCT x.id) FROM things x JOIN \"Tags\" t ON t.thing = x.id"; + let (_, builder, cx) = open(&env, cx, sql); + let shown = |builder: &Entity, cx: &mut VisualTestContext| { + cx.update(|_, cx| { + let builder = builder.read(cx); + let values = builder.design.items.iter().filter_map(|item| match item { + Item::Value { value, .. } => Some(builder.shown(value)), + Item::All(_) => None, + }); + values.collect::>() + }) + }; + assert_eq!(shown(&builder, cx), ["t.Label", "COUNT(DISTINCT x.id)"]); + let (_, alone, cx) = open(&env, cx, "SELECT \"name\" FROM things"); + assert_eq!(shown(&alone, cx), ["name"], "one table needs no prefix"); +} + +#[gpui_kit::test] +fn the_panel_rows_line_up_and_its_edge_drags_wider(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (_, _, cx) = open(&env, cx, "SELECT name FROM things"); + let select = cx.debug_bounds("qb-aggregate-0").expect("the aggregate select is drawn"); + let alias = cx.debug_bounds("qb-alias-0").expect("the alias field is drawn"); + assert_eq!(select.size.height, alias.size.height, "a select and a field share a row's height"); + let before = cx.debug_bounds("qb-panel").expect("the panel shows"); + let edge = gpui_kit::point(before.left() + px(1.), before.center().y); + let to = edge - gpui_kit::point(px(80.), px(0.)); + cx.simulate_mouse_down(edge, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(edge - gpui_kit::point(px(10.), px(0.)), MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(to, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::default()); + draw(cx); + let after = cx.debug_bounds("qb-panel").expect("the panel shows"); + assert!((after.size.width - before.size.width - px(80.)).abs() < px(2.), "{before:?} {after:?}"); + cx.executor().advance_clock(super::panel::WIDTH_SAVE * 2); + cx.run_until_parked(); + let kept = cx.update(|_, cx| crate::state::setting(cx, "barsql-builder-panel-w")); + assert!(kept.is_some(), "a paused drag keeps the width"); +} + +#[gpui_kit::test] +fn the_panels_add_and_remove_buttons_sit_under_the_help_button(cx: &mut TestAppContext) { + let env = Env::new(cx); + let sql = "SELECT name, COUNT(id) FROM things WHERE id > 1 GROUP BY name HAVING COUNT(id) > 1 ORDER BY name"; + let (_, _, cx) = open(&env, cx, sql); + let help = cx.debug_bounds("qb-help").expect("the help button is drawn").center().x; + let buttons = ["qb-add-item", "qb-item-remove-0", "qb-add-filter", "qb-where-remove-0", "qb-add-group"]; + for id in buttons.into_iter().chain(["qb-add-having", "qb-having-remove-0", "qb-add-sort", "qb-sort-remove-0"]) { + let x = cx.debug_bounds(id).unwrap_or_else(|| panic!("{id} is drawn")).center().x; + assert!((x - help).abs() < px(0.01), "{id} centres at {x:?}, the help button at {help:?}"); + } +} + +// Pressed on `from`, moved off it, and let go on `to`. +fn drag(from: &'static str, to: &'static str, cx: &mut VisualTestContext) { + let start = cx.debug_bounds(from).expect("the grip is drawn").center(); + let end = cx.debug_bounds(to).expect("the target is drawn").center(); + cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(start + gpui_kit::point(px(0.), px(6.)), MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default()); + draw(cx); +} + +#[gpui_kit::test] +fn filters_and_sorts_drag_into_a_new_order(cx: &mut TestAppContext) { + let env = Env::new(cx); + let sql = "SELECT id, name FROM things WHERE id > 1 AND name <> 'x' ORDER BY id, name DESC"; + let (tab, _, cx) = open(&env, cx, sql); + drag("qb-where-grip-1", "qb-where-grip-0", cx); + let moved = text(&tab, cx); + assert!(moved.find("name <> 'x'").unwrap() < moved.find("id > 1").unwrap(), "{moved}"); + drag("qb-sort-grip-1", "qb-sort-grip-0", cx); + let sorted = text(&tab, cx); + assert!(sorted.contains("ORDER BY name DESC, id"), "{sorted}"); +} + +#[gpui_kit::test] +fn the_panel_hides_for_every_builder(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (_, _, cx) = open(&env, cx, "SELECT name FROM things"); + let canvas = |cx: &mut VisualTestContext| cx.debug_bounds("qb-canvas").expect("drawn").size.width; + let (before, panel) = (canvas(cx), cx.debug_bounds("qb-panel").expect("the panel shows")); + let button = cx.debug_bounds("qb-panel-toggle").expect("drawn"); + cx.simulate_click(button.center(), Modifiers::default()); + draw(cx); + assert!(cx.debug_bounds("qb-panel").is_none()); + assert!(canvas(cx) >= before + panel.size.width - px(1.), "the canvas takes its room"); +} + +// Hidden under the canvas, the editor gets no keys: not by Tab, a menu's Escape or Ctrl+Space. +#[gpui_kit::test] +fn the_editor_under_the_canvas_never_takes_the_keys(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT name FROM things"); + let id = env.connection.id.clone(); + settle(cx, |cx| cx.update(|_, cx| schema::catalog(cx, &id).is_some())); + let stop = |cx: &mut VisualTestContext| cx.update(|_, cx| tab.read(cx).editor().read(cx).focus_handle(cx).tab_stop); + assert!(!stop(cx), "no stop for Tab"); + show_sql(&tab, true, cx); + assert!(stop(cx), "shown, it is one"); + cx.update(|window, cx| { + let editor = tab.read(cx).editor(); + editor.update(cx, |state, cx| { + let on_name = state.text().offset_to_position("SELECT na".len()); + state.set_cursor_position(on_name, window, cx); + }) + }); + show_sql(&tab, false, cx); + assert!(!stop(cx)); + + let caret = cx.debug_bounds("explain-menu").expect("the Explain menu is drawn"); + cx.simulate_click(caret.center(), Modifiers::default()); + draw(cx); + cx.simulate_keystrokes("escape"); + draw(cx); + let keys = + cx.update(|window, cx| (builder.read(cx).focus.is_focused(window), tab.read(cx).editor_has_focus(window, cx))); + assert_eq!(keys, (true, false), "Escape hands the keys back to the canvas"); + + cx.simulate_keystrokes("ctrl-space"); + draw(cx); + let completion = cx.update(|_, cx| tab.read(cx).completion()); + assert_eq!(cx.update(|_, cx| completion.read(cx).labels(cx)), Vec::::new()); +} + +// A change made from SQL that was edited since is dropped, and the canvas reads the edit when it shows. +#[gpui_kit::test] +fn the_canvas_never_writes_over_an_edit_it_has_not_read(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open( + &env, + cx, + "SELECT name +FROM things", + ); + show_sql(&tab, true, cx); + type_sql( + &tab, + "SELECT id +FROM things", + cx, + ); + cx.update(|_, cx| builder.update(cx, |builder, cx| builder.edit(cx, |design| design.items.push(Item::All(None))))); + draw(cx); + assert_eq!( + text(&tab, cx), + "SELECT id +FROM things" + ); + show_sql(&tab, false, cx); + assert_eq!(cx.update(|_, cx| builder.read(cx).design.items.len()), 1, "the canvas reads the edit"); +} + +#[gpui_kit::test] +fn a_filter_being_filled_in_outlasts_columns_loading(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (_, builder, cx) = open(&env, cx, "SELECT name FROM things WHERE id > 1"); + columns_of(&builder, 1, cx); + let blank = Condition::Raw(String::new()); + cx.update(|_, cx| { + builder.update(cx, |builder, cx| builder.edit(cx, |design| design.filters.insert(0, blank.clone()))) + }); + // As though more columns had come. + cx.update(|_, cx| { + builder.update(cx, |builder, cx| { + builder.known = 0; + builder.schema_changed(cx); + }) + }); + let filters = cx.update(|_, cx| builder.read(cx).design.filters.clone()); + assert_eq!(filters.len(), 2, "{filters:?}"); + assert_eq!(filters[0], blank, "where it was"); +} + +#[gpui_kit::test] +fn cards_ask_for_their_columns_again_once_the_schema_is_forgotten(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (_, builder, cx) = open(&env, cx, "SELECT name FROM things"); + columns_of(&builder, 1, cx); + cx.update(|_, cx| schema::forget(&env.connection.id, cx)); + columns_of(&builder, 1, cx); + assert!(cx.debug_bounds("qb-column-0-1").is_some(), "the card lists them again"); +} + +// Typing after a row's × can't land in the row that takes its place. +#[gpui_kit::test] +fn a_rows_remove_button_takes_the_keys_from_its_fields(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, builder, cx) = open(&env, cx, "SELECT id, name FROM things"); + let alias = cx.debug_bounds("qb-alias-0").expect("the alias field is drawn"); + cx.simulate_click(alias.center(), Modifiers::default()); + draw(cx); + let remove = cx.debug_bounds("qb-item-remove-0").expect("the row's × is drawn"); + cx.simulate_click(remove.center(), Modifiers::default()); + draw(cx); + assert_eq!( + text(&tab, cx), + "SELECT name +FROM things" + ); + assert!(cx.update(|window, cx| builder.read(cx).focus.is_focused(window)), "the canvas has the keys"); + cx.simulate_input("x"); + draw(cx); + assert_eq!( + text(&tab, cx), + "SELECT name +FROM things" + ); +} + +#[gpui_kit::test] +fn a_transaction_begun_in_a_builder_tab_ends_there(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tab, _, cx) = open(&env, cx, "BEGIN"); + let run = cx.debug_bounds("run").expect("Run is drawn"); + cx.simulate_click(run.center(), Modifiers::default()); + settle(cx, |cx| cx.update(|_, cx| tab.read(cx).idle(cx))); + draw(cx); + assert!(cx.debug_bounds("commit-txn").is_some(), "Commit and Rollback are in the toolbar"); + let rollback = cx.debug_bounds("rollback-txn").expect("Rollback is drawn"); + cx.simulate_click(rollback.center(), Modifiers::default()); + settle(cx, |cx| cx.update(|_, cx| tab.read(cx).idle(cx))); + draw(cx); + assert!(cx.debug_bounds("rollback-txn").is_none()); +} diff --git a/crates/barsql-ui/src/query_tab.rs b/crates/barsql-ui/src/query_tab.rs index c598007..fdc214e 100644 --- a/crates/barsql-ui/src/query_tab.rs +++ b/crates/barsql-ui/src/query_tab.rs @@ -2,8 +2,9 @@ use std::ops::Range; use std::rc::Rc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -use barsql_app::{EditorTab, RunEvent}; +use barsql_app::{BuilderRef, EditorTab, RunEvent, TablePlace}; use barsql_core::{ConnectionConfig, DatabaseInfo, SavedQuery, scope}; +use barsql_sql::design; use barsql_sql::lang::{self, TxnControl, detect_transaction_control}; use barsql_sql::params::{find_params, param_names, substitute}; use barsql_sql::{is_read_only, split_statements, unbounded_writes}; @@ -12,7 +13,7 @@ use gpui_kit::base::resize_handle; use gpui_kit::component::button::{Button, ButtonVariants}; use gpui_kit::component::input::{ Editor, EditorMode, EditorState, GoToDefinition, InputEvent, RangeDecoration, RangeDecorationCollection, - RangeDecorationStyle, Replace, Search, SelectAll, + RangeDecorationStyle, Redo, Replace, Search, SelectAll, Undo, }; use gpui_kit::component::menu::{DropdownMenu, PopupMenu, PopupMenuItem}; use gpui_kit::component::native_menu::NativeMenu; @@ -24,7 +25,7 @@ use gpui_kit::*; use lsp_types::{Diagnostic, DiagnosticSeverity, ShowDocumentParams}; use crate::actions::{ - BeginTransaction, CommitTransaction, ExplainAnalyze, ExplainQuery, FormatQuery, RenameSavedQuery, + BeginTransaction, CommitTransaction, ExplainAnalyze, ExplainQuery, FormatQuery, OpenQueryBuilder, RenameSavedQuery, RollbackTransaction, RunAll, RunSelection, SaveQuery, SaveQueryAs, ShowAlgebra, TriggerSuggest, }; use crate::algebra_graph::{self, AlgebraEvent, AlgebraGraph}; @@ -38,6 +39,7 @@ use crate::grid::{Grid, RowRef, copy}; use crate::hover_card::HoverCard; use crate::i18n::{I18n, t, t_count, t_with}; use crate::occurrences::{self, OccurrenceMarks}; +use crate::query_builder::{self, BuilderEvent, Place, QueryBuilder}; use crate::results::{Fix, ResultsEvent, ResultsPanel}; use crate::saved_queries; use crate::schema::{self, Schemas}; @@ -45,7 +47,7 @@ use crate::scrollbars::ScrollbarsOnHover as _; 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::tokens::{DOT_SM, ICON_XS, RADIUS, STRIP, STRIP_PAD, TEXT_XS, TINT, TINT_BORDER}; use crate::{params_dialog, shortcuts, state, theme, toast}; const EDITOR_CONTEXT: &str = "QueryEditor CodeEditor"; @@ -122,6 +124,21 @@ impl Render for SplitDrag { } } +// A builder tab's canvas, the SQL it last wrote or read, and whether the editor shows in its place. +struct Builder { + view: Entity, + sql_view: bool, + _subscriptions: [Subscription; 2], +} + +const CANVAS_FLOOR: f32 = 14.; + +// A statement's code, less leading comments and `;`, as the builder reads it. +fn code_of(text: &str) -> String { + let code = barsql_sql::strip_leading_comments(text).trim_end(); + code.strip_suffix(';').unwrap_or(code).trim_end().to_string() +} + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum TxnState { #[default] @@ -154,6 +171,10 @@ pub enum QueryTabEvent { OpenTable { schema: String, table: String, filter: Option }, // Now runs on another database of its connection. Moved, + // The selection or the statement at the caret, in a new builder tab. + OpenBuilder, + // A builder tab's SQL, in a new SQL tab. + OpenSql(String), } #[derive(PartialEq)] @@ -183,6 +204,7 @@ pub struct QueryTab { marks: RangeDecorationCollection, marked: Option, graph: Option<(WeakEntity, [Subscription; 2])>, + builder: Option, flash_task: Task<()>, results: Entity, running: Option, @@ -219,7 +241,7 @@ pub fn new_tab_id() -> String { impl QueryTab { pub fn new(tab: EditorTab, connection: ConnectionConfig, window: &mut Window, cx: &mut Context) -> Self { - let sql = tab.sql; + let (sql, builder) = (tab.sql, tab.builder); let language = Rc::new(SqlLanguage::new(connection.id.clone(), connection.driver.clone())); let highlight = crate::syntax::sql_language(&connection.driver); let editor = cx.new(|cx| { @@ -264,11 +286,13 @@ impl QueryTab { this.let_go(cx); } this.schedule_diagnostics(window, cx); + this.reload_builder(cx); cx.emit(QueryTabEvent::Edited); } }), cx.observe(&editor, |this, editor, cx| { - if this.marked.is_some_and(|caret| caret != editor.read(cx).cursor()) { + let caret = editor.read(cx).cursor(); + if this.marked.is_some_and(|marked| marked != caret) { this.let_go(cx); } }), @@ -315,6 +339,7 @@ impl QueryTab { marks, marked: None, graph: None, + builder: None, flash_task: Task::ready(()), results, running: None, @@ -325,6 +350,10 @@ impl QueryTab { _subscriptions: subscriptions, }; this.schedule_diagnostics(window, cx); + if let Some(builder) = builder { + let places = builder.tables.into_iter().map(|t| (t.table, Place::new(t.x as f32 / 10., t.y as f32 / 10.))); + this.open_builder(places.collect(), builder.sql_view, window, cx); + } this } @@ -344,8 +373,33 @@ impl QueryTab { self.editor.read(cx).focus_handle(cx).contains_focused(window, cx) } + // A builder tab's canvas while it shows. pub fn focus_editor(&self, window: &mut Window, cx: &mut App) { - self.editor.update(cx, |state, cx| state.focus(window, cx)); + match self.canvas() { + Some(view) => window.focus(&view.read(cx).focus_handle(), cx), + None => self.editor.update(cx, |state, cx| state.focus(window, cx)), + } + } + + // Where the tab's keys go. + fn keys(&self, cx: &App) -> FocusHandle { + match self.canvas() { + Some(view) => view.read(cx).focus_handle(), + None => self.editor.read(cx).focus_handle(cx), + } + } + + pub fn is_builder(&self) -> bool { + self.builder.is_some() + } + + // The SQL in view: a SQL tab's, or a builder tab's in place of its canvas. + pub fn shows_sql(&self) -> bool { + self.canvas().is_none() + } + + fn canvas(&self) -> Option<&Entity> { + self.builder.as_ref().filter(|builder| !builder.sql_view).map(|builder| &builder.view) } pub fn insert(&self, text: &str, window: &mut Window, cx: &mut App) { @@ -372,6 +426,12 @@ impl QueryTab { table_view: None, diagram: None, structure: None, + builder: self.builder.as_ref().map(|builder| { + let tenths = |at: f32| (at * 10.).round() as i32; + let places = builder.view.read(cx).places().into_iter(); + let tables = places.map(|(table, at)| TablePlace { table, x: tenths(at.x), y: tenths(at.y) }).collect(); + BuilderRef { tables, sql_view: builder.sql_view } + }), // The workspace knows. pinned: false, } @@ -413,6 +473,11 @@ impl QueryTab { // Another id is another database of the same connection, so suggestions follow it. pub fn set_connection(&mut self, connection: ConnectionConfig, cx: &mut Context) { self.results.update(cx, |results, cx| results.set_connection(connection.clone(), cx)); + if let Some(builder) = &self.builder + && connection.driver == self.connection.driver + { + builder.view.update(cx, |view, cx| view.set_connection(connection.clone(), cx)); + } if connection.driver == self.connection.driver { if connection.id != self.connection.id { self.language.set_connection_id(connection.id.clone()); @@ -633,7 +698,9 @@ impl QueryTab { } fn suggest(&mut self, window: &mut Window, cx: &mut Context) { - self.completion.update(cx, |completion, cx| completion.request(true, window, cx)); + if self.shows_sql() { + self.completion.update(cx, |completion, cx| completion.request(true, window, cx)); + } } // Formats the whole text, undoably. @@ -718,6 +785,9 @@ impl QueryTab { window: &mut Window, cx: &mut Context, ) { + if self.canvas().is_some() { + self.show_builder_sql(true, window, cx); + } let Some(offset) = self.error_offset(statement, position, cx) else { self.focus_editor(window, cx); return; @@ -739,13 +809,16 @@ impl QueryTab { self.editor.update(cx, |state, cx| { state.set_selected_range(range, cx); state.replace(meant, window, cx); - state.focus(window, cx); }); + self.focus_editor(window, cx); self.refresh_diagnostics(cx); } // The selection, or with nothing selected the statement holding the caret, as DataGrip's Execute does. fn run_selection(&mut self, window: &mut Window, cx: &mut Context) { + if self.canvas().is_some() { + return self.run_all(window, cx); + } let state = self.editor.read(cx); let (selected, base) = (state.selected_text().to_string(), state.selected_range().start); if !selected.trim().is_empty() { @@ -1143,6 +1216,7 @@ impl QueryTab { let state = self.editor.read(cx); let selected = state.selected_text().to_string(); let (text, base) = match () { + _ if self.canvas().is_some() => (state.value().to_string(), 0), _ if !selected.trim().is_empty() => (selected, state.selected_range().start), _ => match self.statement_at_caret(cx) { Some((text, start)) => (text, start), @@ -1241,6 +1315,95 @@ impl QueryTab { }); } + // For a new builder tab: the selection, else the statement at the caret, or why the builder can't show it. + pub(crate) fn builder_source(&self, cx: &App) -> Result { + let selected = self.editor.read(cx).selected_text().to_string(); + let text = match selected.trim().is_empty() { + true => self.statement_at_caret(cx).map(|(text, _)| text).unwrap_or_default(), + false => selected, + }; + let sql = code_of(&text); + match design::import(&sql, &self.connection.driver, &|_| None) { + Ok(_) => Ok(sql), + Err(problem) => Err(query_builder::problem_text(&problem, &sql, cx)), + } + } + + fn open_builder( + &mut self, + places: Vec<(String, Place)>, + sql_view: bool, + window: &mut Window, + cx: &mut Context, + ) { + let (connection, text) = (self.connection.clone(), self.sql(cx).to_string()); + let view = cx.new(|cx| QueryBuilder::new(connection, places, cx)); + view.update(cx, |view, cx| view.load(&text, cx)); + let subscriptions = [ + cx.subscribe_in(&view, window, |this, _, event: &BuilderEvent, window, cx| match event { + BuilderEvent::Changed { base, sql } => this.write_builder(base, sql, window, cx), + BuilderEvent::Moved => cx.emit(QueryTabEvent::Edited), + BuilderEvent::EditSql => this.show_builder_sql(true, window, cx), + }), + // Its tools are in this tab's toolbar. + cx.observe(&view, |_, _, cx| cx.notify()), + ]; + self.builder = Some(Builder { view, sql_view, _subscriptions: subscriptions }); + self.editor.read(cx).focus_handle(cx).tab_stop(sql_view); + } + + pub(crate) fn add_builder_table(&mut self, schema: &str, table: &str, cx: &mut Context) { + if let Some(builder) = &self.builder { + builder.view.update(cx, |view, cx| view.add_table(schema, table, None, cx)); + } + } + + pub(crate) fn toggle_builder_view(&mut self, window: &mut Window, cx: &mut Context) { + let show = self.canvas().is_some(); + self.show_builder_sql(show, window, cx); + } + + // The canvas, redrawn from any edits to its SQL, or the SQL in its place. + pub(crate) fn show_builder_sql(&mut self, show: bool, window: &mut Window, cx: &mut Context) { + let Some(builder) = self.builder.as_mut().filter(|builder| builder.sql_view != show) else { return }; + builder.sql_view = show; + // Hidden on the canvas, the editor is no stop for Tab. + self.editor.read(cx).focus_handle(cx).tab_stop(show); + self.reload_builder(cx); + self.focus_editor(window, cx); + cx.emit(QueryTabEvent::Edited); + cx.notify(); + } + + // The canvas's Undo and Redo, for the editor, whose edits they are. + fn editor_action(&self, action: Box, window: &mut Window, cx: &mut Context) { + let focus = self.editor.read(cx).focus_handle(cx); + window.defer(cx, move |window, cx| focus.dispatch_action(action.as_ref(), window, cx)); + } + + // One edit to undo, over only the text it was made from. + fn write_builder(&mut self, base: &str, sql: &str, window: &mut Window, cx: &mut Context) { + if *self.sql(cx) != *base { + return; + } + let (end, sql) = (self.editor.read(cx).text().len(), sql.to_string()); + self.editor.update(cx, |state, cx| editor_commands::replace_range(state, 0..end, sql, window, cx)); + } + + // At once while the canvas shows, as Undo and Redo change the text under it; edits to the SQL view wait for it. + fn reload_builder(&mut self, cx: &mut Context) { + let Some(view) = self.canvas().cloned() else { return }; + let sql = self.sql(cx); + if view.read(cx).source() != &*sql { + view.update(cx, |view, cx| view.load(&sql, cx)); + } + } + + #[cfg(test)] + pub(crate) fn builder(&self) -> Option> { + self.builder.as_ref().map(|builder| builder.view.clone()) + } + fn explain_sql(&mut self, sql: String, analyze: bool, window: &mut Window, cx: &mut Context) { if self.running.is_some() { return; @@ -1278,37 +1441,24 @@ impl QueryTab { fn disk_bar(&self, cx: &mut Context) -> Option> { let changed = matches!(self.disk.as_ref()?, Disk::Changed(_)); - let theme = cx.theme().clone(); let message = t(cx, if changed { "editor.changedOnDisk" } else { "editor.goneFromDisk" }); - let bar = h_flex() - .debug_selector(|| "disk-changed".into()) - .flex_none() - .gap(rems(0.462)) - .px(rems(0.769)) - .py(rems(0.308)) - .bg(theme.warning.opacity(TINT)) - .border_b_1() - .border_color(theme.warning.opacity(TINT_BORDER)) - .text_size(TEXT_SM) - .child(Icon::new(IconName::TriangleAlert).size(ICON_XS).text_color(theme.warning)) - .child(div().flex_1().min_w_0().truncate().child(message)) - .when(changed, |bar| { - bar.child( - Button::new("disk-reload") - .debug_selector(|| "disk-reload".into()) - .small() - .label(t(cx, "editor.reloadFromDisk")) - .on_click(cx.listener(|this, _, window, cx| this.reload_from_disk(window, cx))), - ) - .child( - Button::new("disk-keep") - .debug_selector(|| "disk-keep".into()) - .small() - .ghost() - .label(t(cx, "editor.keepMine")) - .on_click(cx.listener(|this, _, _, cx| this.keep_mine(cx))), - ) - }); + let bar = form::warning_bar(message, cx).debug_selector(|| "disk-changed".into()).when(changed, |bar| { + bar.child( + Button::new("disk-reload") + .debug_selector(|| "disk-reload".into()) + .small() + .label(t(cx, "editor.reloadFromDisk")) + .on_click(cx.listener(|this, _, window, cx| this.reload_from_disk(window, cx))), + ) + .child( + Button::new("disk-keep") + .debug_selector(|| "disk-keep".into()) + .small() + .ghost() + .label(t(cx, "editor.keepMine")) + .on_click(cx.listener(|this, _, _, cx| this.keep_mine(cx))), + ) + }); Some(bar) } @@ -1329,44 +1479,46 @@ impl QueryTab { // while one is going. The transaction sits at the far end. fn toolbar(&self, cx: &mut Context) -> impl IntoElement { let theme = cx.theme().clone(); + let bar = h_flex() + .debug_selector(|| "query-toolbar".into()) + .flex_none() + .h(STRIP) + .px(STRIP_PAD) + .gap(rems(0.462)) + .bg(theme.sidebar) + .border_b_1() + .border_color(theme.border); + let divider = || div().flex_none().w(px(1.)).h(rems(1.231)).mx(rems(0.154)).bg(theme.border); + // A builder tab: Run and Explain, the switch between its canvas and its SQL, then that view's tools. + if self.builder.is_some() { + // The database and a transaction typed into the SQL view, before the canvas's own tools. + let picker = self.database_picker(cx); + let txn = (self.txn != TxnState::Idle).then(|| self.transaction_controls(cx).into_any_element()); + let mut lead = (picker.is_some() || txn.is_some()) + .then(|| h_flex().gap(rems(0.462)).children(picker).children(txn).into_any_element()); + let tools = match self.canvas().cloned() { + Some(view) => view.update(cx, |view, cx| view.tools(lead.take(), cx).into_any_element()), + None => self.sql_tools(cx).into_any_element(), + }; + return bar + .child(self.run_buttons(cx)) + .child(self.explain_button(cx)) + .child(divider()) + .child(self.view_switch(cx)) + .child(divider()) + .child(tools) + .children(lead); + } let linked = !self.saved_query_id.is_empty(); - let left = h_flex().gap(rems(0.462)); - let left = match self.running.is_some() { - true => left.child( - Button::new("stop") - .debug_selector(|| "stop".into()) - .danger() - .tool(Icon::new(Lucide::Square), ICON_XS, t(cx, "editor.stop")) - .tooltip(t(cx, "tooltip.stopQuery")) - .on_click(cx.listener(|this, _, _, cx| this.cancel(cx))), - ), - false => { - let selected = !self.editor.read(cx).selected_range().is_empty(); - let run = if selected { "tooltip.runSelection" } else { "tooltip.runStatementAtCaret" }; - left.child( - Button::new("run") - .debug_selector(|| "run".into()) - .primary() - .tool(Icon::new(Lucide::Play), ICON_XS, t(cx, "editor.run")) - .tooltip(hint(run, "runSelection", cx)) - .on_click(cx.listener(|this, _, window, cx| this.run_selection(window, cx))), - ) - .child( - Button::new("run-all") - .debug_selector(|| "run-all".into()) - .tool(Icon::new(Lucide::SkipForward), ICON_XS, t(cx, "editor.contextRunAll")) - .tooltip(hint("tooltip.runAll", "runAll", cx)) - .on_click(cx.listener(|this, _, window, cx| this.run_all(window, cx))), - ) - } - }; let (save, save_hint) = match linked { true => ("editor.update", "tooltip.updateSavedQuery"), false => ("editor.save", "tooltip.saveQuery"), }; - let left = left + let left = self + .run_buttons(cx) .child(self.explain_button(cx)) - .child(div().w(px(1.)).h(rems(1.231)).mx(rems(0.154)).bg(theme.border)) + .child(self.builder_button(cx)) + .child(divider()) .child(self.save_button(save, save_hint, cx)) .when(linked, |el| { el.child( @@ -1378,20 +1530,98 @@ impl QueryTab { .on_click(cx.listener(|this, _, window, cx| this.rename_saved(window, cx))), ) }); - h_flex() - .debug_selector(|| "query-toolbar".into()) - .flex_none() - .h(STRIP) - .px(rems(0.769)) - .gap(rems(0.462)) - .justify_between() - .bg(theme.sidebar) - .border_b_1() - .border_color(theme.border) + bar.justify_between() .child(left) .child(h_flex().gap(rems(0.462)).children(self.database_picker(cx)).child(self.transaction_controls(cx))) } + fn run_buttons(&self, cx: &mut Context) -> Div { + let buttons = h_flex().gap(rems(0.462)); + if self.running.is_some() { + return buttons.child( + Button::new("stop") + .debug_selector(|| "stop".into()) + .danger() + .tool(Icon::new(Lucide::Square), ICON_XS, t(cx, "editor.stop")) + .tooltip(t(cx, "tooltip.stopQuery")) + .on_click(cx.listener(|this, _, _, cx| this.cancel(cx))), + ); + } + let run = match () { + _ if self.canvas().is_some() => "queryBuilder.runTooltip", + _ if !self.editor.read(cx).selected_range().is_empty() => "tooltip.runSelection", + _ => "tooltip.runStatementAtCaret", + }; + buttons + .child( + Button::new("run") + .debug_selector(|| "run".into()) + .primary() + .tool(Icon::new(Lucide::Play), ICON_XS, t(cx, "editor.run")) + .tooltip(hint(run, "runSelection", cx)) + .on_click(cx.listener(|this, _, window, cx| this.run_selection(window, cx))), + ) + .when(self.builder.is_none(), |buttons| { + buttons.child( + Button::new("run-all") + .debug_selector(|| "run-all".into()) + .tool(Icon::new(Lucide::SkipForward), ICON_XS, t(cx, "editor.contextRunAll")) + .tooltip(hint("tooltip.runAll", "runAll", cx)) + .on_click(cx.listener(|this, _, window, cx| this.run_all(window, cx))), + ) + }) + } + + fn builder_button(&self, cx: &mut Context) -> impl IntoElement + use<> { + Button::new("open-builder") + .debug_selector(|| "open-builder".into()) + .tool(Icon::new(Lucide::Blocks), ICON_XS, t(cx, "queryBuilder.open")) + .tooltip(hint("queryBuilder.openTooltip", "openQueryBuilder", cx)) + .on_click(cx.listener(|_, _, _, cx| cx.emit(QueryTabEvent::OpenBuilder))) + } + + // A builder tab's canvas or its SQL. + fn view_switch(&self, cx: &mut Context) -> impl IntoElement + use<> { + let sql = self.shows_sql(); + let tip = hint("queryBuilder.switchTooltip", "openQueryBuilder", cx); + form::toggle_group() + .flex_none() + .child( + form::toggle_small("view-builder", t(cx, "queryBuilder.open"), !sql) + .debug_selector(|| "view-builder".into()) + .tooltip(tip.clone()) + .on_click(cx.listener(|this, _, window, cx| this.show_builder_sql(false, window, cx))), + ) + .child( + form::toggle_small("view-sql", t(cx, "queryBuilder.sqlView"), sql) + .debug_selector(|| "view-sql".into()) + .tooltip(tip) + .on_click(cx.listener(|this, _, window, cx| this.show_builder_sql(true, window, cx))), + ) + } + + fn sql_tools(&self, cx: &mut Context) -> impl IntoElement + use<> { + h_flex() + .flex_1() + .min_w_0() + .gap(rems(0.462)) + .child( + Button::new("copy-sql") + .debug_selector(|| "copy-sql".into()) + .tool(Icon::new(Lucide::Copy), ICON_XS, t(cx, "common.copy")) + .on_click(cx.listener(|this, _, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(this.sql(cx).to_string())); + toast::success(t(cx, "toast.copiedClipboard"), cx); + })), + ) + .child( + Button::new("open-sql") + .debug_selector(|| "open-sql".into()) + .tool(Icon::new(Lucide::SquarePen), ICON_XS, t(cx, "queryBuilder.openInEditor")) + .on_click(cx.listener(|this, _, _, cx| cx.emit(QueryTabEvent::OpenSql(this.sql(cx).to_string())))), + ) + } + // A linked tab's caret offers Save as. fn save_button(&self, label: &str, tooltip: &str, cx: &mut Context) -> impl IntoElement + use<> { let save = Button::new("save-query") @@ -1408,7 +1638,7 @@ impl QueryTab { self.split_button(save, "save-menu", t(cx, "editor.saveOptions"), false, items, cx) } - // The caret's items act on the editor. + // The caret's items act where the tab's keys go. fn split_button( &self, main: Button, @@ -1432,7 +1662,7 @@ impl QueryTab { .tooltip(tooltip) .disabled(disabled) .dropdown_menu(move |menu, _, cx| { - let focus = tab.upgrade().map(|tab| tab.read(cx).editor.read(cx).focus_handle(cx)); + let focus = tab.upgrade().map(|tab| tab.read(cx).keys(cx)); items(menu.when_some(focus, |menu, focus| menu.action_context(focus)), cx) }), ) @@ -1458,7 +1688,8 @@ impl QueryTab { } fn can_begin(&self) -> bool { - self.txn == TxnState::Idle + self.builder.is_none() + && self.txn == TxnState::Idle && !self.connection.read_only && self.connection.driver.capabilities().interactive_transactions } @@ -1599,6 +1830,7 @@ fn editor_menu( entries.push(Entry::item(t(cx, "editor.explainAnalyze"), ExplainAnalyze, false)); } entries.push(Entry::item(t(cx, "algebra.title"), ShowAlgebra, false)); + entries.push(Entry::item(t(cx, "queryBuilder.openInBuilder"), OpenQueryBuilder, false)); entries.extend([ Entry::Separator, Entry::item(t(cx, "editor.contextGoToDefinition"), GoToDefinition, false), @@ -1623,20 +1855,28 @@ fn editor_menu( impl Render for QueryTab { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let font_size = px(theme::editor_font_size(cx)); + let canvas = self.canvas().cloned(); + let (in_builder, on_canvas) = (self.builder.is_some(), canvas.is_some()); + let floor = editor_floor(cx); // Before the editor lays out this frame, so a new text size moves its text once. - sync_glyph_strip(&self.editor, window, cx); + if !on_canvas { + sync_glyph_strip(&self.editor, window, cx); + } v_flex() .size_full() .on_action(cx.listener(|this, _: &RunSelection, window, cx| this.run_selection(window, cx))) .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))) - .on_action(cx.listener(|this, _: &SaveQueryAs, window, cx| this.save_as(window, cx))) - .on_action(cx.listener(|this, _: &RenameSavedQuery, window, cx| this.rename_saved(window, cx))) + .on_action(cx.listener(|this, _: &ShowAlgebra, window, cx| this.show_algebra(window, cx))) + // A builder tab's SQL isn't saved. + .when(!in_builder, |el| { + el.on_action(cx.listener(|this, _: &SaveQuery, window, cx| this.save(window, cx))) + .on_action(cx.listener(|this, _: &SaveQueryAs, window, cx| this.save_as(window, cx))) + .on_action(cx.listener(|this, _: &RenameSavedQuery, window, cx| this.rename_saved(window, cx))) + }) // Only while they apply, so the command palette offers just these. .when(self.can_begin(), |el| { el.on_action(cx.listener(|this, _: &BeginTransaction, window, cx| { @@ -1651,12 +1891,16 @@ impl Render for QueryTab { this.transaction(TxnControl::Rollback, false, window, cx) })) }) - .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, window, cx| { let (bounds, y) = (event.bounds, event.event.position.y); if bounds.size.height > px(0.) { 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 rem = window.rem_size(); + let floor = match this.canvas().is_some() { + true => bounds.top() + STRIP.to_pixels(rem) + rem * CANVAS_FLOOR, + false => 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(); @@ -1665,31 +1909,63 @@ impl Render for QueryTab { .child(self.toolbar(cx)) .children(self.disk_bar(cx)) .child( - completion::handlers(editor_commands::handlers(div(), &self.editor, Some("-- ")), &self.completion) - .key_context(if self.completion.read(cx).is_open(cx) { COMPLETING_CONTEXT } else { EDITOR_CONTEXT }) - .debug_selector(|| "query-editor".into()) - .relative() + v_flex() + .debug_selector(|| "editor-region".into()) .flex_1() - .min_h(editor_floor(cx)) + .min_h(if on_canvas { window.rem_size() * CANVAS_FLOOR } else { floor }) + .children(canvas.map(|view| { + div() + .debug_selector(|| "builder-pane".into()) + .flex_1() + .min_h_0() + .on_action( + cx.listener(|this, _: &Undo, window, cx| { + this.editor_action(Box::new(Undo), window, cx) + }), + ) + .on_action( + cx.listener(|this, _: &Redo, window, cx| { + this.editor_action(Box::new(Redo), window, cx) + }), + ) + .child(view) + })) .child( - Editor::new(&self.editor) - .size_full() - .bordered(false) - .text_size(font_size) - .context_menu(editor_menu(self.editor.clone(), self.can_analyze())) - .on_paste({ - let editor = self.editor.clone(); - move |item, window, cx| { - let Some(text) = copy::aligned_text(item) else { return false }; - editor.update(cx, |editor, cx| editor.replace(text, window, cx)); - true - } - }) - .scrollbars_on_hover(), - ) - .child(self.run_glyphs(cx)) - .child(self.completion.clone()) - .child(self.hover.clone()), + completion::handlers( + editor_commands::handlers(div(), &self.editor, Some("-- ")), + &self.completion, + ) + .key_context(if self.completion.read(cx).is_open(cx) { + COMPLETING_CONTEXT + } else { + EDITOR_CONTEXT + }) + .debug_selector(|| "query-editor".into()) + .relative() + .map(|el| match on_canvas { + true => el.flex_none().h(px(0.)).overflow_hidden(), + false => el.flex_1().min_h(floor), + }) + .child( + Editor::new(&self.editor) + .size_full() + .bordered(false) + .text_size(font_size) + .context_menu(editor_menu(self.editor.clone(), self.can_analyze())) + .on_paste({ + let editor = self.editor.clone(); + move |item, window, cx| { + let Some(text) = copy::aligned_text(item) else { return false }; + editor.update(cx, |editor, cx| editor.replace(text, window, cx)); + true + } + }) + .scrollbars_on_hover(), + ) + .children((!on_canvas).then(|| self.run_glyphs(cx))) + .child(self.completion.clone()) + .child(self.hover.clone()), + ), ) .child( div() diff --git a/crates/barsql-ui/src/saved_panel.rs b/crates/barsql-ui/src/saved_panel.rs index bf3db7e..6a16aaf 100644 --- a/crates/barsql-ui/src/saved_panel.rs +++ b/crates/barsql-ui/src/saved_panel.rs @@ -52,7 +52,7 @@ struct SavedDrag(SavedQuery); impl Render for SavedDrag { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - list_nav::drag_chip(self.0.name.clone().into(), cx) + list_nav::drag_chip(SharedString::from(self.0.name.clone()), cx) } } diff --git a/crates/barsql-ui/src/scenarios/algebra.rs b/crates/barsql-ui/src/scenarios/algebra.rs index 0cb49a0..71e8735 100644 --- a/crates/barsql-ui/src/scenarios/algebra.rs +++ b/crates/barsql-ui/src/scenarios/algebra.rs @@ -36,6 +36,21 @@ fn explains_menu_and_a_shortcut_draw_the_graph_in_the_results(cx: &mut TestAppCo assert!(!app.cx.update(|_, cx| query.read(cx).marked()), "and its mark goes with it"); } +// A builder tab's Explain menu draws its whole query, and a pick marks it behind the canvas. +#[gpui_kit::test] +fn a_builder_tabs_explain_menu_draws_its_query(cx: &mut TestAppContext) { + let mut app = open(cx); + app.connect(); + app.set_sql(JOIN); + app.keys("mod-shift-b"); + let builder = app.tab(); + assert!(app.cx.update(|_, cx| builder.read(cx).is_builder()), "the statement went to a builder tab"); + app.menu_pick("explain-menu", 1); + assert!(app.shown("ra-node-0") && graph(&mut app).is_some(), "drawn in the builder tab's results"); + app.click("ra-node-1"); + assert!(app.cx.update(|_, cx| builder.read(cx).marked()), "the pick marks its SQL"); +} + // 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) { diff --git a/crates/barsql-ui/src/scenarios/editor.rs b/crates/barsql-ui/src/scenarios/editor.rs index 9f67f14..7d10ae6 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, 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); + // Run statement, Run all, Explain, Relational algebra, Open in builder, 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", 14); 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/engines.rs b/crates/barsql-ui/src/scenarios/engines.rs index e971723..ab615fa 100644 --- a/crates/barsql-ui/src/scenarios/engines.rs +++ b/crates/barsql-ui/src/scenarios/engines.rs @@ -23,9 +23,9 @@ use crate::schema_actions::Change; use crate::status_bar::server::Detail; use crate::table_tab::TableTab; -// In a table's menu, after Browse data, Edit structure, SELECT in new tab and Count rows. +// In a table's menu, after Browse data, Edit structure, SELECT in new tab, Open in builder and Count rows. const SELECT_IN_NEW_TAB: usize = 2; -const SYSTEM_VIEWS: usize = 4; +const SYSTEM_VIEWS: usize = 5; #[derive(Clone, Copy, PartialEq)] enum Engine { @@ -201,7 +201,7 @@ fn browse(app: &mut Driver, name: &str) { // Drop is a table menu's last item, one further down where the System views submenu comes first. fn drop_item(engine: Engine) -> usize { - 13 + usize::from(views(&engine.driver(), ViewScope::Table).next().is_some()) + 14 + usize::from(views(&engine.driver(), ViewScope::Table).next().is_some()) } fn label(app: &mut Driver, view: &SystemView) -> String { diff --git a/crates/barsql-ui/src/scenarios/import.rs b/crates/barsql-ui/src/scenarios/import.rs index 254086e..8c35874 100644 --- a/crates/barsql-ui/src/scenarios/import.rs +++ b/crates/barsql-ui/src/scenarios/import.rs @@ -6,7 +6,7 @@ use super::driver::{Driver, open}; use crate::file_dialogs::Stub; use crate::import_dialog::{ImportDialog, Opened, Shown}; -const IMPORT_INTO_TABLE: usize = 4; +const IMPORT_INTO_TABLE: usize = 5; fn dialog(app: &mut Driver) -> Entity { app.cx.update(|_, cx| cx.try_global::().and_then(|opened| opened.0.upgrade())).expect("the import dialog") diff --git a/crates/barsql-ui/src/scenarios/schema.rs b/crates/barsql-ui/src/scenarios/schema.rs index 317e11b..84b42f7 100644 --- a/crates/barsql-ui/src/scenarios/schema.rs +++ b/crates/barsql-ui/src/scenarios/schema.rs @@ -7,13 +7,13 @@ use crate::schema_tree::SchemaTree; // Table menu positions, counted from Browse data at 0. const SELECT_IN_NEW_TAB: usize = 2; -const COUNT_ROWS: usize = 3; -const BACKUP: usize = 5; -const COPY_DDL: usize = 6; -const OPEN_DDL: usize = 7; -const RENAME: usize = 11; -const TRUNCATE: usize = 12; -const DROP: usize = 13; +const COUNT_ROWS: usize = 4; +const BACKUP: usize = 6; +const COPY_DDL: usize = 7; +const OPEN_DDL: usize = 8; +const RENAME: usize = 12; +const TRUNCATE: usize = 13; +const DROP: usize = 14; // Column menus start with Insert name and Copy name. Object menus start with Copy DDL, Open DDL and Copy name. const COLUMN_INSERT: usize = 0; const COLUMN_RENAME: usize = 2; diff --git a/crates/barsql-ui/src/scenarios/structure.rs b/crates/barsql-ui/src/scenarios/structure.rs index 4cb8434..891bb00 100644 --- a/crates/barsql-ui/src/scenarios/structure.rs +++ b/crates/barsql-ui/src/scenarios/structure.rs @@ -12,7 +12,7 @@ use crate::workspace::QuitRequests; // Table menu positions, counted from Browse data at 0. const BROWSE: usize = 0; const EDIT_STRUCTURE: usize = 1; -const DROP_TABLE: usize = 13; +const DROP_TABLE: usize = 14; const COLUMN_RENAME: usize = 2; // The Columns grid's columns on SQLite. diff --git a/crates/barsql-ui/src/schema_tree.rs b/crates/barsql-ui/src/schema_tree.rs index 56e3949..eed5fa6 100644 --- a/crates/barsql-ui/src/schema_tree.rs +++ b/crates/barsql-ui/src/schema_tree.rs @@ -23,6 +23,7 @@ use gpui_kit::*; use crate::form::{LargeButton as _, ToolButton as _}; use crate::i18n::{I18n, bytes, count, t, t_count, t_with}; use crate::list_nav::{self, BarClearance, LIST_INSET}; +use crate::query_builder::TableDrag; use crate::schema::{self, Schemas}; use crate::schema_actions::{self, Applied, Change}; use crate::schema_objects::{ @@ -74,6 +75,8 @@ pub enum SchemaTreeEvent { Browse { schema: String, table: String }, // The ER diagram of a schema, in its own tab. OpenDiagram { schema: String }, + // A builder tab with the table on its canvas. + OpenBuilder { schema: String, table: String }, // A table's Structure tab, or a new table's without `table`. OpenStructure { schema: String, table: Option }, // SQL for another connection, like a schema comparison's sync script. Opens without running. @@ -158,6 +161,8 @@ pub struct SchemaTree { cursor: Option, keyed: bool, active_table: Option, + // Where a press on a table row began. + press: Option>, search_task: Task<()>, _subscriptions: Vec, } @@ -204,6 +209,7 @@ impl SchemaTree { cursor: None, keyed: false, active_table: None, + press: None, search_task: Task::ready(()), _subscriptions: subscriptions, } @@ -1006,6 +1012,7 @@ impl SchemaTree { run: false, }; let browse = SchemaTreeEvent::Browse { schema: schema_name.clone(), table: table.name.clone() }; + let build = SchemaTreeEvent::OpenBuilder { schema: schema_name.clone(), table: table.name.clone() }; let (schema, name) = (schema_name.clone(), table.name.clone()); let rename = Change::RenameTable { schema: schema.clone(), table: name.clone(), kind: kind.clone() }; let truncate = Change::Truncate { schema: schema.clone(), table: name.clone() }; @@ -1023,6 +1030,7 @@ impl SchemaTree { menu.item(PopupMenuItem::new(t(cx, "sidebar.browseData")).on_click(emit(browse))) .when(is_table, |menu| menu.item(PopupMenuItem::new(t(cx, structure_label)).on_click(emit(structure)))) .item(PopupMenuItem::new(t(cx, "sidebar.selectInNewTab")).on_click(emit(select))) + .item(PopupMenuItem::new(t(cx, "queryBuilder.openInBuilder")).on_click(emit(build))) .item(PopupMenuItem::new(t(cx, "sidebar.countRows")).on_click(count)) .when(table_views, |menu| menu.submenu(t(cx, "sidebar.systemViews"), window, cx, system_views)) .when(is_table, |menu| { @@ -1387,10 +1395,17 @@ impl SchemaTree { }); let menu = self.table_menu(schema.clone(), table.clone(), cx); let name = table.name.clone(); + let (jitter_schema, jitter_name) = (schema.clone(), name.clone()); let group = SharedString::from(format!("schema-table-{}-{}", schema, table.name)); let browse = self.browse_action(&schema, &table.name, group.clone(), ring, clearance, cx); + let drag = self.connection.as_ref().map(|c| TableDrag { + connection_id: c.id.clone(), + schema: schema.clone(), + table: table.name.clone(), + }); clickable(base) .group(group) + .when_some(drag, |el, drag| el.on_drag(drag, |drag, _, _, cx| cx.new(|_| drag.clone()))) .child(chevron(expanded, ICON_SM)) .child(Icon::new(relation_icon).size(ICON_SM).text_color(if relation_badge.is_some() { theme.primary @@ -1414,6 +1429,20 @@ impl SchemaTree { }) .child(browse) .on_click(cx.listener(move |this, _, _, cx| this.toggle_table(&schema, &name, cx))) + // A press that slipped into a drag is still a click. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, _, _| this.press = Some(event.position)), + ) + .on_mouse_up( + MouseButton::Left, + cx.listener(move |this, event: &MouseUpEvent, _, cx| { + let near = this.press.take().is_some_and(|at| (event.position - at).magnitude() < 6.); + if near && cx.has_active_drag() { + this.toggle_table(&jitter_schema, &jitter_name, cx); + } + }), + ) .context_menu(menu) .into_any_element() } diff --git a/crates/barsql-ui/src/schema_tree/tests.rs b/crates/barsql-ui/src/schema_tree/tests.rs index 0b2e13f..a88aa5d 100644 --- a/crates/barsql-ui/src/schema_tree/tests.rs +++ b/crates/barsql-ui/src/schema_tree/tests.rs @@ -449,3 +449,18 @@ fn a_click_selects_a_column_and_its_menu_inserts_the_name(cx: &mut TestAppContex cx.run_until_parked(); assert_eq!(*inserted.borrow(), ["name"]); } + +// A press that slips a few pixels starts a drag, and letting go on the row still opens it. +#[gpui_kit::test] +fn a_click_that_slips_a_little_still_opens_the_table(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tree, cx) = open(&env, cx); + connect(&tree, cx); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let row = cx.debug_bounds("tree:t:main.things").expect("the table's row is drawn").center(); + let slipped = row + gpui_kit::point(gpui_kit::px(3.), gpui_kit::px(1.)); + cx.simulate_mouse_down(row, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_move(slipped, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_up(slipped, MouseButton::Left, Modifiers::default()); + settle(cx, has(&tree, "c:main.things.name")); +} diff --git a/crates/barsql-ui/src/shortcuts.rs b/crates/barsql-ui/src/shortcuts.rs index f197a30..24194d4 100644 --- a/crates/barsql-ui/src/shortcuts.rs +++ b/crates/barsql-ui/src/shortcuts.rs @@ -9,7 +9,8 @@ use crate::state::{set_setting, setting}; // In a Binding, `ctrl` means Cmd on macOS. pub const OVERRIDES_KEY: &str = "barsql-shortcut-overrides"; -const EDITOR_CONTEXT: &str = "QueryEditor > Input"; +// The SQL editor, and a builder tab's canvas. +const EDITOR_CONTEXT: &str = "(QueryEditor > Input) || QueryBuilder"; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Binding { @@ -70,6 +71,7 @@ impl ShortcutDef { "explainQuery" => Box::new(ExplainQuery), "explainAnalyze" => Box::new(ExplainAnalyze), "showAlgebra" => Box::new(ShowAlgebra), + "openQueryBuilder" => Box::new(OpenQueryBuilder), "saveQuery" => Box::new(SaveQuery), "saveQueryAs" => Box::new(SaveQueryAs), "renameSavedQuery" => Box::new(RenameSavedQuery), @@ -114,7 +116,7 @@ const VIEW: Category = Category::View; const GLOBAL: Scope = Scope::Global; const EDITOR: Scope = Scope::Editor; -pub const SHORTCUTS: [ShortcutDef; 23] = [ +pub const SHORTCUTS: [ShortcutDef; 24] = [ def("quickSearch", TABS, GLOBAL, "p", CTRL), def("commandPalette", VIEW, GLOBAL, "p", CTRL_SHIFT), def("runSelection", QUERY, EDITOR, "Enter", CTRL), @@ -123,6 +125,7 @@ pub const SHORTCUTS: [ShortcutDef; 23] = [ // 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("openQueryBuilder", QUERY, GLOBAL, "b", CTRL_SHIFT), def("saveQuery", QUERY, EDITOR, "s", CTRL), def("saveQueryAs", QUERY, EDITOR, "s", CTRL_SHIFT), def("renameSavedQuery", QUERY, EDITOR, "F2", NONE), @@ -171,12 +174,24 @@ pub fn effective(def: &ShortcutDef, cx: &App) -> Binding { effective_in(def, &read_overrides(cx)) } -fn effective_in(def: &ShortcutDef, overrides: &Overrides) -> Binding { +fn saved(id: &str, overrides: &Overrides) -> Option { overrides - .get(def.id) + .get(id) .and_then(|value| serde_json::from_value::(value.clone()).ok()) .filter(|binding| !binding.key.is_empty()) - .unwrap_or_else(|| def.default_binding()) +} + +// A default another shortcut saved stays unset, so a new default never takes keys someone chose. +fn effective_in(def: &ShortcutDef, overrides: &Overrides) -> Binding { + if let Some(binding) = saved(def.id, overrides) { + return binding; + } + let default = def.default_binding(); + let key = binding_key(&default); + let taken = SHORTCUTS.iter().any(|other| { + other.id != def.id && saved(other.id, overrides).is_some_and(|binding| binding_key(&binding) == key) + }); + if taken { Binding::default() } else { default } } pub fn set_binding(id: &str, binding: &Binding, cx: &mut App) { diff --git a/crates/barsql-ui/src/shortcuts/tests.rs b/crates/barsql-ui/src/shortcuts/tests.rs index e93b6f6..e7b05ad 100644 --- a/crates/barsql-ui/src/shortcuts/tests.rs +++ b/crates/barsql-ui/src/shortcuts/tests.rs @@ -6,7 +6,7 @@ use super::{ Binding, SHORTCUTS, binding_from_keystroke, binding_key, effective, find, find_conflict, format_binding, keystrokes, reset_all, reset_binding, set_binding, }; -use crate::actions::{QuickSearch, ZoomIn}; +use crate::actions::{OpenQueryBuilder, QuickSearch, ZoomIn}; use crate::test_support::Env; fn binding(key: &str, ctrl: bool, shift: bool, alt: bool) -> Binding { @@ -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(), 23); + assert_eq!(SHORTCUTS.len(), 24); } #[test] @@ -111,3 +111,23 @@ fn overrides_rebuild_the_keymap_and_resets_restore_the_defaults(cx: &mut TestApp let zoom = cx.update(|cx| cx.key_bindings().borrow().bindings_for_action(&ZoomIn).count()); assert!(zoom >= 2, "= and its + alias"); } + +#[gpui_kit::test] +fn a_default_another_shortcut_saved_stays_unset(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let builder = find("openQueryBuilder").unwrap(); + let bound = |cx: &mut TestAppContext| { + cx.update(|cx| cx.key_bindings().borrow().bindings_for_action(&OpenQueryBuilder).count()) + }; + assert!(bound(cx) > 0); + + cx.update(|cx| set_binding("commandPalette", &binding("B", true, true, false), cx)); + assert_eq!(cx.update(|cx| effective(builder, cx)), Binding::default()); + assert_eq!(bound(cx), 0, "Ctrl+Shift+B stays the palette's"); + let conflict = cx.update(|cx| find_conflict("quickSearch", &builder.default_binding(), cx).map(|d| d.id)); + assert_eq!(conflict, Some("commandPalette")); + + cx.update(|cx| reset_binding("commandPalette", cx)); + assert_eq!(cx.update(|cx| effective(builder, cx)), binding("b", true, true, false)); + assert!(bound(cx) > 0); +} diff --git a/crates/barsql-ui/src/shortcuts_dialog.rs b/crates/barsql-ui/src/shortcuts_dialog.rs index 0aa20cb..346d283 100644 --- a/crates/barsql-ui/src/shortcuts_dialog.rs +++ b/crates/barsql-ui/src/shortcuts_dialog.rs @@ -46,7 +46,7 @@ impl ShortcutsDialog { fn apply(&mut self, id: &str, binding: &Binding, cx: &mut Context) { if let Some(conflict) = shortcuts::find_conflict(id, binding, cx) { - self.error = Some(t_with(cx, "shortcuts.conflict", &[("label", &conflict.label(cx))])); + self.error = Some(taken_by(conflict, cx)); cx.notify(); return; } @@ -54,6 +54,13 @@ impl ShortcutsDialog { self.stop(cx); } + // The default stays unset while another shortcut holds its keys. + fn reset(&mut self, def: &ShortcutDef, cx: &mut Context) { + shortcuts::reset_binding(def.id, cx); + self.error = shortcuts::find_conflict(def.id, &def.default_binding(), cx).map(|other| taken_by(other, cx)); + cx.notify(); + } + fn stop(&mut self, cx: &mut Context) { self.recording = None; self.error = None; @@ -78,11 +85,7 @@ impl ShortcutsDialog { el.child( Button::new(SharedString::from(format!("reset-{}", def.id))) .tool_label(t(cx, "shortcuts.reset")) - .on_click(cx.listener(move |this, _, _, cx| { - shortcuts::reset_binding(def.id, cx); - this.error = None; - cx.notify(); - })), + .on_click(cx.listener(move |this, _, _, cx| this.reset(def, cx))), ) }) .child( @@ -160,6 +163,10 @@ impl Render for ShortcutsDialog { } } +fn taken_by(other: &ShortcutDef, cx: &App) -> SharedString { + t_with(cx, "shortcuts.conflict", &[("label", &other.label(cx))]) +} + pub fn open(window: &mut Window, cx: &mut App) -> Entity { let view = cx.new(|_| ShortcutsDialog::new()); let dialog = view.clone(); diff --git a/crates/barsql-ui/src/shortcuts_dialog/tests.rs b/crates/barsql-ui/src/shortcuts_dialog/tests.rs index 4a9af5b..a91397b 100644 --- a/crates/barsql-ui/src/shortcuts_dialog/tests.rs +++ b/crates/barsql-ui/src/shortcuts_dialog/tests.rs @@ -62,3 +62,18 @@ fn a_taken_combination_is_refused_and_escape_cancels(cx: &mut TestAppContext) { assert!(cx.update(gpui_kit::component::WindowExt::has_active_dialog), "Esc cancelled only the recording"); assert_eq!(quick_search(cx), Binding { key: "p".into(), ctrl: true, ..Default::default() }); } + +#[gpui_kit::test] +fn resetting_a_default_another_shortcut_holds_names_it(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let (dialog, cx) = dialog(cx); + let palette = Binding { key: "b".into(), ctrl: true, shift: true, alt: false }; + cx.update(|_, cx| shortcuts::set_binding("commandPalette", &palette, cx)); + let builder = shortcuts::find("openQueryBuilder").unwrap(); + dialog.update(cx, |dialog, cx| dialog.reset(builder, cx)); + let error = cx.update(|_, cx| dialog.read(cx).error.clone()); + assert_eq!(error.as_deref(), Some("Already used by “Command palette”. Choose a different combination.")); + + dialog.update(cx, |dialog, cx| dialog.reset(shortcuts::find("quickSearch").unwrap(), cx)); + assert_eq!(cx.update(|_, cx| dialog.read(cx).error.clone()), None); +} diff --git a/crates/barsql-ui/src/sidebar.rs b/crates/barsql-ui/src/sidebar.rs index 6ea4786..86e082c 100644 --- a/crates/barsql-ui/src/sidebar.rs +++ b/crates/barsql-ui/src/sidebar.rs @@ -53,6 +53,7 @@ pub enum SidebarEvent { OpenQuery { connection: ConnectionConfig, sql: String, title: String, run: bool }, Browse { connection: ConnectionConfig, schema: String, table: String }, OpenDiagram { connection: ConnectionConfig, schema: String }, + OpenBuilder { connection: ConnectionConfig, schema: String, table: String }, // No `table` for a new one. OpenStructure { connection: ConnectionConfig, schema: String, table: Option }, // SQL from history. Goes into the connection's plain query tab. @@ -116,6 +117,10 @@ impl Sidebar { let Some(connection) = this.selected() else { return }; SidebarEvent::OpenDiagram { connection, schema: schema.clone() } } + SchemaTreeEvent::OpenBuilder { schema, table } => { + let Some(connection) = this.selected() else { return }; + SidebarEvent::OpenBuilder { connection, schema: schema.clone(), table: table.clone() } + } SchemaTreeEvent::OpenStructure { schema, table } => { let Some(connection) = this.selected() else { return }; SidebarEvent::OpenStructure { connection, schema: schema.clone(), table: table.clone() } diff --git a/crates/barsql-ui/src/test_support.rs b/crates/barsql-ui/src/test_support.rs index ec7edc8..6696976 100644 --- a/crates/barsql-ui/src/test_support.rs +++ b/crates/barsql-ui/src/test_support.rs @@ -76,6 +76,7 @@ impl Env { schema_tree::init(cx); list_nav::init(cx); crate::editor_commands::init(cx); + crate::query_builder::init(cx); crate::completion::init(cx); shortcuts::init(cx); }); diff --git a/crates/barsql-ui/src/tokens.rs b/crates/barsql-ui/src/tokens.rs index 90a7796..851b5f7 100644 --- a/crates/barsql-ui/src/tokens.rs +++ b/crates/barsql-ui/src/tokens.rs @@ -24,6 +24,8 @@ pub const RADIUS_LG: Rems = rems(0.615); // under them is a STRIP. pub const TOP_BAR: Rems = rems(2.769); pub const STRIP: Rems = rems(3.077); +// A strip's padding at either end. +pub const STRIP_PAD: Rems = rems(0.769); // A connection's state beside its name, and smaller marks like an unsaved tab's. pub const DOT: Rems = rems(0.538); diff --git a/crates/barsql-ui/src/workspace.rs b/crates/barsql-ui/src/workspace.rs index b561f4b..0bcaa3f 100644 --- a/crates/barsql-ui/src/workspace.rs +++ b/crates/barsql-ui/src/workspace.rs @@ -5,7 +5,7 @@ use std::collections::HashSet; use std::rc::Rc; use barsql_app::{ - AppEvent, DiagramRef, EditorSession, EditorTab, StructureRef, TableViewRef, Unsaved, is_sqlite_file, + AppEvent, BuilderRef, DiagramRef, EditorSession, EditorTab, StructureRef, TableViewRef, Unsaved, is_sqlite_file, sqlite_file_payload, }; use barsql_core::capabilities::DefaultSchema; @@ -82,6 +82,11 @@ impl TabView { } } + // A query tab with SQL to edit, not a builder. + fn editor(&self, cx: &App) -> Option<&Entity> { + self.query().filter(|tab| !tab.read(cx).is_builder()) + } + fn id(&self, cx: &App) -> String { match self { Self::Query(tab) => tab.read(cx).id.clone(), @@ -184,6 +189,7 @@ impl TabView { fn icon(&self, cx: &App) -> Lucide { match self { + Self::Query(tab) if tab.read(cx).is_builder() => Lucide::Blocks, Self::Query(tab) if tab.read(cx).saved_query_id().is_empty() => Lucide::File, Self::Query(tab) if saved_queries::folder_of(tab.read(cx).saved_query_id()).is_some() => Lucide::Users, Self::Query(_) => Lucide::Bookmark, @@ -584,7 +590,7 @@ impl Workspace { SidebarEvent::Selected(connection) => this.focus_or_open_tab(connection.clone(), window, cx), SidebarEvent::Insert(text) => this.insert_into_editor(text, window, cx), SidebarEvent::OpenQuery { connection, sql, title, run } => { - this.open_query_tab_with(connection.clone(), sql.clone(), title.clone().into(), window, cx); + this.open_query_tab_with(connection.clone(), sql.clone(), title.clone().into(), None, window, cx); if *run && let Some(tab) = this.active_query().cloned() { tab.update(cx, |tab, cx| tab.run_all(window, cx)); } @@ -597,6 +603,12 @@ impl Workspace { SidebarEvent::OpenDiagram { connection, schema } => { this.open_diagram(connection.clone(), schema.clone(), window, cx) } + SidebarEvent::OpenBuilder { connection, schema, table } => { + this.open_numbered(connection.clone(), String::new(), Some(BuilderRef::default()), window, cx); + if let Some(tab) = this.active_query().cloned() { + tab.update(cx, |tab, cx| tab.add_builder_table(schema, table, cx)); + } + } SidebarEvent::OpenStructure { connection, schema, table } => { this.open_structure(connection.clone(), schema.clone(), table.clone(), window, cx) } @@ -903,6 +915,11 @@ impl Workspace { self.active_tab().and_then(TabView::query) } + // The active tab while it shows SQL: a query tab, or a builder tab's SQL view. + fn active_sql_tab(&self, cx: &App) -> Option> { + self.active_query().filter(|tab| tab.read(cx).shows_sql()).cloned() + } + // Observes the tabs that can hold a draft. Only the one that changed is asked again. fn tab_changed(&mut self, view: Entity, cx: &mut Context) { let id = view.entity_id(); @@ -1018,6 +1035,11 @@ impl Workspace { this.sidebar.update(cx, |sidebar, cx| sidebar.set_selected(&id, cx)); } } + QueryTabEvent::OpenBuilder => this.open_in_builder(window, cx), + QueryTabEvent::OpenSql(sql) => { + let connection = view.read(cx).connection.clone(); + this.open_numbered(connection, sql.clone(), None, window, cx); + } }), ]; self.tabs.push(OpenTab { view: TabView::Query(view), pinned, _subscriptions: subscriptions }); @@ -1268,21 +1290,58 @@ impl Workspace { cx.notify(); } - fn next_query_number(&self, connection_id: &str, cx: &App) -> usize { + // SQL tabs and builder tabs count apart. + fn next_query_number(&self, connection_id: &str, builder: bool, cx: &App) -> usize { self.query_tabs() .iter() .filter(|tab| { let tab = tab.read(cx); - scope::same_connection(&tab.connection.id, connection_id) && tab.saved_query_id().is_empty() + scope::same_connection(&tab.connection.id, connection_id) + && tab.saved_query_id().is_empty() + && tab.is_builder() == builder }) .count() + 1 } fn open_query_tab(&mut self, connection: ConnectionConfig, window: &mut Window, cx: &mut Context) { - let num = self.next_query_number(&connection.id, cx).to_string(); - let title = t_with(cx, "app.queryTabWithConn", &[("num", &num), ("conn", &connection.name)]); - self.open_query_tab_with(connection, String::new(), title, window, cx); + self.open_numbered(connection, String::new(), None, window, cx); + } + + // "Query N" or, with `builder`, "Builder N" on the connection. + fn open_numbered( + &mut self, + connection: ConnectionConfig, + sql: String, + builder: Option, + window: &mut Window, + cx: &mut Context, + ) { + let num = self.next_query_number(&connection.id, builder.is_some(), cx).to_string(); + let key = if builder.is_some() { "app.builderTabWithConn" } else { "app.queryTabWithConn" }; + let title = t_with(cx, key, &[("num", &num), ("conn", &connection.name)]); + self.open_query_tab_with(connection, sql, title, builder, window, cx); + } + + // A builder tab swaps its view; else a new builder takes the active SQL tab's statement, or starts empty. + fn open_in_builder(&mut self, window: &mut Window, cx: &mut Context) { + if let Some(tab) = self.active_query().filter(|tab| tab.read(cx).is_builder()).cloned() { + return tab.update(cx, |tab, cx| tab.toggle_builder_view(window, cx)); + } + let (connection, sql) = match self.active_tab() { + Some(tab) => match tab.editor(cx).map(|query| query.read(cx)) { + Some(query) => (query.connection.clone(), query.builder_source(cx)), + None => (tab.connection(cx).clone(), Ok(String::new())), + }, + None => match self.sidebar.read(cx).selected() { + Some(connection) => (connection, Ok(String::new())), + None => return, + }, + }; + match sql { + Ok(sql) => self.open_numbered(connection, sql, Some(BuilderRef::default()), window, cx), + Err(reason) => toast::error(reason, cx), + } } // History entries reuse the connection's plain query tab while it's empty or still shows the last entry @@ -1291,7 +1350,7 @@ impl Workspace { let prefix = t(cx, "app.queryTabPrefix"); let last = self.history_shown.clone(); let existing = self.tabs.iter().position(|tab| { - tab.view.query().is_some_and(|tab| { + tab.view.editor(cx).is_some_and(|tab| { let tab = tab.read(cx); let current = tab.sql(cx); tab.connection.id == connection.id @@ -1308,9 +1367,9 @@ impl Workspace { self.activate(ix, window, cx); return; } - let num = self.next_query_number(&connection.id, cx).to_string(); + let num = self.next_query_number(&connection.id, false, cx).to_string(); let title = t_with(cx, "app.queryTab", &[("num", &num)]); - self.open_query_tab_with(connection, sql.clone(), title, window, cx); + self.open_query_tab_with(connection, sql.clone(), title, None, window, cx); self.history_shown = self.active_query().map(|tab| (tab.read(cx).id.clone(), sql)); } @@ -1322,7 +1381,7 @@ impl Workspace { let order = saved_queries::open_order(&saved, saved_queries::folders(cx), preferred); let connection = order.iter().find_map(|id| sidebar.connection(id)); let Some(connection) = connection else { return }; - let query = |ix: usize| self.tabs[ix].view.query().map(|tab| tab.read(cx)); + let query = |ix: usize| self.tabs[ix].view.editor(cx).map(|tab| tab.read(cx)); let found = (0..self.tabs.len()) .find(|&ix| query(ix).is_some_and(|tab| tab.saved_query_id() == saved.id)) .or_else(|| { @@ -1374,6 +1433,7 @@ impl Workspace { connection: ConnectionConfig, sql: String, title: SharedString, + builder: Option, window: &mut Window, cx: &mut Context, ) { @@ -1383,19 +1443,21 @@ impl Workspace { title: title.to_string(), sql, color: connection.color.clone(), + builder, ..Default::default() }; self.add_tab(tab, connection, window, cx); self.activate(self.tabs.len() - 1, window, cx); } - // Into the active query tab, or with a table view or nothing open, into the connection's plain query tab. + // Into the SQL in view, or with none, into the connection's plain query tab. fn insert_into_editor(&mut self, text: &str, window: &mut Window, cx: &mut Context) { - if self.active_query().is_none() + let active = |this: &Self, cx: &App| this.active_sql_tab(cx); + if active(self, cx).is_none() && let Some(connection) = self.sidebar.read(cx).selected() { let plain = self.tabs.iter().position(|tab| { - tab.view.query().is_some_and(|tab| { + tab.view.editor(cx).is_some_and(|tab| { let tab = tab.read(cx); tab.connection.id == connection.id && tab.saved_query_id().is_empty() }) @@ -1405,7 +1467,7 @@ impl Workspace { None => self.open_query_tab(connection, window, cx), } } - if let Some(tab) = self.active_query().cloned() { + if let Some(tab) = active(self, cx) { tab.update(cx, |tab, cx| tab.insert(text, window, cx)); } } @@ -1415,7 +1477,7 @@ impl Workspace { return; } let plain = |tab: &OpenTab| { - tab.view.query().is_some_and(|tab| { + tab.view.editor(cx).is_some_and(|tab| { let tab = tab.read(cx); tab.connection.id == connection.id && tab.saved_query_id().is_empty() }) @@ -1792,16 +1854,14 @@ impl Workspace { self.activate(ix, window, cx); } - // A new plain query tab with the same SQL, on the same connection. + // A copy on the same connection, a builder's keeping its cards' places. fn duplicate_tab(&mut self, id: &str, window: &mut Window, cx: &mut Context) { let Some(view) = self.index_of(id, cx).and_then(|ix| self.tabs[ix].view.query().cloned()) else { return }; - let (connection, sql) = { + let (connection, stored) = { let tab = view.read(cx); - (tab.connection.clone(), tab.sql(cx).to_string()) + (tab.connection.clone(), tab.stored(cx)) }; - let num = self.next_query_number(&connection.id, cx).to_string(); - let title = t_with(cx, "app.queryTabWithConn", &[("num", &num), ("conn", &connection.name)]); - self.open_query_tab_with(connection, sql, title, window, cx); + self.open_numbered(connection, stored.sql, stored.builder, window, cx); } fn cycle_tab(&mut self, forward: bool, window: &mut Window, cx: &mut Context) { @@ -2366,7 +2426,7 @@ impl Workspace { false => AiAccess::Read, }), transaction, - caret: query.filter(|_| grid.is_none()).map(|tab| tab.caret(cx)), + caret: query.filter(|tab| grid.is_none() && tab.shows_sql()).map(|tab| tab.caret(cx)), aggregate: grid.and_then(|grid| grid.read(cx).aggregate()), live, sidebar_open: self.sidebar_open, @@ -2388,7 +2448,7 @@ impl Workspace { }; let query = self.active_tab().and_then(TabView::query); StatusActions { - go_to_line: query.map(|_| on(Self::go_to_line)), + go_to_line: query.filter(|tab| tab.read(cx).shows_sql()).map(|_| on(Self::go_to_line)), switch_connection: Some(on(Self::open_switcher)), edit_connection: self.active_tab().map(|_| on(Self::edit_tab_connection)), stop: query.filter(|tab| tab.read(cx).is_running()).map(|_| on(Self::stop_run)), @@ -2406,7 +2466,7 @@ impl Workspace { } fn go_to_line(&mut self, window: &mut Window, cx: &mut Context) { - if let Some(tab) = self.active_tab().and_then(TabView::query).cloned() { + if let Some(tab) = self.active_sql_tab(cx) { tab.update(cx, |tab, cx| tab.go_to_line(window, cx)); } } @@ -2521,7 +2581,7 @@ impl Workspace { window: &mut Window, cx: &mut Context, ) { - self.open_query_tab_with(connection, sql.to_string(), title.to_string().into(), window, cx); + self.open_query_tab_with(connection, sql.to_string(), title.to_string().into(), None, window, cx); } pub(crate) fn close_active(&mut self, window: &mut Window, cx: &mut Context) { @@ -2669,6 +2729,7 @@ impl Render for Workspace { window.refresh(); })) .on_action(cx.listener(|this, _: &NewTab, window, cx| this.new_tab(window, cx))) + .on_action(cx.listener(|this, _: &OpenQueryBuilder, window, cx| this.open_in_builder(window, cx))) .when(self.structure_target(cx).is_some(), |el| { el.on_action(cx.listener(|this, _: &EditTableStructure, window, cx| { if let Some((connection, schema, table)) = this.structure_target(cx) { diff --git a/crates/barsql-ui/src/workspace/tests.rs b/crates/barsql-ui/src/workspace/tests.rs index e7cadc8..61bfa0f 100644 --- a/crates/barsql-ui/src/workspace/tests.rs +++ b/crates/barsql-ui/src/workspace/tests.rs @@ -11,12 +11,13 @@ use gpui_kit::{ use super::Workspace; use crate::actions::{ToggleEnterAcceptsSuggestions, ToggleJsonPanel, ToggleSidebar}; -use crate::query_tab::{QueryTab, TxnState}; +use crate::query_tab::{QueryTab, QueryTabEvent, TxnState}; use crate::saved_queries; use crate::schema_actions::{Applied, Change, Options}; use crate::schema_tree::TableChange; +use crate::sidebar::SidebarEvent; use crate::test_support::{Env, settle}; -use crate::window_state; +use crate::{toast, window_state}; fn tab(id: &str, connection_id: &str, sql: &str) -> EditorTab { EditorTab { @@ -482,6 +483,67 @@ fn history_sql_lands_in_the_plain_query_tab(cx: &mut TestAppContext) { assert_eq!((count, kept.as_str()), (2, "SELECT 2 -- mine")); } +fn shown(tab: &Entity, cx: &mut VisualTestContext) -> (String, String, bool) { + cx.update(|_, cx| { + let tab = tab.read(cx); + (tab.title.to_string(), tab.sql(cx).to_string(), tab.is_builder()) + }) +} + +// Mod+Shift+B copies a SQL tab's statement into a builder tab; Insert and Open in editor go to SQL tabs. +#[gpui_kit::test] +fn the_builder_opens_in_a_tab_of_its_own(cx: &mut TestAppContext) { + let env = Env::new(cx); + let id = env.connection.id.clone(); + let session = EditorSession { tabs: vec![tab("a", &id, "SELECT name FROM things")], active_tab: "a".into() }; + env.bar.save_editor_session(session).unwrap(); + let (workspace, cx) = open(cx); + cx.run_until_parked(); + let sql_tab = active(&workspace, cx); + let shortcut = format!("{}-shift-b", modifier()); + cx.update(|window, cx| sql_tab.update(cx, |tab, cx| tab.focus_editor(window, cx))); + cx.simulate_keystrokes(&shortcut); + cx.run_until_parked(); + let builder = active(&workspace, cx); + assert_eq!(shown(&builder, cx), ("Builder 1 · Local".into(), "SELECT name FROM things".into(), true)); + assert_eq!(shown(&sql_tab, cx).1, "SELECT name FROM things", "the SQL tab keeps its statement"); + cx.simulate_keystrokes(&shortcut); + cx.run_until_parked(); + let sql = cx.update(|_, cx| builder.read(cx).shows_sql()); + assert!(sql && active(&workspace, cx) == builder, "in a builder tab it shows the SQL"); + cx.simulate_keystrokes(&shortcut); + cx.run_until_parked(); + assert!(!cx.update(|_, cx| builder.read(cx).shows_sql()), "and the canvas again"); + workspace.update_in(cx, |ws, window, cx| ws.insert_into_editor("things", window, cx)); + assert_eq!(active(&workspace, cx), sql_tab, "Insert goes to a SQL tab"); + builder.update(cx, |_, cx| cx.emit(QueryTabEvent::OpenSql("SELECT 2".into()))); + cx.run_until_parked(); + let opened = active(&workspace, cx); + assert_eq!(shown(&opened, cx), ("Query 2 · Local".into(), "SELECT 2".into(), false), "numbered among SQL tabs"); + opened.update_in(cx, |tab, window, cx| tab.set_sql("SELECT 1 UNION SELECT 2".into(), window, cx)); + cx.update(|window, cx| opened.update(cx, |tab, cx| tab.focus_editor(window, cx))); + let before = cx.update(|_, cx| workspace.read(cx).tabs.len()); + cx.simulate_keystrokes(&shortcut); + cx.run_until_parked(); + assert_eq!(cx.update(|_, cx| workspace.read(cx).tabs.len()), before, "a UNION opens nothing"); + let toasts = cx.update(|_, cx| toast::messages(cx)); + assert!(toasts.iter().any(|(_, message)| message.contains("UNION")), "{toasts:?}"); +} + +#[gpui_kit::test] +fn a_table_from_the_tree_opens_a_builder_tab_on_it(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (workspace, cx) = open(cx); + cx.run_until_parked(); + let sidebar = cx.update(|_, cx| workspace.read(cx).sidebar.clone()); + let event = + SidebarEvent::OpenBuilder { connection: env.connection.clone(), schema: "main".into(), table: "things".into() }; + sidebar.update(cx, |_, cx| cx.emit(event)); + cx.run_until_parked(); + let builder = active(&workspace, cx); + assert_eq!(shown(&builder, cx), ("Builder 1 · Local".into(), "SELECT *\nFROM things".into(), true)); +} + #[gpui_kit::test] fn panel_widths_come_back_no_narrower_than_their_least_and_drags_store_them(cx: &mut TestAppContext) { let env = Env::new(cx); diff --git a/guide/README.md b/guide/README.md index 4839c4e..3b604a0 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, the relational algebra graph, saved queries and history | +| [🧠 SQL Editor](editor.md) | Autocomplete, multiple cursors, scripts, transactions, the query plan viewer, the relational algebra graph, query builder tabs, 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 389f996..de1285b 100644 --- a/guide/app.md +++ b/guide/app.md @@ -29,6 +29,7 @@ The in-app shortcuts editor remaps all of these except the editor's own keys: go | Explain query plan | `Ctrl/⌘ + Shift + E` | | Explain query plan (analyze) | `Ctrl/⌘ + Shift + A` | | Relational algebra graph | `Ctrl/⌘ + Shift + R` | +| Query builder (or its SQL) | `Ctrl/⌘ + Shift + B` | | 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 c8cf67a..b17eb78 100644 --- a/guide/editor.md +++ b/guide/editor.md @@ -23,9 +23,10 @@ - **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 +- **Query builder tabs** (`Ctrl/⌘+Shift+B`) - 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, **relational algebra**, go to definition, **change all occurrences**, toggle comment and **format SQL** +- Right-click menu with run, explain, **relational algebra**, **open in builder**, go to definition, **change all occurrences**, toggle comment and **format SQL** - **Remappable keyboard shortcuts** ## 🧭 Query Plan Viewer @@ -47,7 +48,7 @@ Plans are outputs like any other, so a script can mix them freely - `SELECT …; ## 🧮 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. +**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. On a builder tab's canvas it draws the whole query. 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. @@ -58,6 +59,21 @@ Tables sit along the bottom, and each operator above what it reads: ⋈ joins, - **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 Builder + +**Builder** on the toolbar (`Ctrl/⌘+Shift+B`, also in the right-click menu) opens the selection, or the statement under the cursor, in a **builder tab** of its own: its tables as cards, its joins as lines between their columns, and what it picks, filters, groups and sorts in a panel beside them. It's a copy - the query tab keeps its SQL, and neither changes the other after. With nothing there, or from another kind of tab, it opens an empty builder, and **Open in builder** in a table's right-click menu starts one with that table. + +**Builder | SQL** on a builder tab's toolbar (or `Ctrl/⌘+Shift+B` there) swaps the canvas for the query's SQL, to read or edit, with **Copy** and **Open in editor**, which puts it in a new query tab to save. Edits redraw the canvas when you switch back; SQL it can't show greys it out and says why, with **Edit SQL** to fix it. On the canvas, **Run**, **Explain** and **Relational algebra** take the whole query, with the results below as in a query tab, and Undo (`Ctrl/⌘+Z`) steps back through your changes, edits to the SQL included. + +- **Add tables** by dragging them from the schema tree onto the canvas, or from **Add table**. A table with a foreign key to one already there joins it on that key +- **Pick columns** by clicking them; with none picked it's `*`. Drag a column onto another table's column to join on them, and click a join's label to make it `LEFT`, `RIGHT` or `FULL`, or to remove it +- **Compact cards** - a table read from the SQL lists its keys and the columns the query uses; the row under them lists the rest, or fewer again. One you add lists every column +- **Right-click a column** to aggregate it (`COUNT`, `COUNT DISTINCT`, `SUM`, `AVG`, `MIN`, `MAX`), sort by it or filter on it. An aggregate groups by the other picked columns +- **The panel** lists the picked columns in order (drag to reorder) with their aggregates and names, then `DISTINCT`, the filters (a column, an operator and a value, or any SQL condition), the grouping and its group filters, the sort, and how many rows to return and skip. Values are SQL, so text goes in quotes +- **Each engine's own SQL** - names are quoted only where they need it, and the rows to return become `LIMIT` and `OFFSET`, or `TOP` and `OFFSET … FETCH` on SQL Server +- **Reads what you write** - a `SELECT` with its joins, `WHERE`, `GROUP BY`, `HAVING`, `ORDER BY` and limit comes apart onto the canvas, and expressions it doesn't take apart keep their SQL. A statement it can't show, like a `UNION`, a `WITH` or a subquery in `FROM`, says why and opens no tab. Comments inside the statement are dropped once the builder rewrites it +- Drag a card by its header to move it, or let **Arrange** lay them out; zoom and pan as in the ER diagram. Drag the panel's edge to widen it (a double-click puts it back), or hide it to give the canvas its room. A builder tab comes back with its cards where you left them, on the view it showed + ## 📚 Query Library & History - **Saved queries** - name, filter, sort, link tabs with dirty-state tracking