//! A connection and everything it owns: the profile, its session, and the tabs //! and objects open inside it. //! //! The editor, results, explorer and query state live here rather than on //! `Workspace` deliberately (spec §3.1). A profile is replaced wholesale when //! the connection changes, so a buffer written against one database cannot be //! retargeted at another -- it does not exist outside its profile. //! //! These were plain types at the crate root. They moved out whole; nothing //! changed but their visibility. use std::{ collections::{BTreeMap, HashMap, HashSet}, ops::Range, path::{Path, PathBuf}, rc::Rc, sync::{ Arc, Mutex, PoisonError, atomic::{AtomicBool, AtomicU64, Ordering}, }, }; use gpui::{App, AppContext, Context, Entity, SharedString, Window}; use gpui_component::{ input::{CompletionProvider, EditorState, InputEvent, InputState}, resizable::ResizableState, table::TableState, tree::{TreeEvent, TreeState}, }; use crate::{ Workspace, completion, db::{ CancelToken, Catalog, Connection, ConnectionConfig, Databases, DbError, Engine, ExplainMode, Levels, QueryResult, Relation, RelationKind, Routine, Row, Structure, Syntax, Target, }, explain::{self, Plan, analysis::Analysis}, explorer::{ ExplorerLeaf, Member, ObjectKind, ObjectRef, Pin, Shortcut, ShortcutDatabase, Shortcuts, }, filter::{ Conjunction, FilterBar, FilterRow, applied_filters, filter_bars, restored_filter, stored_filter, }, import_rows, result_grid, result_grid::{InsertTarget, NewValue, ResultGrid}, sidebar::OPEN_ROWS_CAP, sql::{self, Destructive, Mode, SortKey, Verdict}, sql_file, store, structure_grid::StructureGrid, theme::ConnectionColor, ui::row_readout, workspace::SchemaExportDialog, }; /// A connection and everything it owns. /// /// The editor, results, explorer and query state live here rather than on /// `Workspace` deliberately (spec §3.1). A profile is replaced wholesale when /// the connection changes, so a buffer written against one database cannot be /// retargeted at another — it does not exist outside its profile. pub(crate) struct Profile { pub(crate) id: String, pub(crate) name: String, pub(crate) config: ConnectionConfig, pub(crate) color: Option, pub(crate) mode: Mode, /// Whether an agent may reach this connection. Off for every profile that /// exists before its owner says otherwise. Read from `profiles.toml` only /// at load, and written only by `Workspace::set_agent_visible`. pub(crate) agent_visible: bool, pub(crate) confirmed: Vec, /// Whether this connection has silenced the prompt before editing rows /// restored from an earlier session. Stored as [`STALE_ROWS`] among /// `confirmed`'s slugs, which a build without it drops as unknown. pub(crate) confirmed_stale: bool, pub(crate) generation: u64, pub(crate) state: ProfileState, pub(crate) cleanup_attempt: Option, /// Whether the server is known to hold this connection as `mode` says /// (`Connection::set_read_only`): set when a connect lands, which fails /// rather than open unheld, and by the latest hold `set_mode` sent, once /// it lands. Cleared while one is on its way or after one failed. pub(crate) held: bool, pub(crate) holds: Arc, /// Whether the user's statements on this connection have left a /// transaction open (`sql::Leaves`), which a fresh one opened for a /// queue's reads would not see. Read off what was sent, not asked of the /// server; cleared by a `COMMIT` or `ROLLBACK`, and on connect. pub(crate) in_transaction: bool, /// Whether each of the user's statements commits on its own. Off means /// dbdelve keeps a transaction open for them, opening it by writing a /// `BEGIN` into the buffer where they can read it -- never onto the wire /// unseen (`AGENTS.md` hard rule 1). Per connection, and off again on /// connect, because the transaction it was holding died with the session. pub(crate) auto_commit: bool, /// Whether they have changed the session in a way that lasts as long as /// it does -- a `SET`, `USE` or temporary table. Cleared on connect. pub(crate) session_changed: bool, pub(crate) catalog: CatalogState, /// The generation a schema refresh was started on. Compared rather than /// cleared, so a reconnect that drops the refresh's answer takes the /// refresh with it. pub(crate) schema_refresh: Option, /// What the server listed the last time Select Database asked. pub(crate) databases: Databases, /// The session opened for each other database of the server, by name, /// for the connections tree to read its catalog over. Never the profile's /// own connection, and dropped with it. pub(crate) bound: HashMap, /// What each other database's catalog has got to, by name. A database /// with no entry has not been asked for. pub(crate) database_catalogs: HashMap, /// Whether the connection opened on another database than the one the /// tabs were opened on, because the picked one was no longer there. What /// is left of that database goes on the next frame, which has the window /// a connect does not, as on a switch. pub(crate) left_database: bool, /// The explorer's folders and pins. pub(crate) shortcuts: Shortcuts, /// Whether the user left each of the explorer's top-level rows open, by /// row id (`store::StoredProfile::folds`). pub(crate) folds: BTreeMap, /// The rows of the connections tree this profile has open, and the rows /// of it that are selected, by row id: what `profiles.toml` holds between /// runs. Complex mode only. A row listed here whose subtree has not /// loaded waits for it; the tree owns a row once it holds it. pub(crate) open_rows: Vec, pub(crate) selected_rows: Vec, /// The `.sql` files last opened or saved here, newest first /// ([`remember_recent`]), and those of them found gone at the last look, /// which the Files group greys. pub(crate) recent_files: Vec, pub(crate) missing_files: HashSet, /// Bumped whenever the recent files or what is known of one changes, so a /// look that set out before lands on nothing ([`Self::take_missing`]). pub(crate) recent_generation: u64, pub(crate) session: Session, } /// Orders `set_mode`'s holds, which go out on tasks nothing else orders and /// meet on a connection mutex that is not first come, first served: each /// takes its turn here, and one a newer hold has overtaken is skipped rather /// than land after it and leave the session held the opposite way. #[derive(Default)] pub(crate) struct HoldLine { latest: AtomicU64, turn: Mutex<()>, } impl HoldLine { /// Stamps a new hold, overtaking every one stamped before it. pub(crate) fn stamp(&self) -> u64 { self.latest.fetch_add(1, Ordering::SeqCst) + 1 } pub(crate) fn is_latest(&self, stamp: u64) -> bool { self.latest.load(Ordering::SeqCst) == stamp } /// Sends the hold stamped `stamp` unless a newer one has been stamped /// since; `Ok(false)` when it was skipped. pub(crate) fn send( &self, stamp: u64, hold: impl FnOnce() -> Result<(), DbError>, ) -> Result { let _turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); if !self.is_latest(stamp) { return Ok(false); } hold().map(|()| true) } } /// Whether `Settings::run_unreadable` lets a statement dbdelve cannot parse /// skip the run-once prompt: only one the user just asked to run, and in /// Read-only only once the server's hold is known to be in place. With no /// prompt left, that hold is all that stands between such a statement and a /// write. pub(crate) fn skips_run_once(opted_in: bool, own_run: bool, mode: Mode, held: bool) -> bool { opted_in && own_run && (mode != Mode::ReadOnly || held) } /// See [`Profile::shortcut_database`]. The shown catalog's own word comes /// first: a `USE` of the user's can move the session it was read on without /// the profile hearing of it, and a shortcut names what the sidebar shows. fn shortcut_database( target: Target, shown: Option<&Catalog>, active: impl FnOnce() -> Option, ) -> ShortcutDatabase { if !target.catalog_is_per_database() { return ShortcutDatabase::Unnamed; } shown .and_then(|catalog| catalog.database.clone()) .or_else(active) .map_or(ShortcutDatabase::Unknown, ShortcutDatabase::On) } /// See [`Profile::explorer_opens_on`]. fn explorer_opens_on( target: Target, active_schema: Option<&str>, database: impl FnOnce() -> Option, ) -> Option { match active_schema { Some(schema) => Some(schema.to_string()), None if target.catalog_lists_databases() => database(), None => None, } } impl Profile { /// The schema the sidebar starts with open (`explorer::root_folds`): the /// active one, or where the catalog lists each database as a schema, the /// database the connection is on. Gated rather than matched by name /// alone, so a schema that happens to share the database's name elsewhere /// is not taken for it. pub(crate) fn explorer_opens_on(&self) -> Option { explorer_opens_on(self.config.target(), self.active_schema(), || { self.active_database() }) } /// Why a queue of reads on this connection runs in turn rather than at /// once, said to the user when one does. pub(crate) fn in_turn(&self) -> Option<&'static str> { if self.in_transaction { Some("Ran one at a time: a transaction is open on this connection.") } else if self.session_changed { Some("Ran one at a time: this connection's session settings were changed.") } else { None } } /// The schema unqualified names resolve in first, where the engine has /// one to pick: until one is picked, the one the server put the session /// in. None where nothing is picked and the server named none, or wasn't /// asked, rather than a guess at its default. pub(crate) fn active_schema(&self) -> Option<&str> { if !self.config.target().picks_schema() { return None; } let current = match &self.state { ProfileState::Connected(connection) => connection.current_schema(), _ => None, }; self.config.schema().or(current) } /// The schema the session is in, for a list of schemas to open on. pub(crate) fn schema_in(&self) -> Option { let connected = match &self.state { ProfileState::Connected(connection) => connection.current_schema(), _ => None, }; schema_in( self.config.target(), self.active_schema(), self.active_database(), connected, ) } /// The database the connection is on: as last listed, else as the /// server spelled it on connecting, else as the profile names it, else /// the one it opened on. The server's spelling before the profile's, so /// a folder names the database as the list will once it comes. pub(crate) fn active_database(&self) -> Option { let connection = match &self.state { ProfileState::Connected(connection) => Some(connection), _ => None, }; self.databases .current .clone() .or_else(|| connection?.spelled_database().map(str::to_string)) .or_else(|| self.config.database_name()) .or_else(|| connection?.current_database().map(str::to_string)) } /// The database a folder or a pin names its objects by, where the /// catalog is one database's. Where it lists every database as a schema, /// none: keying on the one the session is on would hide every shortcut /// after a switch, though the catalog still lists them all. pub(crate) fn shortcut_database(&self) -> ShortcutDatabase { let shown = match &self.catalog { CatalogState::Loaded(catalog, _) => Some(catalog), _ => None, }; shortcut_database(self.config.target(), shown, || self.active_database()) } /// The sidebar row of the tab in front: its object's, its saved query's /// or its file's. A scratch query has none, and nor has an object the /// catalog does not list. pub(crate) fn front_row(&self) -> Option { match self.session.active_object() { // Listed under its own database, not under the connection's. Some(tab) if tab.database.is_some() => None, Some(tab) => match &self.catalog { CatalogState::Loaded(catalog, _) => { crate::explorer::object_row(catalog, &tab.schema, &tab.name, tab.kind?) } _ => None, }, None => { let tab = self.session.active_query_tab()?; match self.session.saved_query_of(tab) { Some(name) => Some(crate::explorer::query_row(name)), None => Some(crate::explorer::file_row(&tab.file.as_ref()?.path)), } } } } /// What the sidebar's Files group lists besides the saved queries: the /// recent files, then any file open in a tab they no longer hold. A saved /// query's file is listed as the query, so not here. pub(crate) fn recent_files_changed(&mut self) { self.recent_generation += 1; } /// What a look that set out at `generation` found gone, taken only if /// nothing has changed since: a stale look would grey a file opened or /// saved after it set out. pub(crate) fn take_missing(&mut self, generation: u64, gone: HashSet) { if let Some(missing) = still_missing(generation, self.recent_generation, gone, &self.recent_files) { self.missing_files = missing; } } pub(crate) fn listed_files(&self) -> Vec { let mut listed: Vec = Vec::new(); let open = self .session .queries .iter() .filter_map(|tab| Some(&tab.file.as_ref()?.path)); for path in self.recent_files.iter().chain(open) { if !listed.contains(path) && path.parent() != Some(&self.session.query_directory) { listed.push(path.clone()); } } listed } /// How far the catalog an object of `database` is looked up in has got: /// the one read for that database, or the profile's own when there is /// none. A database nothing has asked for is still loading. pub(crate) fn catalog_state_of(&self, database: Option<&str>) -> &CatalogState { static NOT_READ: CatalogState = CatalogState::Loading; match database { Some(database) => self.database_catalogs.get(database).unwrap_or(&NOT_READ), None => &self.catalog, } } /// The loaded catalog behind [`Profile::catalog_state_of`], if it is. pub(crate) fn catalog_of(&self, database: Option<&str>) -> Option<&Catalog> { match self.catalog_state_of(database) { CatalogState::Loaded(catalog, _) => Some(catalog), _ => None, } } /// The row of the object tab in front when it is of another database, /// with that database, found in the catalog read for it. pub(crate) fn front_row_elsewhere(&self) -> Option<(&str, String)> { let tab = self.session.active_object()?; let database = tab.database.as_deref()?; match self.database_catalogs.get(database)? { CatalogState::Loaded(catalog, _) => { let row = crate::explorer::object_row(catalog, &tab.schema, &tab.name, tab.kind?)?; Some((database, row)) } _ => None, } } pub(crate) fn refreshing_schema(&self) -> bool { self.schema_refresh == Some(self.generation) } /// Whether this profile's schemas can be drawn. Asked of the live /// connection, because a plugin draws only once it offered `graph`, /// which its target cannot know; a built-in answers by its target, /// connected or not. pub(crate) fn draws_diagrams(&self) -> bool { let target = self.config.target(); match &self.state { ProfileState::Connected(connection) => connection.draws_diagrams(target), _ => target.draws_diagrams(), } } /// Every session open for another database, which a read-only hold has /// to reach as well as the profile's own connection. A session still /// opening is not here; its landing applies the hold itself. pub(crate) fn sessions_to_hold(&self) -> Vec> { self.bound .values() .filter_map(|session| match session { BoundSession::Open(bound) => Some(bound.clone()), BoundSession::Opening => None, }) .collect() } /// Whether `session` is still the one registered for `database`. One /// that was lost and replaced since has nothing left to say about it. pub(crate) fn is_registered(&self, database: &str, session: &Arc) -> bool { matches!( self.bound.get(database), Some(BoundSession::Open(open)) if Arc::ptr_eq(open, session) ) } /// Take out `session`, found lost, while it is still the one registered /// for `database`, so the next read or run opens another. A replacement /// registered since is left alone. pub(crate) fn lose_session(&mut self, database: &str, session: &Arc) { if self.is_registered(database, session) { self.bound.remove(database); } } /// Let go of every session opened for another database, and what was read /// over them: the connection they were opened from has ended or been /// replaced, and a landing issued to it is dropped by its generation. /// /// The schema export's dialog goes with them: its tick list and the keys /// it read are the connection's being dropped, and its reads under the old /// generation are dropped when they land, which would leave it reading /// forever. A disconnect, a reconnect and a database switch all come here. /// /// ponytail: a session lives as long as its connection and ends with /// nothing else, so a server with many databases expanded holds one /// session each until it disconnects. The upgrade is to close one when /// the last tab bound to it is gone and its row is folded. pub(crate) fn drop_sessions(&mut self) { self.bound.clear(); self.database_catalogs.clear(); self.session.schema_export = None; } /// Why an edit under `binding` is not sent, as far as is known before it /// goes ([`Bound::write_refusal`]); [`Bound::edit`] asks again once it is /// the edit's turn on the session. pub(crate) fn bound_write_refusal(&self, binding: &Binding) -> Option { match self.bound.get(&binding.database) { Some(BoundSession::Open(bound)) => bound.write_refusal(&binding.database), _ => None, } } /// Whether a transaction the user opened is open on the session `tab`'s /// statements run on, which a verified apply's own `BEGIN` and `COMMIT` /// would end: the profile's own for a tab of its database, the bound /// session's for a tab bound to another. pub(crate) fn transaction_open_for(&self, tab: Tab) -> bool { match self.binding_of(tab) { Some(binding) => self.bound_write_refusal(&binding).is_some(), None => self.in_transaction, } } /// The connection a Cancel for `tab` is sent over: the session its /// statement runs on, which for a bound tab is not the profile's own. What /// MongoDB keeps of a running statement, and ClickHouse's fallback, is on /// that session and nowhere else. pub(crate) fn connection_to_stop(&self, tab: Tab) -> Option { self.connection_for(tab).existing().cloned() } /// Where a run of `tab` goes. See [`Profile::route`]. pub(crate) fn connection_for(&self, tab: Tab) -> Routed { self.route(self.binding_of(tab)) } /// The binding `tab` runs under: a bound query tab's own, or, for an /// object tab of another database, that database alone -- its statements /// name their schema, so there is none to pick. pub(crate) fn binding_of(&self, tab: Tab) -> Option { match tab { Tab::Query(query) => self.session.query_tab(query)?.binding.clone(), Tab::Object(object) => self .session .objects .iter() .find(|tab| tab.id == object)? .database .clone() .map(|database| Binding { database, schema: None, }), } } /// The connection a run under `binding` goes to: the profile's own when /// there is none, else the session open for its database, else what is /// needed to open one. The one place a tab's database picks a session. pub(crate) fn route(&self, binding: Option) -> Routed { let Some(own) = self.connection() else { return Routed::Unavailable; }; let Some(binding) = binding else { return Routed::Own(own); }; match self.bound.get(&binding.database) { Some(BoundSession::Open(session)) => Routed::Bound { session: session.clone(), schema: binding.schema, }, _ => Routed::Open { from: own, database: binding.database, schema: binding.schema, read_only: self.mode == Mode::ReadOnly, }, } } pub(crate) fn connection(&self) -> Option { match &self.state { ProfileState::Connected(connection) => Some((**connection).clone()), _ => None, } } pub(crate) fn stored(&self, cx: &gpui::App) -> store::StoredProfile { let engine = self.config.engine(); // Tabs read back from disk that the catalog has not named yet are still // the truth about this profile: writing the live list instead would // drop every restored object the first time anything else is saved. let active = self.session.active; let mut open_objects = self .session .objects .iter() .map(|tab| store::StoredObject { active: active == Tab::Object(tab.id), ..tab.stored(engine, cx) }) .collect::>(); // Both lists, because a restore now opens the relations first and // leaves the routines pending: writing either one alone would drop the // other half of the session. open_objects.extend(self.session.pending_objects.iter().cloned()); // A file engine writes no server fields and a server engine writes no // path, rather than either writing a blank the loader would have to // decide the meaning of. let server = self.config.server(); let password_command = server.and_then(|server| server.password_command.as_ref()); let snowflake = match &self.config { ConnectionConfig::Snowflake(account) => Some(account), _ => None, }; let mongo = match &self.config { ConnectionConfig::MongoDb(mongo) => Some(mongo), _ => None, }; let external = match &self.config { ConnectionConfig::External(external) => Some(external), _ => None, }; store::StoredProfile { id: self.id.clone(), name: self.name.clone(), host: server .map(|server| server.host.clone()) .or_else(|| snowflake.and_then(|account| account.host.clone())) .unwrap_or_default(), port: server.and_then(|server| server.port), database: self.config.database().unwrap_or_default().to_string(), user: server .map(|server| server.user.clone()) .or_else(|| snowflake.map(|account| account.user.clone())) .or_else(|| external.map(|external| external.user.clone())) .unwrap_or_default(), sslmode: server.map(|server| server.sslmode.as_str().to_string()), root_certificate: server.and_then(|server| server.root_certificate.clone()), service: self.config.service().map(str::to_string), // A plugin profile's engine is the plugin, and its dialect is // `speaks`: `engine()` answers with the dialect. engine: Some(match external { Some(external) => format!("{}{}", store::PLUGIN_TAG, external.plugin.id).into(), None => engine.as_str().into(), }), speaks: external.map(|external| external.speaks.as_str().to_string()), connection: external.map(|external| external.connection.clone()), path: match &self.config { ConnectionConfig::Sqlite { path, .. } | ConnectionConfig::Turso { path, .. } | ConnectionConfig::DuckDb { path, .. } => Some(path.clone()), _ => None, }, account: snowflake.map(|account| account.account.clone()), private_key: snowflake.map(|account| account.private_key.clone()), warehouse: snowflake.and_then(|account| account.warehouse.clone()), role: snowflake.and_then(|account| account.role.clone()), srv: mongo.map(|mongo| mongo.srv), options: mongo.map(|mongo| mongo.options.clone()), login_database: mongo.and_then(|mongo| mongo.login_database.clone()), schema: self.config.schema().map(str::to_string), // App-wide now, in `[settings]`. Kept on the stored shape and left // unwritten so the value an older build put here is still there for // the migration to read on the next upgrade. editor_font_size: None, statement_timeout: Some(self.config.statement_timeout()), password_command: password_command.map(|command| command.command.clone()), password_expires: password_command.map(|command| command.expires), next_query_id: Some(self.session.next_query_id), color: self.color.map(|color| color.slug().to_string()), mode: Some(self.mode.slug().to_string()), agent_visible: self.agent_visible, confirmed: self .confirmed .iter() .map(|kind| kind.slug()) .chain(self.confirmed_stale.then_some(STALE_ROWS)) .map(str::to_string) .collect(), // Nothing writes the legacy scalar any more; a buffer's name is a // property of its tab now. Kept on the stored shape only so a // profile written by an older build still loads with its buffer. open_query: None, ssm: self.config.ssm().cloned(), open_rows: self.open_rows.iter().take(OPEN_ROWS_CAP).cloned().collect(), selected_rows: self .selected_rows .iter() .take(OPEN_ROWS_CAP) .cloned() .collect(), recent_files: self.recent_files.clone(), ssh: self.config.ssh().cloned(), open_queries: self .session .queries .iter() .map(|tab| tab.stored(self.session.active == Tab::Query(tab.id))) .collect(), open_objects, folders: self .shortcuts .folders .iter() .map(|folder| store::StoredFolder { name: folder.name.clone(), members: folder.members.iter().map(stored_member).collect(), }) .collect(), pins: self .shortcuts .pins .iter() .map(|pin| match pin { Pin::Member(member) => stored_member(member), Pin::Folder(name) => store::StoredShortcut { folder: Some(name.clone()), ..Default::default() }, }) .collect(), folds: self.folds.clone(), } } } fn stored_member(member: &Member) -> store::StoredShortcut { match member { Member::Query(name) => store::StoredShortcut { query: Some(name.clone()), ..Default::default() }, Member::Object(object) => store::StoredShortcut { database: object.database.clone(), schema: Some(object.schema.clone()), name: Some(object.name.clone()), kind: Some(object.kind.slug().to_string()), ..Default::default() }, } } fn restored_member(stored: &store::StoredShortcut) -> Option { if let Some(name) = &stored.query { return Some(Member::Query(name.clone())); } Some(Member::Object(ObjectRef { database: stored.database.clone(), schema: stored.schema.clone()?, name: stored.name.clone()?, kind: ObjectKind::from_slug(stored.kind.as_deref()?)?, })) } /// A profile's folders and pins as read back, less any entry this build /// cannot read and any that repeats one before it, which a hand-edited file /// can hold and the tree cannot: an id may be in it once. pub(crate) fn restored_shortcuts( folders: &[store::StoredFolder], pins: &[store::StoredShortcut], ) -> Shortcuts { let mut shortcuts = Shortcuts::default(); for folder in folders { if shortcuts.add_folder(folder.name.trim()).is_err() { continue; } let name = folder.name.trim(); for member in folder.members.iter().filter_map(restored_member) { if !shortcuts.holds(name, &member) { shortcuts.toggle(name, member); } } } for stored in pins { let pin = match &stored.folder { Some(name) if shortcuts.folder(name.trim()).is_some() => { Pin::Folder(name.trim().to_string()) } Some(_) => continue, None => match restored_member(stored) { Some(member) => Pin::Member(member), None => continue, }, }; if !shortcuts.pinned(&pin) { shortcuts.toggle_pin(pin); } } shortcuts } pub(crate) enum ProfileState { Idle, Connecting { _attempt: crate::db::ConnectGuard }, // Boxed: a server profile's `ssh` tunnel made `Connection` far larger than // `Failed`'s `String`, and this variant is the one every idle profile pays // for. Connected(Box), Failed(String), } /// The per-profile view state. /// /// Separate from `Profile` only because GPUI entities need a `&mut Window` to /// create, and the connection resolves on a task that has none — so this is /// built before the spawn and moved in once the connection opens. pub(crate) struct Session { /// The open query buffers, in strip order. Empty when the last one has been /// closed; `active` may then name a tab that no longer exists, which every /// lookup by id already answers with `None`. pub(crate) queries: Vec, pub(crate) objects: Vec, pub(crate) active: Tab, /// The order the strip was last left in, by a drag or by a tab opening at /// its end. Chips it does not mention -- every tab restored at launch, /// until either happens -- follow it, in their default order. pub(crate) tab_order: Vec, pub(crate) next_query_id: u64, pub(crate) next_object_id: u64, /// Object tabs read back from disk, held until the catalog can name them. pub(crate) pending_objects: Vec, /// What completion has learned about this connection's columns. /// /// Not in the catalog, deliberately: fetching every column of every /// relation at connect is unbounded work for a database nobody has asked a /// question about yet. A relation lands here the first time a statement /// names it, so what is held is bounded by what was written. pub(crate) completion_columns: completion::ColumnCache, /// What every editor on this connection completes from, as /// `Workspace::install_completions` last built it. Kept for a filter bar /// turned raw after that, which completes from the same one. pub(crate) completions: Option>, pub(crate) explorer_filter: Entity, pub(crate) explorer_tree: Entity, pub(crate) explorer_leaves: Arc>, /// The matched characters of each row's name, by tree item id, as /// [`crate::explorer::ExplorerTree::highlights`] built them. pub(crate) explorer_highlights: Arc>>>, pub(crate) explorer_shortcuts: Arc>, /// `cmd+enter` reaches the workspace only through the focused element's /// dispatch path, so an unfocused editor makes the primary keystroke dead. pub(crate) editor_needs_focus: bool, /// Every query file this profile has, open in a tab or not: what the /// sidebar's Files group and the palette list. pub(crate) saved_queries: Vec, /// Where those files are, resolved as a file tab's path is, so a tab on /// one can be told by its path. pub(crate) query_directory: PathBuf, /// The statements this profile has run, newest first, each with what is /// known of its last run. Held rather than read off disk when the palette /// opens, for the reason `saved_queries` is: the list is wanted while a /// list is being built, which is a frame. pub(crate) history: Vec, /// The page in front, and where to jump to once it is typed over: see /// `sync_page_input`. One field for the window, because only the relation /// in front can be paged. pub(crate) page_input: Entity, /// The page last written into `page_input`, to tell a page that moved /// from one that is being typed over. pub(crate) page_shown: usize, /// The saved query the delete dialog is asking about. pub(crate) pending_delete: Option, /// The sidebar row a saved query is being renamed in. pub(crate) query_rename: Option, /// The same hazard as `editor_needs_focus`, for the row's field. pub(crate) query_rename_needs_focus: bool, /// The tab a close is asking about, because it holds cell edits nobody /// has applied. pub(crate) pending_discard: Option, pub(crate) pending_overwrite: Option, /// The recent file found gone when its Files row was opened, while the /// question whether to leave it off the list is up. pub(crate) pending_forget: Option, /// An action a landed row send released, waiting for render, which has the /// `Window` its handler needs (`Workspace::resume_released`). pub(crate) resume_after: Option<(Tab, AfterEdits)>, pub(crate) notice: Option, /// What a statement's run cost beyond its result (`QueryResult::notice`), /// said only while the tab it ran on is in front, under any `notice`. pub(crate) tab_notice: Option<(Tab, String)>, /// The generated batch a relation tab is showing before it runs. That tab /// has no buffer to put SQL in, so the modal is where the statement is on /// screen — and nothing runs until Run. pub(crate) apply_review: Option, /// The tabs whose review was closed while their batch was still out, one /// entry each, cleared by that tab's own landing. Such a grid takes no /// edit until its run lands: the success that clears the draft would drop /// one staged meanwhile unsaid. One per tab, since another tab's review /// can be opened, run and closed while the first is still out. pub(crate) draft_out: Vec, /// The "Insert" form a preview tab is filling in. Beside `apply_review` /// because the two are halves of one flow: the form collects, the review /// shows the statement it generated, and only Run sends it. pub(crate) insert_form: Option, /// The Import Rows dialog, over the whole workspace while this profile is /// in front. Tied to no tab: the table need not be open. pub(crate) import_rows: Option, /// The statement the mode check stopped, held until the user answers. pub(crate) pending_run: Option, /// An export asked for over rows that are not the whole result, held /// until the user says which rows it writes. pub(crate) pending_export: Option, /// The tables, structure and rows a schema export is being chosen over. pub(crate) schema_export: Option, /// Numbered across opens, so a read the dialog it was for has closed /// before landing is not taken for the reopened one's. pub(crate) last_schema_export: u64, /// The export of every row this connection is running, at most one. pub(crate) exporting: Option, /// The query tab whose queue stopped on a failed statement, held until /// the user says whether the rest of it still runs. Nothing after the /// failure is sent from here without an explicit Continue. pub(crate) queue_failure: Option, /// Query tabs whose queue had more to send when a statement landed with /// another connection in front, each with the generation it ran on. The /// next is sent once this connection is in front again on that /// generation; a connection opened since has none of what the first /// statements left on the session, so the rest is not run there. pub(crate) parked: Vec<(Tab, u64)>, /// The edit held until the user accepts that a restored grid's rows may /// be stale. pub(crate) stale_edit: Option, /// The structure request each relation tab is waiting on, by tab id. /// /// A refresh asks for the definition again, and nothing stops a second /// refresh starting while the first is in flight -- the engine reads the /// catalog in several queries, so the older request can finish last and /// put the older definition back. A completion that is not the newest /// issued for its tab is dropped. pub(crate) structure_requests: HashMap, pub(crate) last_structure_request: u64, } /// What a verified apply is refused with while a transaction the user opened /// is open on the connection, at review and at Run alike: the apply opens and /// ends a transaction of its own, and its `BEGIN` and `COMMIT` would end the /// user's (MySQL and MariaDB commit it at the `START TRANSACTION`). pub(crate) const APPLY_IN_TRANSACTION: &str = "A transaction is open on this connection; the edits were not applied."; /// A generated statement waiting to be read and run. pub(crate) struct ApplyReview { /// The tab the edits came from, so the modal is shown over that surface /// and a run cannot land in another tab's grid. pub(crate) tab: Tab, /// What this panel is confirming. An `UPDATE` batch and an `INSERT` both /// arrive here, and a panel calling either of them "Apply edits" would be /// the confirmation lying about what it confirms. pub(crate) title: &'static str, pub(crate) sql: String, /// What the engine adds about running `sql`, one paragraph each. pub(crate) notes: Vec, /// What the last run of `sql` came to when it failed or was refused, /// drawn where the statement is. Cleared when it runs again. pub(crate) error: Option, /// Whether `sql` is the grid's draft, which a successful run clears. An /// `INSERT` or a `DELETE` of the New row form or Delete row sends none of it. pub(crate) edits: bool, /// What a run of `sql` is verified against, when its target verifies an /// apply (`Target::verifies_applies`). Kept for as long as the review is /// open, since a refusal leaves it open and the next Run verifies again. pub(crate) verify: Option, /// The profile generation its last Run went out on. A reconnect since /// means that run's landing will be dropped, so the review may close. pub(crate) ran_on: Option, } /// The rows a reviewed draft was written from, as they were fetched: one step /// for each statement of the batch, in the order the batch holds them, built /// when the review is written and handed to the apply with the run. #[derive(Clone)] pub(crate) struct Verification { pub(crate) steps: Vec, /// What each step's row is called in what the apply says of it, `rows[i]` /// for step `i`: the key's `name = value` terms, or `added row N`. pub(crate) rows: Vec, /// The draft row each step was written for, by what names it, `identities[i]` /// for step `i` (`ResultGrid::draft_identities`). Empty for the one step of /// a Row send or a form, whose failure applies nothing. pub(crate) identities: Vec, } impl ApplyReview { /// Whether this review was written from `tab`'s rows: the one tab it is /// drawn over, and the one grid whose edits it holds up. pub(crate) fn covers(&self, tab: Tab) -> bool { self.tab == tab } } /// What a new review from `from` does about the session's one review slot. #[derive(Debug, PartialEq, Eq)] pub(crate) enum ReviewSlot { Free, /// `from`'s own review is on screen, and the new one is its newer /// statement: what `cmd+s` regenerates from the same pending edits. Replace, /// `from`'s own review is on screen and stays. Refuse, /// Another tab's review, out of sight behind `from`, to be brought forward. JumpTo(Tab), /// Held by a tab no longer open. Nothing can bring it forward, so it is /// put away and the slot is free. Stale, } impl ReviewSlot { pub(crate) fn for_review_from( held: Option<&ApplyReview>, from: Tab, replaces_own: bool, is_open: impl FnOnce(Tab) -> bool, ) -> Self { match held { None => Self::Free, Some(review) if review.covers(from) && replaces_own => Self::Replace, Some(review) if review.covers(from) => Self::Refuse, Some(review) if is_open(review.tab) => Self::JumpTo(review.tab), Some(_) => Self::Stale, } } } /// Whether `slot` holds a review written from `grid`'s rows, which an edit /// to that grid would leave describing something it no longer holds. pub(crate) fn review_holds_up(slot: Option<&ApplyReview>, grid: Tab) -> bool { slot.is_some_and(|review| review.covers(grid)) } /// Whether an edit may be staged into `owner`'s grid. Asked of the tab whose /// grid it is, not the tab in front: a row panel's blur lands on its own /// grid after another tab has been brought forward. pub(crate) fn may_stage_into(slot: Option<&ApplyReview>, importing: bool, owner: Tab) -> bool { !importing && !review_holds_up(slot, owner) } /// Put away the new-row form and the review `tab` had open. pub(crate) fn forget_tab( form: &mut Option, review: &mut Option, tab: Tab, ) { form.take_if(|open| open.tab == tab); drop_review_of(review, tab); } /// Put away the review written from `tab`'s rows, leaving another tab's be. pub(crate) fn drop_review_of(slot: &mut Option, tab: Tab) { slot.take_if(|review| review.covers(tab)); } /// The row a table has not got yet, one field per column (spec §4). /// /// Insertion needs a schema and a table and no primary key, so this is offered /// on relations the grid refuses to edit. pub(crate) struct InsertForm { pub(crate) tab: Tab, pub(crate) schema: String, pub(crate) table: String, pub(crate) fields: Vec, } pub(crate) struct InsertField { pub(crate) column: String, pub(crate) data_type: String, pub(crate) input: Entity, /// The `NULL` chip is on. Exclusive with `touched`: whichever happened /// last wins, and NULL clears the box. pub(crate) nulled: bool, /// Typed into since the last DEFAULT or NULL, so the text is sent even /// when empty. The reason `insert_value` answers three ways rather than /// two. pub(crate) touched: bool, /// `Engine::new_row_sends_empty`: whether an emptied field is `''` or left /// out. pub(crate) sends_empty: bool, } /// Rows on their way into a table. pub(crate) struct ImportDialog { /// The database the table is in, `None` for the connection's own: the /// columns are read, and the rows written, on that database's session. pub(crate) database: Option, pub(crate) schema: String, pub(crate) table: String, /// The table's columns, read for the dialog alone. pub(crate) structure: StructureState, pub(crate) source: ImportSource, pub(crate) bytes: Arc<[u8]>, pub(crate) options: import_rows::Options, pub(crate) mappings: Vec, pub(crate) prepared: Option, String>>, pub(crate) plan: Option>, /// Bumped by every recheck, so only the newest one's answer lands. pub(crate) checks: u64, pub(crate) checking: bool, pub(crate) phase: ImportPhase, pub(crate) error: Option, /// Rows a failed run of this file committed before it stopped. Running it /// again would send them twice. pub(crate) committed: usize, pub(crate) inputs: ImportInputs, pub(crate) preview: Entity>, pub(crate) sql: Entity, /// Set when a check lands: the SQL view needs a window to take the new /// statement, and a landing has none, so the next render writes it. pub(crate) sql_stale: bool, pub(crate) showing_sql: bool, /// The first file row the preview shows. pub(crate) preview_start: usize, /// The problem the footer's arrows are on. pub(crate) problem_at: usize, /// The file column a jump or the "Map a column" link pointed at. pub(crate) focused_mapping: Option, pub(crate) mapping_scroll: gpui::ScrollHandle, } impl ImportDialog { /// The table as the dialog names it: with its database when that is not /// the connection's own, where `public.t` of two databases would read the /// same. pub(crate) fn target_name(&self) -> String { match &self.database { Some(database) => format!("{database}.{}.{}", self.schema, self.table), None => format!("{}.{}", self.schema, self.table), } } /// Where the import runs: on the session of its table's database, when /// that is not the connection's own. pub(crate) fn binding(&self) -> Option { self.database.clone().map(|database| Binding { database, schema: None, }) } } /// Where an import's rows were read from. pub(crate) enum ImportSource { File(PathBuf), /// With the values a paste could not read back as their own types, /// which hold the import up while the rows are read as JSON. Clipboard(Vec), } impl ImportSource { pub(crate) fn name(&self) -> String { match self { Self::File(path) => path.file_name().map_or_else( || path.display().to_string(), |name| name.to_string_lossy().into_owned(), ), Self::Clipboard(_) => "Clipboard".into(), } } } /// The import options typed rather than picked. pub(crate) struct ImportInputs { pub(crate) delimiter: Entity, pub(crate) skip_lines: Entity, pub(crate) null_word: Entity, pub(crate) booleans: Entity, } // At most one per session: boxing the run saves nothing worth an indirection. #[allow(clippy::large_enum_variant)] pub(crate) enum ImportPhase { Editing, Running { plan: Arc, run: import_rows::Run, /// `None` while the import's own session is still opening. connection: Option, cancel: CancelToken, started: std::time::Instant, cancelling: bool, }, } /// What an empty box says will be sent. An emptied field is an empty string /// only where the engine writes one; elsewhere it is left out after all. pub(crate) fn insert_placeholder(nulled: bool, touched: bool, sends_empty: bool) -> &'static str { match (nulled, touched && sends_empty) { (true, _) => "NULL", (false, true) => "empty string", (false, false) => "DEFAULT", } } /// Whether the statement leaves the column out, so it keeps its default: /// what the DEFAULT chip shows. pub(crate) fn insert_left_out(nulled: bool, touched: bool, sends_empty: bool, typed: &str) -> bool { !nulled && (!touched || (!sends_empty && typed.is_empty())) } /// What one field contributes to the `INSERT`. The outer `None` is a column /// left out of the statement entirely, so the server's default applies; the /// inner `None` is a `NULL` the user asked for. /// /// Three answers and not two: a field nobody touched and a field deliberately /// emptied are different intents, and collapsing them would make `''` /// unreachable from the form for every text column in the database. pub(crate) fn insert_value(nulled: bool, touched: bool, typed: &str) -> Option> { match (nulled, touched) { (true, _) => Some(None), (false, true) => Some(Some(typed.to_string())), (false, false) => None, } } /// Everything `execute_and_then` needs to run a statement it was stopped from /// running. pub(crate) struct Resume { pub(crate) sql: String, pub(crate) tab: Tab, pub(crate) refresh: Option, pub(crate) keep_rows: bool, pub(crate) explain: Option, } /// The statement the mode check stopped, held until the user answers. Nothing /// runs from here without an explicit Run. pub(crate) struct PendingRun { /// `None` when the mode refused an inline edit rather than a statement -- /// there is nothing to resume, and the dialog offers only the mode change. pub(crate) resume: Option, pub(crate) verdict: Verdict, /// The "don't ask again" tick, shown by the Confirm shape and, as the /// app-wide opt-in to run what dbdelve cannot parse, by RunOnce. pub(crate) dont_ask: bool, /// The mode refused a grid cell's commit, whose input waits open behind /// the prompt: raising the mode carries the commit through. pub(crate) commit_cell: bool, /// Raised by `execute_own`, so `Settings::run_unreadable` applies to it. pub(crate) own_run: bool, } /// Export over a grid holding less than its result, waiting on the dialog /// that asks whether to write the rows shown or fetch every row again. pub(crate) struct PendingExport { pub(crate) format: crate::export::FileAs, /// The tab it was asked over. pub(crate) tab: Tab, pub(crate) showing: usize, /// What the tab is showing, in the dialog's words. pub(crate) situation: String, /// What Export All Rows runs, or why it is not offered. pub(crate) every_row: Result, } /// The statement an export of every row runs: a query tab's as the user /// typed it, or a relation tab's regenerated without its limit. #[derive(Clone)] pub(crate) struct Refetch { pub(crate) sql: String, pub(crate) generated: bool, /// The database a relation tab of another database fetches from, which /// the connection of its own is opened on; `None` for the profile's own. pub(crate) binding: Option, } /// An export of every row, running on a connection of its own. pub(crate) struct Exporting { /// The file's name, for the status bar. pub(crate) file: String, pub(crate) started: std::time::Instant, pub(crate) progress: Arc, } /// What the export's writer and the status bar share. #[derive(Default)] pub(crate) struct ExportProgress { pub(crate) rows: std::sync::atomic::AtomicUsize, pub(crate) cancelled: std::sync::atomic::AtomicBool, } /// The `confirmed` slug that silences [`StaleEdit`]'s prompt. pub(crate) const STALE_ROWS: &str = "stale-rows"; /// An edit on a restored grid, stopped until the user answers whether to edit /// rows fetched in an earlier session. pub(crate) struct StaleEdit { /// The edit to carry on with, or `None` when the prompt was opened from /// the status bar only to refresh, with no edit waiting. pub(crate) resume: Option, pub(crate) dont_ask: bool, } #[derive(Clone)] pub(crate) enum StaleResume { Open, /// The cell as well as the value: the row panel stages into cells other /// than the active one. Stage((usize, usize), NewValue), Delete, NewRow, } impl Session { /// What a raw filter bar on `schema`'s `relation` completes from: nothing until the /// catalog has loaded, and nothing on an engine whose raw filter is not /// one the schema can complete. pub(crate) fn filter_completions( &self, engine: Engine, schema: &str, relation: &str, ) -> Option> { let provider = completion::FilterCompletions::new( engine.syntax(), self.completions.clone()?, (schema.to_string(), relation.to_string()), )?; Some(Rc::new(provider)) } #[allow(clippy::too_many_arguments)] pub(crate) fn new( id: String, stored_queries: Vec, stored_next_query_id: u64, pending_objects: Vec, engine: Engine, sorting: Sorting, row_limit: Option, window: &mut Window, cx: &mut Context, ) -> Self { let explorer_filter = cx.new(|cx| InputState::new(window, cx).placeholder("Filter queries and objects…")); cx.subscribe(&explorer_filter, { let id = id.clone(); move |workspace, _, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { workspace.refresh_explorer(&id, cx); } } }) .detach(); let explorer_tree = cx.new(|cx| TreeState::new(cx)); cx.subscribe(&explorer_tree, { let id = id.clone(); move |workspace, tree, event: &TreeEvent, cx| { workspace.remember_fold(&id, &tree, event, cx); } }) .detach(); let page_input = cx.new(|cx| InputState::new(window, cx)); cx.subscribe( &page_input, |workspace, _, event: &InputEvent, cx| match event { InputEvent::PressEnter { .. } => workspace.go_to_page(cx), // A page typed and abandoned goes back to the one in front. InputEvent::Blur => cx.notify(), _ => {} }, ) .detach(); let saved_queries = store::saved_queries(&id); let query_directory = sql_file::canonical(&store::query_directory(&id).unwrap_or_default()); let stored_queries = adopted(stored_queries, &query_directory); // No tab is a state a profile can be in: closing the last one leaves // the strip empty, and it comes back empty. let active = stored_queries .iter() .find(|stored| stored.active) .or(stored_queries.first()) .map_or(0, |stored| stored.id); let next_query_id = next_query_id(stored_next_query_id, &stored_queries); let mut notice = None; let queries = stored_queries .iter() .map(|stored| { let (tab, failure) = QueryTab::restore(&id, stored, engine, sorting.clone(), row_limit, window, cx); notice = notice.take().or(failure); tab }) .collect(); Self { queries, objects: Vec::new(), active: Tab::Query(active), tab_order: Vec::new(), next_query_id, next_object_id: 0, pending_objects, completion_columns: completion::ColumnCache::default(), completions: None, explorer_filter, explorer_tree, explorer_leaves: Arc::new(HashMap::new()), explorer_highlights: Arc::new(HashMap::new()), explorer_shortcuts: Arc::new(HashMap::new()), editor_needs_focus: true, saved_queries, query_directory, history: store::history(&id), page_input, page_shown: 0, pending_delete: None, query_rename: None, query_rename_needs_focus: false, pending_discard: None, pending_overwrite: None, pending_forget: None, resume_after: None, notice, tab_notice: None, apply_review: None, draft_out: Vec::new(), insert_form: None, import_rows: None, pending_run: None, pending_export: None, schema_export: None, last_schema_export: 0, exporting: None, queue_failure: None, parked: Vec::new(), stale_edit: None, structure_requests: HashMap::new(), last_structure_request: 0, } } /// The status bar's notice: the session's, or else one about the tab in /// front. pub(crate) fn shown_notice(&self) -> Option<&str> { self.notice.as_deref().or_else(|| { self.tab_notice .as_ref() .filter(|(tab, _)| *tab == self.active) .map(|(_, notice)| notice.as_str()) }) } /// Says what became of an edit send that failed or was refused, where the /// statement is: in the review when one covers `tab`, otherwise in the /// tab's notice, beside the statement appended to its buffer. pub(crate) fn edit_failed(&mut self, tab: Tab, message: String) { match self .apply_review .as_mut() .filter(|review| review.covers(tab)) { Some(review) => review.error = Some(message), None => self.tab_notice = Some((tab, message)), } } pub(crate) fn query_tab(&self, id: u64) -> Option<&QueryTab> { self.queries.iter().find(|tab| tab.id == id) } pub(crate) fn query_tab_mut(&mut self, id: u64) -> Option<&mut QueryTab> { self.queries.iter_mut().find(|tab| tab.id == id) } /// Bring `tab`'s results pane back, for an answer written into it or a /// command that acts on what it shows: neither may happen out of sight. pub(crate) fn reveal_results(&mut self, tab: Tab) { if let Tab::Query(id) = tab && let Some(query) = self.query_tab_mut(id) { query.results_hidden = false; } } /// Whether `tab` is a query tab bound to a database, whose statements run /// on that database's session and never beside one another. pub(crate) fn is_bound(&self, tab: Tab) -> bool { matches!(tab, Tab::Query(id) if self.query_tab(id).is_some_and(|tab| tab.binding.is_some())) } /// Put away the new-row form and the review a closed tab, query or /// object, had open. Left in place, a form holds its inputs alive for /// nothing, a query tab's id is handed to the next buffer, which would /// find both, and a review holds the session's one slot with no tab left /// to bring it forward from. pub(crate) fn forget(&mut self, tab: Tab) { forget_tab(&mut self.insert_form, &mut self.apply_review, tab); } pub(crate) fn apply_review_covers(&self, tab: Tab) -> bool { review_holds_up(self.apply_review.as_ref(), tab) } /// Asked of the tab whose grid is being edited, which a blur can make a /// tab other than the active one. pub(crate) fn may_stage_into(&self, owner: Tab) -> bool { !self.draft_out.contains(&owner) && may_stage_into( self.apply_review.as_ref(), self.import_rows.is_some(), owner, ) } pub(crate) fn review_slot(&self, from: Tab, replaces_own: bool) -> ReviewSlot { ReviewSlot::for_review_from(self.apply_review.as_ref(), from, replaces_own, |tab| { self.is_open(tab) }) } pub(crate) fn is_open(&self, tab: Tab) -> bool { match tab { Tab::Query(id) => self.query_tab(id).is_some(), Tab::Object(id) => self.objects.iter().any(|object| object.id == id), } } /// Undoes what an action that is not going ahead changed before it asked: /// a filter bar the user edited goes back to what it was. Every way a /// parked [`AfterEdits`] can be dropped ends here, so the bars never show /// a filter that did not run. pub(crate) fn put_back(&mut self, tab: Tab, then: AfterEdits) { if let (Tab::Object(id), AfterEdits::Filter { before: Some(rows) }) = (tab, then) && let Some(ObjectBody::Relation { filters, .. }) = self .objects .iter_mut() .find(|tab| tab.id == id) .map(|tab| &mut tab.body) { *filters = rows; } } /// Holds `then` for render to carry out once a landed send has released /// it. One slot: an action already waiting is the user's own, and this /// one is put back instead. pub(crate) fn park_resume(&mut self, tab: Tab, then: AfterEdits) { match self.resume_after { Some(_) => self.put_back(tab, then), None => self.resume_after = Some((tab, then)), } } /// Owes relation tab `id` a read of its rows on its next visit, for rows /// that no longer say what the server holds. pub(crate) fn mark_stale(&mut self, id: u64) { if let Some(ObjectBody::Relation { stale, .. }) = self .objects .iter_mut() .find(|tab| tab.id == id) .map(|tab| &mut tab.body) { *stale = true; } } pub(crate) fn drop_apply_review_of(&mut self, tab: Tab) { drop_review_of(&mut self.apply_review, tab); } /// The query buffer in front, or `None` when an object tab is. pub(crate) fn active_query_tab(&self) -> Option<&QueryTab> { match self.active { Tab::Query(id) => self.query_tab(id), Tab::Object(_) => None, } } /// Every chip the strip draws, left to right: the dragged order first, /// then anything newer than it in the default one. pub(crate) fn strip_order(&self) -> Vec { strip_order(self.default_chips(), &self.tab_order) } /// One chip per open tab, in the order a strip nobody has dragged shows /// them. pub(crate) fn default_chips(&self) -> Vec { default_chips( self.queries .iter() .map(|tab| (tab.id, tab.file.as_ref().map(|file| file.path.as_path()))), self.objects.iter().map(|tab| tab.id), ) } /// Put a chip just opened at the right end of the strip as it is drawn. /// /// The whole order is written down first, not just the new chip: the tabs /// restored at launch are in no order but the default one, and pushing /// onto that would put the newest chip ahead of all of them. pub(crate) fn place_last(&mut self, key: TabKey) { self.tab_order = placed_last(self.strip_order(), key); } /// Swap the chip in front with its neighbour, as dropping it one slot /// over would. Whether it moved: the end of the strip is a wall. pub(crate) fn move_active_tab(&mut self, step: isize) -> bool { let order = self.strip_order(); let Some(key) = order .iter() .find(|key| self.tab_of(key) == Some(self.active)) .cloned() else { return false; }; match moved(order, &key, step) { Some(order) => { self.tab_order = order; true } None => false, } } /// Give a chip its new key where it stands, for a buffer whose file is /// changing: saving it as another or renaming it is not moving it. pub(crate) fn rekey(&mut self, from: &TabKey, to: TabKey) { let mut order = self.strip_order(); if let Some(key) = order.iter_mut().find(|key| *key == from) { *key = to; } self.tab_order = order; } /// The tabs behind the strip's chips, left to right. pub(crate) fn strip_tabs(&self) -> Vec { self.strip_order() .iter() .filter_map(|key| self.tab_of(key)) .collect() } /// The tab that comes to the front when `closing` goes. Asked before it /// goes, while the strip still says where it stood, and brought forward /// through `activate_tab` as a click on its chip would be: a tab not /// looked at since launch has its snapshot read and its rows refreshed /// there and nowhere else. pub(crate) fn fallback(&self, closing: Tab) -> Option { neighbour(&self.strip_tabs(), closing) } /// The tab a chip opens or shows, where it has one. pub(crate) fn tab_of(&self, key: &TabKey) -> Option { match key { TabKey::Unsaved(id) => Some(Tab::Query(*id)), TabKey::File(path) => self.tab_on(path).map(Tab::Query), TabKey::Object(id) => Some(Tab::Object(*id)), } } /// The tab bound to `path`, if one is open. pub(crate) fn tab_on(&self, path: &Path) -> Option { self.queries .iter() .find(|tab| tab.file.as_ref().is_some_and(|file| file.path == path)) .map(|tab| tab.id) } /// Where the saved query `name` is on disk, resolved as every bound path /// is, so a query that is a link names the file a tab on it is bound to. pub(crate) fn saved_query_path(&self, name: &str) -> PathBuf { sql_file::canonical(&self.query_directory.join(format!("{name}.sql"))) } /// Unbind every tab on a file `held` already has open, or an earlier tab /// here does, keeping its text as an untitled buffer's: two tabs on one /// file would save over each other. Restored paths can meet when a link /// they were stored through now leads somewhere else. What to say about /// it, when anything was unbound. pub(crate) fn unbind_duplicates( &mut self, mut held: HashSet, cx: &App, ) -> Option { let mut unbound = None; for tab in &mut self.queries { let Some(file) = &tab.file else { continue; }; if held.insert(file.path.clone()) { continue; } unbound.get_or_insert_with(|| { format!( "{} was open in two tabs, so one of them is untitled now.", sql_file::file_name(&file.path) ) }); tab.file = None; tab.refresh_dirty(cx); } unbound } /// The file deleting the saved query `name` takes away, as a tab on it is /// bound: `None` when the query is a link, which goes alone, leaving the /// file it leads to and any tab on that. pub(crate) fn deleted_with(&self, name: &str) -> Option { let entry = self.query_directory.join(format!("{name}.sql")); let link = std::fs::symlink_metadata(&entry) .is_ok_and(|metadata| metadata.file_type().is_symlink()); (!link).then(|| sql_file::canonical(&entry)) } /// The tab bound to the saved query `name`, if one is open. pub(crate) fn tab_holding(&self, name: &str) -> Option { self.tab_on(&self.saved_query_path(name)) } /// The saved query `tab` is bound to, when its file is one of this /// profile's saved queries. pub(crate) fn saved_query_of<'a>(&self, tab: &'a QueryTab) -> Option<&'a str> { let path = &tab.file.as_ref()?.path; if path.parent()? != self.query_directory { return None; } path.file_name()?.to_str()?.strip_suffix(".sql") } pub(crate) fn active_object(&self) -> Option<&ObjectTab> { match self.active { Tab::Object(id) => self.objects.iter().find(|tab| tab.id == id), Tab::Query(_) => None, } } /// The query state behind the visible surface, or `None` for a surface that /// runs nothing — a routine is read, never executed by being opened. pub(crate) fn active_query(&self) -> Option<&QueryState> { match self.active_object() { None => self.active_query_tab().map(|tab| tab.shown().0), Some(tab) => match &tab.body { ObjectBody::Relation { query, .. } => Some(query), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } /// The grid the visible surface is showing. A routine's tab has none: it is /// read, not run. /// /// A queue's selected result, not the tab's own slot, because this is what /// copying, exporting and editing act on and all three mean the grid in /// front of the user. `slot` is the other half of that split: it is where a /// run's rows land, which stays the tab's slot whatever is being read. pub(crate) fn active_results(&self) -> Option<&Entity>> { match self.active_object() { None => self.active_query_tab().map(|tab| tab.shown().1), Some(tab) => match &tab.body { ObjectBody::Relation { results, .. } => Some(results), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } /// What a new row of the rows in front of the active query tab is /// inserted into, a queue's earlier result included. Nothing while the /// tab shows its plan, which stands in for those rows, nor on a `target` /// that takes no inserts: the grid's `edit` was set by whichever driver /// read its rows, and the profile may have moved to another since. pub(crate) fn query_insert_target(&self, target: Target, cx: &App) -> Option { if !target.takes_inserts(RelationKind::Table) { return None; } self.active_query_tab() .filter(|tab| tab.plan_shown().is_none() && !tab.messages_shown())? .shown() .1 .read(cx) .delegate() .insert_target() } /// Every buffer and structure grid highlighted (and every buffer prompted) /// for `syntax`, once an edit has moved the profile to an engine written in /// another language. pub(crate) fn set_syntax(&self, syntax: Syntax, window: &mut Window, cx: &mut App) { for tab in &self.queries { tab.editor.update(cx, |editor, cx| { editor.set_highlighter(syntax.highlighter(), cx); editor.set_placeholder(syntax.placeholder(), window, cx); }); } for tab in &self.objects { if let ObjectBody::Structure { grid, .. } = &tab.body { grid.update(cx, |table, cx| { table.delegate_mut().set_syntax(syntax); cx.notify(); }); } } } /// The buffer a run reads from, which only the query tab has. An object tab /// shows an object: there is no SQL in front of the user to run. pub(crate) fn editor(&self, tab: Tab) -> Option> { match tab { Tab::Query(id) => self.query_tab(id).map(|tab| tab.editor.clone()), Tab::Object(_) => None, } } /// The grid one named tab is showing. `slot` answers the same question but /// needs a `&mut`, and asking what a tab holds changes nothing. pub(crate) fn results(&self, tab: Tab) -> Option<&Entity>> { match tab { Tab::Query(id) => self.query_tab(id).map(|tab| &tab.results), Tab::Object(id) => match &self.objects.iter().find(|tab| tab.id == id)?.body { ObjectBody::Relation { results, .. } => Some(results), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } /// Every grid one named tab keeps rows in: its slot, the slot's own grid /// while a queue's earlier result stands in for it, and each finished /// result of a queue. The edits a requery would replace are in any of /// them, so the question and the Discard that answers it read the same set. pub(crate) fn tab_grids(&self, tab: Tab) -> Vec>> { let mut grids: Vec<_> = self.results(tab).into_iter().cloned().collect(); if let Tab::Query(id) = tab && let Some(query) = self.query_tab(id) { grids.extend(query.lent.iter().map(|(grid, _)| grid.clone())); grids.extend( query .queue .iter() .flat_map(|queue| queue.done.iter().map(|finished| finished.grid.clone())), ); } grids } /// Whether one named tab has a statement in flight: its own slot, not /// whichever of a queue's results the switcher is showing. pub(crate) fn running(&self, tab: Tab) -> bool { let state = match tab { Tab::Query(id) => self.query_tab(id).map(|tab| &tab.query), Tab::Object(id) => self .objects .iter() .find(|tab| tab.id == id) .and_then(|tab| match &tab.body { ObjectBody::Relation { query, .. } => Some(query), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }), }; matches!(state, Some(QueryState::Running { .. })) } /// Who orders one named tab's rows. `None` for a routine, which has none. pub(crate) fn sorting(&self, tab: Tab) -> Option<&Sorting> { match tab { Tab::Query(id) => self.query_tab(id).map(|tab| &tab.sorting), Tab::Object(id) => match &self.objects.iter().find(|tab| tab.id == id)?.body { ObjectBody::Relation { sorting, .. } => Some(sorting), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } pub(crate) fn sorting_mut(&mut self, tab: Tab) -> Option<&mut Sorting> { match tab { Tab::Query(id) => self.query_tab_mut(id).map(|tab| &mut tab.sorting), Tab::Object(id) => match &mut self.objects.iter_mut().find(|tab| tab.id == id)?.body { ObjectBody::Relation { sorting, .. } => Some(sorting), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } /// When one named tab's edits are sent: its own for a relation, `Draft` for /// every other tab, which has no Row mode to be in. pub(crate) fn edit_mode(&self, tab: Tab) -> EditMode { match tab { Tab::Query(_) => EditMode::Draft, Tab::Object(id) => match self.objects.iter().find(|tab| tab.id == id) { Some(ObjectTab { body: ObjectBody::Relation { edit_mode, .. }, .. }) => *edit_mode, _ => EditMode::Draft, }, } } /// `Some` only for a relation tab, the one view with a mode to change. pub(crate) fn edit_mode_mut(&mut self, tab: Tab) -> Option<&mut EditMode> { match tab { Tab::Query(_) => None, Tab::Object(id) => match &mut self.objects.iter_mut().find(|tab| tab.id == id)?.body { ObjectBody::Relation { edit_mode, .. } => Some(edit_mode), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } /// Every live grid this session holds, across both tab strips. `results` /// and `slot` reach one grid by tab; this reaches all of them, for a /// setting that belongs to the connection rather than to a run -- /// `Workspace::set_mode` is the caller. /// A queue's finished results are in here too: they stay on screen through /// the switcher, so a mode that did not reach them would leave an older /// result editable after the connection stopped allowing it. pub(crate) fn grids(&self) -> impl Iterator>> { self.queries .iter() .flat_map(QueryTab::grids) .chain(self.objects.iter().filter_map(|tab| match &tab.body { ObjectBody::Relation { results, .. } => Some(results), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, })) } /// Where a run's state and rows belong. Returning both together is what /// keeps a result from landing in one tab's grid with another tab's status. pub(crate) fn slot( &mut self, tab: Tab, ) -> Option<(&mut QueryState, Entity>)> { match tab { Tab::Query(id) => { let tab = self.query_tab_mut(id)?; let results = tab.results.clone(); Some((&mut tab.query, results)) } Tab::Object(id) => match &mut self.objects.iter_mut().find(|tab| tab.id == id)?.body { ObjectBody::Relation { query, results, .. } => Some((query, results.clone())), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => None, }, } } /// `slot`, or for a queue's statement running at once with others, that /// statement's own entry in `done`. Keyed by statement rather than /// position, because a batch that lands more than one set puts results /// ahead of those still running; and only while the tab is still running /// the lane's own run, since a later run of the same text has statements /// starting at the same places. pub(crate) fn slot_at( &mut self, tab: Tab, lane: Option<&Lane>, ) -> Option<(&mut QueryState, Entity>)> { let Some(lane) = lane else { return self.slot(tab); }; let Tab::Query(id) = tab else { return None; }; let query = self.query_tab_mut(id)?; if !matches!(&query.query, QueryState::Running { cancel, .. } if cancel.is(&lane.run)) { return None; } let queue = query.queue.as_mut()?; let at = queue.lane(lane.start)?; let finished = &mut queue.done[at]; Some((&mut finished.state, finished.grid.clone())) } /// Drop every confirmation and half-finished prompt this session is holding. /// /// All four name the buffer or tab they were raised over, so leaving one /// standing across a context change offers to delete one query while another /// is on screen. One method rather than a clear at each site, because the /// two callers had drifted apart: a field left up with its focus already /// spent hands focus to nothing at all, and a window with nothing focused /// has no dispatch path, so the keyboard goes dead until something is /// clicked. pub(crate) fn clear_prompts(&mut self) { self.pending_delete = None; self.query_rename = None; self.query_rename_needs_focus = false; // The bars a dropped filter prompt was holding go back as Cancel puts // them: they were changed before anything could ask, and the filter // that ran is the one they have to describe. if let Some(PendingDiscard { tab, then, .. }) = self.pending_discard.take() { self.put_back(tab, then); } // An action released by a landed send does not follow the user to // another tab or connection, and its bars go back like a Cancel's. if let Some((tab, then)) = self.resume_after.take() { self.put_back(tab, then); } self.pending_overwrite = None; self.pending_forget = None; // A stopped statement must not survive a tab or profile switch and get // confirmed against a connection it was never aimed at. self.pending_run = None; self.pending_export = None; self.stale_edit = None; } } /// A saved query's sidebar row turned into a field holding its name. pub(crate) struct QueryRename { /// The name it has on disk now, or the folder's name. pub(crate) name: String, /// A folder's name rather than a saved query's. pub(crate) folder: bool, /// The row the field is drawn over, by id: a saved query can be listed /// in several places, and the field belongs in the one it was asked from. pub(crate) row: SharedString, pub(crate) input: Entity, /// Why the name typed was refused, until it is typed over. pub(crate) error: Option, } /// Why `name` cannot be what a saved query is saved or renamed as, if it /// cannot. `keeping` is the query's own name on a rename, which it may keep. pub(crate) fn query_name_refusal( name: &str, keeping: Option<&str>, saved_queries: &[String], ) -> Option { if let Err(message) = store::validate_query_name(name) { return Some(message); } // Any case: on a filesystem that ignores it, a query that differs only // by case is the same file, and saving over it would replace it. saved_queries .iter() .find(|saved| Some(saved.as_str()) != keeping && store::same_query_name(saved, name)) .map(|saved| format!("A query named {saved} already exists.")) } /// What the Delete dialog asks about. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum PendingDelete { Query(String), /// A folder and how many it holds: one holding nothing goes unasked. Folder(String, usize), } /// What a tab was asked to do while its grid held edits nobody had applied, /// kept as data so the prompt, and in Row mode the send, can carry it out once /// the edits are out of the way. Never a stored closure: every variant is the /// values the action was raised with, so a Discard runs what the user asked /// for and not what the tab has become since. #[derive(Clone)] pub(crate) enum AfterEdits { /// Close the tab, and delete the saved query first when deleting it is /// what closes the tab, by its profile's id and its name: the tab can be /// on another connection. Close { deleting: Option<(String, String)> }, /// A relation tab's statement again, with the filter, sort, row limit and /// page offset the action produced. The tab's own are untouched until it /// runs, so a cancelled page turn leaves the page on screen as it was. Requery { filter: String, sort: Vec, limit: Option, offset: usize, }, /// A relation tab's rows read again as they stand. Refresh, /// The filter bars as the user just changed them. `before` is what they /// were, put back on Cancel: the bars are the tab's state and were changed /// by the caller before anything could ask. Filter { before: Option> }, /// The view's sorting switched to the server (`false`) or to memory. ViewSorting(bool), /// A query tab's Run. Run, /// A header click on a grid holding edits: a query tab's, on the server, or /// a Row view's, in memory. Sort(usize), /// One of a finished queue's statements run again, as `sql`. Rerun { index: usize, sql: String }, /// Bring this tab forward. Only a Row view's row waits on this, sent first /// (or asked about, when the server refused it): a Draft view's draft stays /// with its tab, so a tab switch asks nothing. Activate(Tab), /// Switch the view's edit mode. Only a Row view's row waits on this, being /// sent before the view becomes Draft or Classic (or asked about, when the /// server refused it). EditMode(EditMode), } impl AfterEdits { /// The prompt's title, and the act that discards the edits as the subject /// of its sentence. fn leaves(&self) -> (&'static str, &'static str) { match self { Self::Close { .. } => ("Close tab", "Closing it"), Self::Requery { .. } | Self::Refresh | Self::Filter { .. } | Self::ViewSorting(_) | Self::Sort(_) => ("Discard edits", "Reading the rows again"), Self::Run | Self::Rerun { .. } => ("Discard edits", "Running the statement"), // Reached only over a row the server refused: any other Row view's // row is sent first, and a Draft view is not asked. Self::Activate(_) => ("Discard edits", "Switching to another tab"), Self::EditMode(_) => ("Discard edits", "Switching the edit mode"), } } /// The prompt's title and its sentence: what the edits are discarded by. pub(crate) fn discards(&self) -> (&'static str, String) { let (title, act) = self.leaves(); ( title, format!("This tab has cell edits that have not been applied. {act} discards them."), ) } /// The same prompt over a row of a Row view the server refused, whose /// edits are all that Discard drops. pub(crate) fn discards_refused_row(&self) -> (&'static str, String) { let (title, act) = self.leaves(); ( title, format!( "The server refused a row of this tab, so its edits have not been applied. \ {act} discards that row's edits." ), ) } } /// An action held up by the unapplied-edits question, and what to do once the /// edits are gone. One slot: the prompt covers the tab, so no second action can /// be raised behind it. Close All Tabs holds the other tabs it found edits in /// as `also`, closed with `tab` when the edits go. pub(crate) struct PendingDiscard { pub(crate) tab: Tab, pub(crate) then: AfterEdits, /// The row of a Row view the server refused, when that is what the prompt /// is over: Discard drops its edits and no other row's, which are sent as /// the action meets them. `None` for a draft, all of whose edits go. pub(crate) row: Option, /// The other tabs Close All Tabs found edits in, discarded and closed /// with `tab`, and the file tabs with unsaved changes it holds for the /// Save question after. Empty for every other action. pub(crate) also: Vec, /// Asking Save / Don't Save about file tabs with unsaved changes, `tab` /// and `also`, rather than about cell edits. pub(crate) unsaved: bool, } impl PendingDiscard { /// Every tab the question is over: `tab`, then `also`. pub(crate) fn tabs(&self) -> impl Iterator + '_ { std::iter::once(self.tab).chain(self.also.iter().copied()) } } /// File tabs whose Save is waiting on the Overwrite question, and whether /// each closes once written, as Save in the close question asked. pub(crate) struct PendingOverwrite { pub(crate) tabs: Vec, pub(crate) close: bool, } /// What takes focus when a surface comes to the front. A buffer, a field and a /// grid are all focusable and no two of them share a type. pub(crate) enum Focus { Buffer(Entity), Grid(Entity>), Structure(Entity>), Diagram(gpui::FocusHandle), /// The window itself, for a surface with nothing in it to type into. Not a /// no-op: a keystroke only reaches the workspace along the focused /// element's dispatch path, so focusing nothing at all is what makes every /// binding dead until something is clicked. Window, } pub(crate) enum CatalogState { Loading, /// The relations, and how far the routines behind them have got. Loaded(Catalog, Routines), Failed(String), } /// Where a tab's reads and writes go, as [`Profile::connection_for`] finds /// it. Resolved on the blocking pool, because opening a session is not /// something to wait on from the frame. pub(crate) enum Routed { /// The profile's own connection: the tab is not bound. Own(Connection), /// The session already open for the tab's database. Bound { session: Arc, schema: Option, }, /// No session is open for the tab's database: one is opened from `from` /// ([`Connection::on_database`]), held to reads when `read_only`. Open { from: Connection, database: String, schema: Option, read_only: bool, }, /// The profile has no live connection to run on. Unavailable, } impl Routed { /// The connection to run on, with the schema a bound tab runs in. Opens /// the session when there is none, and so may take as long as a connect. pub(crate) fn resolve(self) -> Result<(Connection, Option), DbError> { match self { Self::Own(connection) => Ok((connection, None)), Self::Bound { session, schema } => Ok((session.connection.clone(), schema)), Self::Open { from, database, schema, read_only, } => { let session = from.on_database(&database)?; // Only Read-only asks the server for anything, as at connect: // a session that fails to take the hold is dropped, not run // on looking held. if read_only { session.set_read_only(true)?; } Ok((session, schema)) } Self::Unavailable => Err(DbError { message: "The connection is not open.".into(), position: None, }), } } /// The session already open that a run goes to, kept for what is /// recorded with it and to tell it from a replacement. pub(crate) fn bound(&self) -> Option> { match self { Self::Bound { session, .. } => Some(session.clone()), _ => None, } } /// Whether there is a connection to run on, now or once a session opens. pub(crate) fn is_available(&self) -> bool { !matches!(self, Self::Unavailable) } /// A connection that exists now to ask something of, such as a statement /// to stop: the session of a bound tab, else the profile's own. pub(crate) fn existing(&self) -> Option<&Connection> { match self { Self::Own(connection) => Some(connection), Self::Bound { session, .. } => Some(&session.connection), Self::Open { from, .. } => Some(from), Self::Unavailable => None, } } } /// A session for one (profile, database) pair other than the profile's own. pub(crate) enum BoundSession { /// Being opened on the blocking pool. Holds the database's place, so a /// second expand does not open a second session. Opening, /// Shared by every read and run that goes to the database. The `Arc` is /// the session's identity: what was read or run over one that has since /// been lost and replaced lands on none of the replacement's state /// ([`Profile::is_registered`]). Open(Arc), } /// A session open for another database of a profile's server, and what is /// kept with it. pub(crate) struct Bound { pub(crate) connection: Connection, /// Orders `set_mode`'s holds on this session as [`Profile::holds`] does /// on the profile's own connection. A line of its own, so a hold here /// waits behind nothing running on another session. pub(crate) holds: HoldLine, /// Whether a statement of a tab's has left a transaction open on this /// session, read off what was sent as [`Profile::in_transaction`] is. /// Every tab bound to the database shares it, so a write of dbdelve's /// from another tab would run inside it ([`Bound::edit`]). transaction: AtomicBool, /// Whether one has changed the session in a way that lasts as long as it /// does, as [`Profile::session_changed`] says of the profile's own. The /// binding is put back before each run; a `SET ROLE` is not. settings: AtomicBool, /// Taken by a statement of a tab's that opens or ends a transaction, for /// as long as it runs, and by an edit of dbdelve's, which reads /// `transaction` under it: an edit waiting its turn on the session cannot /// be overtaken by a `BEGIN` it would then run inside. turn: Mutex<()>, } impl Bound { pub(crate) fn new(connection: Connection) -> Arc { Arc::new(Self { connection, holds: HoldLine::default(), transaction: AtomicBool::new(false), settings: AtomicBool::new(false), turn: Mutex::new(()), }) } pub(crate) fn in_transaction(&self) -> bool { self.transaction.load(Ordering::SeqCst) } /// Whether a transaction or a changed setting means a session of its own /// would not read what this one does. pub(crate) fn changed(&self) -> bool { self.in_transaction() || self.settings.load(Ordering::SeqCst) } /// Runs a statement of a tab's that leaves `transaction` (`sql::leaves`: /// `Some(true)` opens one, `Some(false)` ends it) and, with `settings`, /// changes the session. One that opens a transaction or changes a setting /// is marked before it is sent, as one that fails part way may still have /// done either; one that ends a transaction is marked once it has run, and /// only if it succeeded. A COMMIT cancelled before it was sent leaves the /// transaction open, and nothing in the error tells that from one the /// server refused, so a failed one keeps edits refused until a ROLLBACK or /// COMMIT goes through. pub(crate) fn leave( &self, transaction: Option, settings: bool, run: impl FnOnce() -> Result, ) -> Result { if settings { self.settings.store(true, Ordering::SeqCst); } let Some(open) = transaction else { return run(); }; let _turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); if open { self.transaction.store(true, Ordering::SeqCst); } let ran = run(); if !open && ran.is_ok() { self.transaction.store(false, Ordering::SeqCst); } ran } /// Runs a read of dbdelve's own, such as the catalog, on this session, or /// on one apart while a transaction is open on it: a failed read inside /// the transaction would fail it on Postgres. Under `turn`, so a `BEGIN` /// cannot be sent between the check and the read and have the read run /// inside it. A `BEGIN` would queue behind the read on the session anyway. pub(crate) fn metadata( &self, read: impl FnOnce(&Connection) -> Result, ) -> Result { let turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); if self.in_transaction() { drop(turn); return read(&self.connection.apart()?); } read(&self.connection) } /// Runs an edit of dbdelve's on this session, the session of `database`, /// unless a transaction is open on it: the edit would run inside it and /// read back as applied while nothing has committed it. pub(crate) fn edit( &self, database: &str, run: impl FnOnce() -> Result, ) -> Result { let _turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); match self.write_refusal(database) { Some(message) => Err(DbError { message, position: None, }), None => run(), } } /// Why an edit on this session of `database` is not sent; see /// [`Bound::edit`]. pub(crate) fn write_refusal(&self, database: &str) -> Option { self.in_transaction().then(|| { format!( "Not sent: a transaction is open on the session of {database}, and the change would run inside it." ) }) } } /// Where a query tab opened with New Query Here runs: a database of its /// connection's server, and where the engine picks one, a schema in it. Both /// as the server listed them, handed to the driver unchanged. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Binding { pub(crate) database: String, pub(crate) schema: Option, } impl Binding { /// The database, or `database.schema`: how a notice and a chip name where /// the tab runs. pub(crate) fn label(&self) -> String { match &self.schema { Some(schema) => format!("{}.{schema}", self.database), None => self.database.clone(), } } /// The binding for a tab opened on `database` and `schema`, or `None` /// where there is nothing to bind: a target that switches no database, and /// a blank name, which is the login default and so the profile's own /// session. The schema is kept only where the target picks one. pub(crate) fn for_target( target: Target, database: Option<&str>, schema: Option<&str>, ) -> Option { let database = database.filter(|database| !database.is_empty())?; if !target.switches_database() { return None; } Some(Self { database: database.to_string(), schema: schema .filter(|schema| !schema.is_empty() && target.picks_schema()) .map(str::to_string), }) } /// The binding for a tab opened on the schema row `row` of a connection /// whose tree shape is `target`'s, under `database` where the row sits /// under one. Where the catalog lists databases as schemas, or a /// database's one schema is the database, the row is the database. pub(crate) fn for_schema_row( target: Target, database: Option<&str>, row: &str, ) -> Option { match target.levels() { Levels::Flat => None, Levels::DatabaseIsSchema | Levels::DatabaseHoldsObjects => { Self::for_target(target, Some(row), None) } Levels::DatabaseThenSchema => Self::for_target(target, database, Some(row)), } } } /// The second half of a loaded catalog. A catalog whose routines are not /// `Loaded` holds none, and a routine missing from it says nothing about the /// database. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Routines { Loading, Loaded, Failed, } /// Which surface the main pane is showing, and what a run targets. Both kinds /// of tab are addressed by id rather than by index, so closing one cannot land /// an in-flight result in its neighbour's grid. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Tab { Query(u64), Object(u64), } impl Tab { /// A key unique to this tab in this profile, for scroll state /// (`scroller::smooth_scoped`) that must not bleed into another tab or /// profile reusing the same id -- `next_query_id` and `next_object_id` /// each count from zero per profile, so a bare id collides across both /// kinds and across profiles. pub(crate) fn scroll_scope(&self, profile_id: &str) -> String { format!("{profile_id}-{self:?}") } } /// A chip of the tab strip. A file tab's is keyed by its path rather than its /// tab, which is what lets a rename keep the chip where it stands. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub(crate) enum TabKey { Unsaved(u64), File(PathBuf), Object(u64), } /// Untitled buffers, then file tabs, then objects, each kind in the order its /// tabs were opened. fn default_chips<'a>( queries: impl Iterator)> + Clone, objects: impl Iterator, ) -> Vec { queries .clone() .filter(|(_, path)| path.is_none()) .map(|(id, _)| TabKey::Unsaved(id)) .chain(queries.filter_map(|(_, path)| path.map(|path| TabKey::File(path.to_path_buf())))) .chain(objects.map(TabKey::Object)) .collect() } /// `chips` in default order, rearranged by the order the strip was last left /// in. A chip that order does not mention follows it. fn strip_order(mut chips: Vec, order: &[TabKey]) -> Vec { let mut ordered: Vec = order .iter() .filter(|key| chips.contains(key)) .cloned() .collect(); chips.retain(|key| !ordered.contains(key)); ordered.extend(chips); ordered } fn placed_last(mut order: Vec, key: TabKey) -> Vec { order.retain(|candidate| *candidate != key); order.push(key); order } fn moved(mut order: Vec, key: &TabKey, step: isize) -> Option> { let at = order.iter().position(|candidate| candidate == key)?; let to = at.checked_add_signed(step).filter(|to| *to < order.len())?; order.swap(at, to); Some(order) } /// The chip `step` places from `current` among `chips`, wrapping at either /// end as cycling tabs does. pub(crate) fn stepped(chips: &[T], current: T, step: isize) -> Option { let at = chips.iter().position(|chip| *chip == current).unwrap_or(0) as isize; chips .get((at + step).rem_euclid(chips.len().max(1) as isize) as usize) .copied() } /// The tab beside `closing` on the left, or on the right when it was the /// first: the chip the eye is already next to. fn neighbour(tabs: &[Tab], closing: Tab) -> Option { let at = tabs.iter().position(|tab| *tab == closing)?; at.checked_sub(1) .and_then(|left| tabs.get(left)) .or(tabs.get(at + 1)) .copied() } /// Who orders a view's rows on a header click. Per view, because a table read /// a page at a time and a query whose rows are all here want different /// answers; a new view starts from the Default sorting setting. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Sorting { /// The click goes into the statement's `ORDER BY` and the statement runs /// again, so the top of the sort is the table's, not the page's. Server, /// The click reorders the rows already held, by these keys: column /// expressions as `filter::sort_expression` writes them, so they follow a /// column by name into the next result. Nothing runs, and the statement /// keeps whatever `ORDER BY` it had. Client(Vec), } impl Sorting { pub(crate) fn new(client: bool) -> Self { match client { true => Self::Client(Vec::new()), false => Self::Server, } } /// This sorting, but in memory where the engine has no server sort to /// offer (`Engine::sorts_on_server`). pub(crate) fn on(self, engine: Engine) -> Self { match (self, engine.sorts_on_server()) { (Self::Server, false) => Self::Client(Vec::new()), (sorting, _) => sorting, } } pub(crate) fn client_keys(&self) -> Option<&[SortKey]> { match self { Self::Client(keys) => Some(keys), Self::Server => None, } } /// Switch between the server and memory, carrying across `shown`, the /// keys the rows on screen are in. Into memory they become the sort; into /// the server they come back as what it must now be asked for, `None` /// when there are none and nothing needs to run. pub(crate) fn switch(&mut self, client: bool, shown: Vec) -> Option> { match (client, &*self) { (true, Self::Server) => { *self = Self::Client(shown); None } (false, Self::Client(_)) => { *self = Self::Server; (!shown.is_empty()).then_some(shown) } _ => None, } } /// What a snapshot keeps: see `StoredGrid::client_sort`. pub(crate) fn stored(&self) -> Option> { self.client_keys().map(|keys| { keys.iter() .map(|key| (key.expression.clone(), key.ascending)) .collect() }) } pub(crate) fn restored(stored: Option<&[(String, bool)]>) -> Self { match stored { Some(keys) => Self::Client( keys.iter() .map(|(expression, ascending)| SortKey::new(expression.clone(), *ascending)) .collect(), ), None => Self::Server, } } } /// The file a query tab is bound to. pub(crate) struct FileBinding { /// Resolved through every link ([`sql_file::canonical`]), so one file is /// one path however it was reached. pub(crate) path: PathBuf, /// The text as last read from or written to `path`, or `None` while /// nothing is there: a tab whose file has gone has unsaved work whatever /// it holds, and says the file was deleted. pub(crate) saved: Option, pub(crate) bom: bool, /// `path`'s stamp as of that read or write, `None` while nothing is there. pub(crate) stamp: Option, pub(crate) conflict: Option, } /// The file changed on disk while its tab held changes of its own. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Conflict { /// The tab's bar asks Reload or Keep Mine. Asking, /// Keep Mine: the stamp is the file's again, so Save asks before writing /// over what someone else wrote. KeptMine, } /// What a look at a file tab's file does to the tab. #[derive(Debug, PartialEq, Eq)] pub(crate) enum Settle { Keep, /// The tab has nothing unsaved, so it takes the file as it is now. Reload, /// Raise the bar: reloading would lose what the tab holds. Ask, /// Nothing is there any more. Gone, } impl FileBinding { /// What a tab on this file does about `now`, the file's stamp as a look /// finds it, while it is `dirty` or not. pub(crate) fn settle(&self, now: Option, dirty: bool) -> Settle { match now { _ if now == self.stamp => Settle::Keep, None => Settle::Gone, Some(_) if self.conflict == Some(Conflict::Asking) => Settle::Keep, Some(_) if dirty => Settle::Ask, Some(_) => Settle::Reload, } } /// Whether Save asks before writing over the file whose stamp is `now`: /// someone else wrote it since the tab last read or wrote it, or did and /// the user chose to keep their own text. A file that has gone has /// nothing to overwrite, whatever was kept; one that could not be /// stat'ed is asked about only over a known conflict, the write saying /// what is wrong. /// /// An equal stamp is not trusted alone: a coarse clock, or a tool that /// keeps timestamps, leaves a same-length edit with the old one. So the /// file's text and byte order mark (`on_disk`, `None` when it will not /// read) are compared with the saved text, under the 4 MB cap a cheap /// read. pub(crate) fn overwrites( &self, now: &std::io::Result>, on_disk: impl FnOnce() -> Option<(String, bool)>, ) -> bool { match now { Ok(None) => false, Ok(Some(now)) => { self.conflict.is_some() || self.stamp != Some(*now) || on_disk().as_ref().map(|(text, bom)| (text.as_str(), *bom)) != self.saved.as_deref().map(|saved| (saved, self.bom)) } Err(_) => self.conflict.is_some(), } } } /// Whether a tab holding `text` has changes its file does not. Compared /// against the saved text rather than set by an edit, so an undo back to it /// clears the mark. pub(crate) fn is_dirty(file: Option<&FileBinding>, text: &str) -> bool { file.is_some_and(|file| file.saved.as_deref() != Some(text)) } /// When a view's edits are sent. `Classic`, the default, is how editing worked /// before a view had a mode: cell edits are held until Save shows their /// `UPDATE`s. `Draft` holds every edit until it is applied through the review. /// `Row` sends a row's `UPDATE` as the row is left or saved, with no review. /// Per view, because a table the user is correcting row by row and a result /// they are drafting a batch against want different answers; a new view starts /// from the Edit mode setting. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] pub(crate) enum EditMode { #[default] Classic, Draft, Row, } impl EditMode { /// This mode, but `Draft` where the target does not offer Row: Row is /// offered exactly where `Target::keeps_edits` holds, the targets whose edit /// send keeps the grid and is verified, so a Row send is never made on one /// that clears it. Classic and Draft are offered on every target. pub(crate) fn on(self, target: Target) -> Self { match (self, target.keeps_edits()) { (Self::Row, false) => Self::Draft, (mode, _) => mode, } } /// The modes a view on `target` can be put in, in menu order: the ones /// [`Self::on`] leaves as they are. pub(crate) fn offered(target: Target) -> impl Iterator { Self::ALL .into_iter() .filter(move |mode| mode.on(target) == *mode) } } impl EditMode { pub(crate) const ALL: [EditMode; 3] = [EditMode::Classic, EditMode::Draft, EditMode::Row]; pub(crate) fn slug(self) -> &'static str { match self { Self::Classic => "classic", Self::Draft => "draft", Self::Row => "row", } } /// Absent or unknown is `Classic`, how every view edited before there was /// a choice. pub(crate) fn from_slug(slug: Option<&str>) -> Self { Self::ALL .into_iter() .find(|mode| Some(mode.slug()) == slug) .unwrap_or_default() } pub(crate) fn label(self) -> &'static str { match self { Self::Classic => "Classic", Self::Draft => "Draft", Self::Row => "Row", } } } /// One query buffer, and everything that belongs to it. /// /// There used to be exactly one of these per profile, held directly on /// `Session`, and opening a saved query swapped its text in place. That is why /// `cmd+t` on a dirty scratch buffer persisted it and then cleared it: there /// was nowhere else for it to be. A buffer is a tab now, the same way an object /// is, and for the same reason -- addressed by id, so closing one cannot land /// another's result in its grid. pub(crate) struct QueryTab { pub(crate) id: u64, pub(crate) editor: Entity, pub(crate) results: Entity>, pub(crate) query: QueryState, /// The file this buffer is bound to, or `None` for an untitled one. Only /// Save writes it: a quit or a switch writes the buffer to this tab's own /// scratch file either way. pub(crate) file: Option, /// [`is_dirty`], as of the editor's last change. Held because the strip /// and the window's edited mark read it every frame, and a file can be /// megabytes long. pub(crate) dirty: bool, /// [`StoredText::scratch_unread`], for the tab's life: neither Save nor /// a close removes that file, the one copy of whatever it holds. pub(crate) scratch_unread: bool, /// The statement behind this tab's grid. /// /// Held rather than derived from the buffer, unlike the sort path, and a /// deliberate exception to that rule (in-grid editing spec, §4): applying /// edits appends the `UPDATE` to the buffer, so the cursor no longer sits on /// the `SELECT` and the text can no longer say where these rows came from. pub(crate) last_query: Option, /// Where in the buffer the statement last sent from it began, and its /// text. Taken by the run it was sent for once that run starts, so a run /// the mode gate stopped, or one refused while another was in flight, /// cannot re-label the error already on screen. pub(crate) sent_from: Option<(usize, String)>, /// The same for the statement behind `query`: what places an error's /// position in the buffer. `None` when the buffer did not supply it, as /// for a grid edit's or a sort's. pub(crate) ran_from: Option<(usize, String)>, /// Whether this tab's snapshot has been looked for yet. Set on the first /// attempt whether or not one was found, so a tab reached a second time /// cannot read the disk again and put stale rows over live ones. pub(crate) hydrated: bool, /// The last plan this tab asked for, or `None` until it asks for one. /// /// Kept beside the grid rather than over it, so flipping to the plan and /// back does not cost a re-run of either. A failed `EXPLAIN` is not here: /// it is a `QueryState::Failed` like any other, shown where every other /// statement's error is shown. pub(crate) plan: Option, /// Which of the two the results pane is showing. Deliberately not derived /// from `plan.is_some()`: a plan that has been read and flipped away from /// is still worth keeping to flip back to. pub(crate) showing_plan: bool, /// Whether the switcher's Messages chip is selected, in place of whichever /// result `queue.showing` names. A flag beside the index rather than a /// value of it, so selecting Messages leaves the result to come back to, /// and so a run with no queue at all can still offer it. pub(crate) showing_messages: bool, /// The multi-statement run this tab is part way through, or `None` for an /// ordinary single-statement run. `query` and `results` stay what they /// always were -- the slot being run or shown right now -- and the /// statements already finished are in `queue.done`. pub(crate) queue: Option, /// The slot's own grid and state, set aside while one of the queue's /// earlier results stands in as the slot: an edit applied to that result /// runs, and its rows are read again, on the profile's own connection, /// which is the session its statement ran on. pub(crate) lent: Option<(Entity>, QueryState)>, /// How many queued results this tab was written with, until it is /// hydrated and `queue` holds them. Taken by `hydrate_tab`, so a tab the /// user never looks at still reports what is on disk and keeps the prune /// off its files. pub(crate) queued_results: usize, /// Who orders this tab's rows on a header click. Per tab rather than per /// result: a queue's results are one view, read through one switcher. pub(crate) sorting: Sorting, /// How many rows of a statement's result this tab keeps, or `None` for /// all of them. Starts at the Settings row limit and is not persisted, so /// a limit picked for one tab lasts only as long as the tab does. pub(crate) row_limit: Option, /// Whether this tab's results pane is hidden, giving the editor the whole /// height. Per tab, like the row panel's fold, and not persisted. A run /// that has something to read clears it ([`reveals_results`]). pub(crate) results_hidden: bool, /// Whether this tab's row-inspector panel is folded away. Per tab, like /// the panel itself (see `RowPanel`), and not persisted. pub(crate) row_panel_folded: bool, /// Whether this tab's row panel shows inputs rather than values. Held as /// the fold is. pub(crate) row_panel_editing: bool, /// What this tab's row panel is filtered by. The field is one for the /// window (`RowPanel::search`); this is what it shows while the tab is in /// front. Not persisted. pub(crate) row_panel_filter: gpui::SharedString, /// The row-inspector split's state, per tab: a width dragged to in one /// tab must not resize another's. Not persisted -- a fresh tab always /// starts at the built-in default. pub(crate) row_panel_split: Entity, /// The database, and where the engine picks one the schema, this tab was /// opened for with New Query Here, or `None` for a tab that runs on the /// profile's own session. Kept for good: running the tab puts its /// session back here, and never moves the profile's own database or /// schema. pub(crate) binding: Option, } /// A plan, and what it is a plan of. #[derive(Debug, PartialEq)] pub(crate) struct Explained { pub(crate) plan: Plan, /// What `plan` means, derived once where the plan landed (or was restored) /// and only read from then on: the plan view draws from it, and the compact /// form prints from the same field. pub(crate) analysis: Analysis, pub(crate) mode: ExplainMode, /// The statement that was explained. Held because it is not necessarily /// what the buffer says any more -- the user is free to keep typing, and a /// plan that silently re-labels itself against edited text would be /// describing a statement nobody ran. pub(crate) sql: String, /// Typed by the user as an `EXPLAIN` rather than asked of the Explain /// command. Its rows are the grid's own, so there is no other Data to /// flip to. pub(crate) typed: bool, /// The Explain command's answer as it arrived, which the grid never holds, /// kept for the snapshot to parse again. Empty for a typed plan, whose /// rows are the grid's. pub(crate) columns: Vec, pub(crate) rows: Vec, } impl Explained { /// A plan an `engine` printed, read once into its [`Analysis`]. pub(crate) fn new( engine: Engine, plan: Plan, mode: ExplainMode, sql: String, typed: bool, columns: Vec, rows: Vec, ) -> Self { Self { analysis: Analysis::new(&plan, engine), plan, mode, sql, typed, columns, rows, } } pub(crate) fn stored(&self, showing: bool) -> store::StoredPlan { store::StoredPlan { mode: self.mode, sql: self.sql.clone(), typed: self.typed, showing, columns: self.columns.clone(), rows: self .rows .iter() .take(store::GRID_ROW_CAP) .cloned() .collect(), } } /// The plan a snapshot was written beside, parsed again from the rows it /// came from, and whether it was the one on screen. The engine comes from /// the profile the snapshot is restored into, never from the snapshot. pub(crate) fn restored(grid: &store::StoredGrid, engine: Engine) -> Option<(Self, bool)> { let stored = grid.plan.as_ref()?; let (columns, rows) = match stored.typed { true => (&grid.columns, &grid.rows), false => (&stored.columns, &stored.rows), }; let explained = Self::new( engine, explain::parse(columns, rows), stored.mode, stored.sql.clone(), stored.typed, stored.columns.clone(), stored.rows.clone(), ); Some((explained, stored.showing)) } } /// The statements a selection covers, run one at a time, and what each has /// produced so far. /// /// The buffer text is held rather than read back when a statement is sent: /// the user is free to keep typing while the queue runs, and every range in /// `remaining` is an offset into the text as it was when Run was /// pressed. /// /// Generic over the grid only so its bookkeeping can be checked without a /// window to build one in. pub(crate) struct Queue>> { pub(crate) sql: String, /// Statements not yet sent, in order. pub(crate) remaining: Vec>, /// One per statement already run, in order; for a queue run at once, /// one per statement from the start, waiting in `Idle` until it is sent. pub(crate) done: Vec>, /// Which of `done` is the result on screen, or `done.len()` for the /// statement still in flight, whose result is in the tab's own slot. /// /// A queue's results are read from `done` rather than swapped into the /// tab's `query`/`results`, so the slot a run writes to is never the slot /// the user is looking at. That is the whole reason an earlier result can /// be read while a later statement is still running. pub(crate) showing: usize, /// Whether a statement this queue sent is still out. /// /// Load-bearing: a finished queue stays on the tab so its results can be /// switched between, and every completion on that tab reaches the queue. /// Without this an ordinary Run, a header sort or a grid edit on such a /// tab would land in `done` as another of the queue's statements. pub(crate) awaiting: bool, /// One empty grid per statement still to run, built when the run started. /// /// Every statement needs its own, or the result stored in `done` is /// overwritten by the statement after it -- and the completion that lands /// a result runs on the executor, where there is no `Window` to build one /// with. ponytail: the whole queue's grids are allocated up front, which /// is the same count they reach anyway; take a window into /// `execute_unchecked` if one ever needs to be built later than this. pub(crate) spare: Vec, } /// A statement of a queue running at once with others, as it was issued: to /// which profile's connection, for which run (the token in the tab's slot, /// which names the run; each statement is stopped by a token of its own), and /// where it starts in [`Queue::sql`]. The profile is named rather than taken to be the /// one in front, which the user may have switched away from by the time it /// lands. #[derive(Clone)] pub(crate) struct Lane { pub(crate) profile: String, pub(crate) generation: u64, pub(crate) run: CancelToken, pub(crate) start: usize, } /// One statement of a queue that has run, with the result it produced. pub(crate) struct Finished>> { /// The statement that produced this result, which is both what the chip is /// labelled from and what the snapshot carries. Held rather than sliced out /// of [`Queue::sql`] on demand because a queue restored from disk has no /// text to slice: the statements are gone and the results are not. pub(crate) sql: String, /// Where the statement begins in [`Queue::sql`]. pub(crate) start: usize, pub(crate) state: QueryState, pub(crate) grid: G, } impl Queue { /// How many of the statements already in `done` were committed, said /// beside the failure of the one after them, which leaves them in place. /// Only when that is certain: never with a transaction open, a session /// setting changed (one may have turned autocommit off), or a statement /// of the queue's own having opened or ended a transaction or run a /// procedure or block that may have. pub(crate) fn committed_note(&self, engine: Engine, uncertain: bool) -> Option { if uncertain || self.done.iter().any(|finished| { sql::leaves(engine, &finished.sql).transaction.is_some() || sql::runs_unseen(engine, &finished.sql) }) { return None; } let committed = self .done .iter() .filter(|finished| { matches!( finished.state, QueryState::Complete { .. } | QueryState::Explained { .. } ) }) .count(); match committed { 0 => None, 1 => Some("1 statement before it was already committed.".into()), n => Some(format!("{n} statements before it were already committed.")), } } /// Whether its statements are running at once and not all back yet. Each /// is then in a slot of its own in `done`, which is what the status bar /// reads and Cancel stops, where a queue run in turn has its one statement /// out in the tab's slot. pub(crate) fn at_once(&self) -> bool { self.done.iter().any(|finished| { matches!( finished.state, QueryState::Running { .. } | QueryState::Idle ) }) } /// Where in `done` a statement running at once with others has its /// entry: found by where it starts, not by position, since a batch that /// lands more than one set puts results ahead of those still running. pub(crate) fn lane(&self, start: usize) -> Option { self.done .iter() .position(|finished| finished.start == start) } /// A submission's result sets after its first, put into `done` at `at` as /// results of their own, with the grids they will be shown in, and how /// many there was no grid for. A result being read past `at` stays the /// one on screen. /// /// The grids are the ones the run reserved, because the completion that /// lands them has no `Window` to build another with. /// /// ponytail: the reservation is one per statement in the batch, which is /// an upper bound for an ordinary batch and not for a procedure, a loop or /// a trigger; a set past the last spare is dropped and said so rather than /// shown. Take a window into `execute_unchecked` if a set has to be able /// to arrive unreserved. pub(crate) fn land_sets( &mut self, at: usize, start: usize, rest: Vec, ) -> (Vec<(G, QueryResult)>, usize) { let mut extra = Vec::new(); let mut dropped = 0; for (offset, set) in rest.into_iter().enumerate() { let Some(grid) = self.spare.pop() else { dropped += 1; continue; }; self.done.insert( at + extra.len(), Finished { // A set after the first has no statement of its own to be // named after: one batch produced them all, and the chip // says which of its results this is. sql: format!("Result {}", offset + 2), start, state: QueryState::Complete { rows: set.total_rows(), bytes: set.bytes, elapsed: set.elapsed, rows_affected: set.rows_affected, messages: Vec::new(), }, grid: grid.clone(), }, ); extra.push((grid, set)); } if self.showing >= at { self.showing += extra.len(); } (extra, dropped) } } impl Queue { /// Where the tab's slot sits in the strip: its entry in `done`, or one /// past the end for a slot that is none of them, which `QueryTab::shown` /// reads as the slot itself. pub(crate) fn slot_index(&self, slot: &G) -> usize { self.done .iter() .position(|finished| finished.grid == *slot) .unwrap_or(self.done.len()) } } /// Whether the plan is what the pane shows. Messages selected over it win, as /// the chip the user last picked; and only over the slot's result, the one /// the plan was asked of, so picking another of a queue's results shows it. pub(crate) fn plan_in_front(showing_plan: bool, messages_shown: bool, on_slot: bool) -> bool { showing_plan && !messages_shown && on_slot } /// `QueryTab::lend`, over the fields it touches so it is checkable without /// a window. A result already in the slot is not lent again, and an existing /// loan is kept, since a second would set the borrowed result aside as the /// slot's own. fn lend_slot( queue: Option<&Queue>, index: usize, (results, query): (&mut G, &mut QueryState), lent: &mut Option<(G, QueryState)>, ) { if lent.is_some() { return; } let Some(finished) = queue.and_then(|queue| queue.done.get(index)) else { return; }; if finished.grid == *results { return; } let grid = std::mem::replace(results, finished.grid.clone()); let state = std::mem::replace(query, finished.state.clone()); *lent = Some((grid, state)); } /// `QueryTab::give_back`. The lent result keeps the state its run ended in. /// An abandoned run (still `Running`, or idled by `drop_stale_run`) has /// already blanked its grid, so the result says so rather than keep a row /// count it no longer shows -- and never `Idle`, which a queue reads as a /// statement still waiting to be sent. fn give_slot_back( queue: Option<&mut Queue>, (results, query): (&mut G, &mut QueryState), lent: &mut Option<(G, QueryState)>, ) { let Some((grid, state)) = lent.take() else { return; }; let borrowed = std::mem::replace(results, grid); let left = match std::mem::replace(query, state) { QueryState::Running { .. } | QueryState::Idle => QueryState::Failed(DbError { message: "This result was interrupted. Run the statement again to see it.".into(), position: None, }), left => left, }; if let Some(finished) = queue.and_then(|queue| { queue .done .iter_mut() .find(|finished| finished.grid == borrowed) }) { finished.state = left; } } /// `QueryTab::apply_refresh`: on a queue's earlier result, that result read /// again in its own place; otherwise the statement behind the slot. `None` /// where dbdelve cannot say which statement produced the rows, as for a /// batch's set after its first, which has none of its own to ask again. fn apply_refresh( queue: Option<&Queue>, slot: &G, last_query: Option<&String>, ) -> Option { let earlier = queue.and_then(|queue| { let finished = queue.done.get(queue.showing)?; (finished.grid != *slot).then_some((queue, finished)) }); match earlier { Some((queue, finished)) => { (queue.lane(finished.start) == Some(queue.showing)).then(|| Refresh::Earlier { index: queue.showing, sql: finished.sql.clone(), verify: None, }) } None => last_query .cloned() .map(|sql| Refresh::Statement { sql, verify: None }), } } /// One statement's share of a run's server messages. #[derive(Debug, PartialEq)] pub(crate) struct Said<'a> { /// Where its chip sits in the switcher. pub(crate) index: usize, pub(crate) sql: &'a str, pub(crate) messages: &'a [String], } /// `QueryTab::messages`, over the fields it reads so it is checkable without /// a window: each of a queue's results, read as its chip reads it, or with no /// queue the slot's own, and only those the server said something during. fn run_messages<'a, G: PartialEq>( queue: Option<&'a Queue>, (results, query): (&G, &'a QueryState), ran: Option<&'a str>, ) -> Vec> { let said: Vec> = match queue { Some(queue) => queue .done .iter() .enumerate() .map(|(index, finished)| Said { index, sql: &finished.sql, messages: match finished.grid == *results { true => query.messages(), false => finished.state.messages(), }, }) .collect(), None => vec![Said { index: 0, sql: ran.unwrap_or_default(), messages: query.messages(), }], }; said.into_iter() .filter(|said| !said.messages.is_empty()) .collect() } const QUERY_LABEL_LIMIT: usize = 32; /// A statement as a switcher chip reads it: whitespace collapsed, clipped to /// what a chip can hold. pub(crate) fn query_label(statement: &str) -> String { let flat = statement.split_whitespace().collect::>().join(" "); match flat.char_indices().nth(QUERY_LABEL_LIMIT) { Some((end, _)) => format!("{}…", &flat[..end]), None => flat, } } /// What a finished statement leaves a queue to do. #[derive(Debug, PartialEq, Eq)] pub(crate) enum Step { Next(Range), /// The statement failed with more to run, so the user decides whether the /// rest still runs. Ask, Finished, } /// Split out of the completion handler so the one branch the queue turns on is /// checkable without a window. pub(crate) fn next_step(failed: bool, remaining: &[Range]) -> Step { match remaining.first() { // Nothing follows the failure, so there is nothing to decide. None => Step::Finished, Some(_) if failed => Step::Ask, Some(next) => Step::Next(next.clone()), } } /// How many of a queue's statements run at once, each on a connection of its /// own; the rest start as those finish. A bound on what one Run asks of the /// server's connection limit. pub(crate) const STATEMENTS_AT_ONCE: usize = 8; /// Whether a queue's statements can all go out at once rather than in turn: /// only when each is a plain read the gate lets through as it stands, and /// (`Profile::in_turn`, asked separately so it can be said) nothing run on the /// session so far makes a fresh connection read differently from it. Anything /// else runs in turn, as it always has. pub(crate) fn runs_at_once(engine: Engine, mode: Mode, statements: &[&str]) -> bool { statements.iter().all(|statement| { sql::plain_read(engine, statement) && sql::gate(&sql::classify(engine, statement), mode, &[]).is_none() }) } impl QueryTab { fn grids(&self) -> impl Iterator>> { std::iter::once(&self.results) .chain(self.lent.iter().map(|(grid, _)| grid)) .chain( self.queue .iter() .flat_map(|queue| queue.done.iter().map(|finished| &finished.grid)), ) } /// Whether the results pane offers Data and Plan to flip between. pub(crate) fn flips_to_plan(&self) -> bool { self.plan.as_ref().is_some_and(|plan| !plan.typed) } /// The result on screen: whichever of a queue's finished statements the /// switcher has selected, else the tab's own slot, which is what a run /// writes into. pub(crate) fn shown(&self) -> (&QueryState, &Entity>) { match self .queue .as_ref() .and_then(|queue| queue.done.get(queue.showing)) { Some(finished) => (self.state_of(finished), &finished.grid), None => (&self.query, &self.results), } } /// A queue's result as its chip reads it: the slot's live state for the /// result whose grid is the slot, which a run on it (an edit applied /// there, a refresh, a sort) is writing, and its own for the rest. pub(crate) fn state_of<'a>(&'a self, finished: &'a Finished) -> &'a QueryState { match finished.grid == self.results { true => &self.query, false => &finished.state, } } /// What the server said during this tab's run, statement by statement. pub(crate) fn messages(&self) -> Vec> { run_messages( self.queue.as_ref(), (&self.results, &self.query), self.ran_from.as_ref().map(|(_, sql)| sql.as_str()), ) } /// What the result switcher's chips select, left to right: a result by /// its index, then `None` for Messages. A statement not yet sent is not /// one, and neither is anything while the switcher is not drawn. pub(crate) fn switcher_chips(&self) -> Vec> { let mut chips: Vec> = match &self.queue { Some(queue) => queue .done .iter() .enumerate() .filter(|(_, finished)| !matches!(self.state_of(finished), QueryState::Idle)) .map(|(index, _)| Some(index)) .chain(queue.awaiting.then_some(Some(queue.done.len()))) .collect(), None => vec![Some(0)], }; if self.messages().is_empty() { if self.queue.is_none() { return Vec::new(); } } else { chips.push(None); } if chips.len() < 2 { return Vec::new(); } chips } /// The switcher chip selected, in the terms of [`QueryTab::switcher_chips`]. pub(crate) fn switcher_selected(&self) -> Option { match self.messages_shown() { true => None, false => Some(self.queue.as_ref().map_or(0, |queue| queue.showing)), } } /// Whether the pane is showing the run's messages rather than a result. /// Read through the messages themselves, so Messages left selected over a /// run that has since said nothing falls back to its result rather than /// an empty list. pub(crate) fn messages_shown(&self) -> bool { self.showing_messages && !self.messages().is_empty() } /// The plan, when it is what the results pane shows (`plan_in_front`). pub(crate) fn plan_shown(&self) -> Option<&Explained> { let on_slot = *self.shown().1 == self.results; plan_in_front(self.showing_plan, self.messages_shown(), on_slot) .then_some(self.plan.as_ref()) .flatten() } /// Bring the slot's result to the front, for a plan of it to be read. /// Whether that moved the switcher off another result. pub(crate) fn show_slot(&mut self) -> bool { self.showing_messages = false; let Some(queue) = &mut self.queue else { return false; }; let slot = queue.slot_index(&self.results); std::mem::replace(&mut queue.showing, slot) != slot } /// Make the queue's result at `index` the slot, for a run on its rows. pub(crate) fn lend(&mut self, index: usize) { lend_slot( self.queue.as_ref(), index, (&mut self.results, &mut self.query), &mut self.lent, ); } /// Put the slot back once the run on a lent result has ended. pub(crate) fn give_back(&mut self) { give_slot_back( self.queue.as_mut(), (&mut self.results, &mut self.query), &mut self.lent, ); } /// What runs after an edit applied to the rows on screen. pub(crate) fn apply_refresh(&self) -> Option { apply_refresh(self.queue.as_ref(), &self.results, self.last_query.as_ref()) } /// Read one stored buffer back off disk. /// /// Returns the message rather than reporting it: several tabs are restored /// at once and the session shows one notice, so the caller decides which /// failure is the one worth saying. A buffer that could not be read is /// empty either way, and silence would make it look like it never held /// anything. pub(crate) fn restore( profile_id: &str, stored: &store::StoredQueryTab, engine: Engine, sorting: Sorting, row_limit: Option, window: &mut Window, cx: &mut Context, ) -> (Self, Option) { let StoredText { file, text, notice, scratch_unread, } = stored_text(profile_id, stored); let mut tab = Self::new( profile_id, stored.id, text, file, engine, sorting, row_limit, window, cx, ); tab.scratch_unread = scratch_unread; tab.queued_results = stored.queued_results; // Kept as written, and handed to the driver as data on the first // run: a database the server no longer has fails that run with the // open's own words, and the tab stays bound to it. tab.binding = stored .database .clone() .filter(|database| !database.is_empty()) .map(|database| Binding { database, schema: stored.schema.clone().filter(|schema| !schema.is_empty()), }); (tab, notice) } #[allow(clippy::too_many_arguments)] pub(crate) fn new( profile_id: &str, id: u64, text: String, file: Option, engine: Engine, sorting: Sorting, row_limit: Option, window: &mut Window, cx: &mut Context, ) -> Self { let dirty = is_dirty(file.as_ref(), &text); let editor = cx.new(|cx| { EditorState::new(window, cx) .language(engine.syntax().highlighter()) .soft_wrap(false) .placeholder(engine.syntax().placeholder()) .default_value(text) }); cx.subscribe(&editor, { let profile_id = profile_id.to_string(); move |workspace, _, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { workspace.buffer_changed(&profile_id, id, cx); } } }) .detach(); Self { id, editor, results: result_grid::new_grid(window, cx), query: QueryState::Idle, file, dirty, scratch_unread: false, last_query: None, sent_from: None, ran_from: None, hydrated: false, plan: None, // A restored queue is rebuilt in `hydrate_tab`, which has the // window its grids need; it is never part way through, since // nothing of a run in flight is kept. queue: None, lent: None, queued_results: 0, sorting: sorting.on(engine), row_limit, showing_plan: false, showing_messages: false, results_hidden: false, row_panel_folded: false, row_panel_editing: false, row_panel_filter: Default::default(), row_panel_split: cx.new(|_| ResizableState::default()), binding: None, } } /// Whether [`Self::dirty`] moved, read again off the editor. pub(crate) fn refresh_dirty(&mut self, cx: &App) -> bool { let dirty = is_dirty(self.file.as_ref(), &self.editor.read(cx).value()); std::mem::replace(&mut self.dirty, dirty) != dirty } /// The file's name without its extension, as its chip shows it. pub(crate) fn file_stem(&self) -> Option { let path = &self.file.as_ref()?.path; Some( path.file_stem() .unwrap_or(path.as_os_str()) .to_string_lossy() .into_owned(), ) } pub(crate) fn stored(&self, active: bool) -> store::StoredQueryTab { store::StoredQueryTab { id: self.id, name: None, path: self.file.as_ref().map(|file| file.path.clone()), active, // The live queue is the truth once there is one; until the tab is // hydrated, what was written last time is. queued_results: self .queue .as_ref() .map_or(self.queued_results, |queue| queue.done.len()), database: self .binding .as_ref() .map(|binding| binding.database.clone()), schema: self .binding .as_ref() .and_then(|binding| binding.schema.clone()), // Only for a dirty tab: a clean one has nothing to lose to a file // changed while the app was closed. saved_hash: self .file .as_ref() .filter(|_| self.dirty) .and_then(|file| Some(sql_file::text_hash(file.saved.as_deref()?, file.bom))), kept_mine: self .file .as_ref() .is_some_and(|file| file.conflict == Some(Conflict::KeptMine)), asking: self .file .as_ref() .is_some_and(|file| file.conflict == Some(Conflict::Asking)), } } } /// An opened database object. It stays in the tab strip until it is closed, so /// coming back to a table does not mean finding it in the explorer again. pub(crate) struct ObjectTab { pub(crate) id: u64, pub(crate) schema: String, /// A relation's name, or a routine's name with its argument types — which /// is the only thing that tells two overloads of one function apart. pub(crate) name: String, /// `None` for a diagram, which is no sidebar row and must never answer /// for one. pub(crate) kind: Option, /// The database of the connection's server this tab's object is in, as the /// server listed it, or `None` for the connection's own. Every read and /// write the tab makes runs on that database's session /// ([`Profile::connection_for`]). pub(crate) database: Option, pub(crate) body: ObjectBody, } impl ObjectTab { /// Whether New row is offered here: on a relation the engine inserts into. pub(crate) fn takes_inserts(&self, target: Target) -> bool { matches!(self.kind, Some(ObjectKind::Relation(kind)) if target.takes_inserts(kind)) } /// Whether Import Rows is offered here. pub(crate) fn takes_imports(&self, target: Target) -> bool { matches!(self.kind, Some(ObjectKind::Relation(kind)) if target.takes_imports(kind)) } /// What the tab strip calls the tab: its relation's or routine's name, and /// a diagram's schema, since a diagram's own name is kept blank. pub(crate) fn label(&self) -> &str { match &self.body { ObjectBody::Diagram { .. } => &self.schema, ObjectBody::Relation { .. } | ObjectBody::Routine(_) | ObjectBody::Structure { .. } => { &self.name } } } /// The `WHERE` this tab reads the relation under, and `""` for a routine /// and for an unfiltered relation -- which is what makes an unfiltered tab /// dedupe exactly as it did before the filter joined the key. pub(crate) fn filter(&self) -> &str { match &self.body { ObjectBody::Relation { filter, .. } => filter, ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => { "" } } } /// The bars this tab's `WHERE` was derived from, the ones that narrow /// something only. pub(crate) fn filters(&self, engine: Engine) -> Vec { match &self.body { ObjectBody::Relation { filters, .. } => applied_filters(engine, &filter_bars(filters)) .iter() .map(stored_filter) .collect(), ObjectBody::Routine(_) | ObjectBody::Structure { .. } | ObjectBody::Diagram { .. } => { Vec::new() } } } pub(crate) fn stored(&self, engine: Engine, cx: &gpui::App) -> store::StoredObject { let diagram_view = match &self.body { ObjectBody::Diagram { view, .. } => Some(view.read(cx).stored()), ObjectBody::Relation { .. } | ObjectBody::Routine(_) | ObjectBody::Structure { .. } => { None } }; store::StoredObject { database: self.database.clone(), schema: self.schema.clone(), name: self.name.clone(), filter: self.filter().to_string(), filter_engine: (!self.filter().is_empty()).then(|| engine.as_str().to_string()), origin: match &self.body { ObjectBody::Structure { origin, .. } => origin.clone(), ObjectBody::Relation { .. } | ObjectBody::Routine(_) | ObjectBody::Diagram { .. } => None, }, // Nothing writes the two-field rows an older build did; they are // read once on the way in and superseded by `bars` on this save. filters: Vec::new(), bars: self.filters(engine), routine: matches!(self.kind, Some(ObjectKind::Routine(_))), structure: matches!(self.body, ObjectBody::Structure { .. }), diagram: diagram_view.is_some(), diagram_view, kind: match self.kind { Some(ObjectKind::Relation(kind)) => kind, // A sequence opens no tab, so this is never stored. Some(ObjectKind::Routine(_) | ObjectKind::Sequence) | None => { RelationKind::default() } }, active: false, } } } /// What the explorer -- or a session read back from disk -- hands over to open /// a tab. A routine arrives whole, because its body is already in the catalog. pub(crate) enum OpenedObject { Relation { schema: String, name: String, kind: RelationKind, /// The `WHERE` the tab opens under, empty for the whole relation. Part /// of the tab's identity (spec §6.3), so following a key opens a tab /// beside the relation's own rather than taking it over. filter: String, /// The bars `filter` was derived from, so the tab opens with the /// controls that produced it rather than with an expression nothing can /// edit. Derived and expression travel together for the length of the /// open: nothing parses one back into the other. filters: Vec, }, Structure { schema: String, name: String, kind: RelationKind, /// See `ObjectBody::Structure`'s. origin: Option, }, Routine { schema: String, routine: Routine, }, } impl OpenedObject { pub(crate) fn schema(&self) -> &str { match self { Self::Relation { schema, .. } | Self::Structure { schema, .. } | Self::Routine { schema, .. } => schema, } } pub(crate) fn name(&self) -> String { match self { Self::Relation { name, .. } | Self::Structure { name, .. } => name.clone(), Self::Routine { routine, .. } => routine_name(routine), } } pub(crate) fn kind(&self) -> ObjectKind { match self { Self::Relation { kind, .. } | Self::Structure { kind, .. } => { ObjectKind::Relation(*kind) } Self::Routine { routine, .. } => ObjectKind::Routine(routine.kind), } } pub(crate) fn filter(&self) -> &str { match self { Self::Relation { filter, .. } => filter, Self::Structure { .. } | Self::Routine { .. } => "", } } pub(crate) fn resolve( engine: Engine, catalog: &Catalog, stored: &store::StoredObject, ) -> Option { let schema = catalog .schemas .iter() .find(|schema| schema.name == stored.schema)?; if stored.routine { let routine = schema .routines .iter() .find(|routine| routine_name(routine) == stored.name)?; Some(Self::Routine { schema: schema.name.clone(), routine: routine.clone(), }) } else { let relation = schema .relations .iter() .find(|relation| relation.name == stored.name)?; let (filter, filters) = restored_filter(engine, stored); Some(Self::Relation { schema: schema.name.clone(), name: relation.name.clone(), kind: relation.kind, filter, filters, }) } } } /// The tab an object would reuse, if it has one. Dedup is on /// `(database, schema, name, filter)` rather than `(schema, name)` (spec /// §6.3), so `customers` and `customers WHERE id = 42` are two tabs, and /// `main.t` under two databases of one server is two. Fed an iterator /// rather than a session, so the invariant has a test that needs no window. pub(crate) fn matching_tab<'a>( open: impl Iterator, &'a str, &'a str, &'a str)>, database: Option<&str>, schema: &str, name: &str, filter: &str, ) -> Option { open.filter( |(_, candidate_database, candidate_schema, candidate_name, candidate_filter)| { *candidate_database == database && *candidate_schema == schema && *candidate_name == name && *candidate_filter == filter }, ) .map(|(id, ..)| id) .next() } /// What the catalog says a relation is. The only authority on it: a stored /// tab's kind is a cache of this, and can be a default rather than a kind. pub(crate) fn relation_kind(catalog: &Catalog, schema: &str, name: &str) -> Option { catalog_relation(catalog, schema, name).map(|relation| relation.kind) } pub(crate) fn catalog_relation<'a>( catalog: &'a Catalog, schema: &str, name: &str, ) -> Option<&'a Relation> { catalog .schemas .iter() .find(|candidate| candidate.name == schema)? .relations .iter() .find(|relation| relation.name == name) } /// A routine's name carries its argument types, because a schema can hold /// several routines with the same name and nothing else to tell them apart. pub(crate) fn routine_name(routine: &Routine) -> String { format!("{}({})", routine.name, routine.identity_arguments) } // One per open tab, and a routine tab is the rarity: boxing the relation's // fields would put an indirection on every one of them to save a few hundred // bytes per tab. #[allow(clippy::large_enum_variant)] pub(crate) enum ObjectBody { /// An opened relation: its rows, full height. Its definition is a tab of /// its own, [`ObjectBody::Structure`] (spec §3.2). /// /// No editor. A generated `SELECT` shown above the grid read as a query the /// user had written and invited edits to a buffer that then stopped being a /// view of the relation at all. The SQL dbdelve runs here is its own, and the /// only thing the user changes about it is the sort. Relation { structure: StructureState, results: Entity>, query: QueryState, /// The `ORDER BY` the header clicks have built up. dbdelve owns this /// statement, so sorting regenerates it rather than editing text. sort: Vec, /// Who orders these rows on a header click. A sort in memory orders /// this page alone, and is never written into `sort`, which is what /// the statement is rebuilt from. sorting: Sorting, /// When this view's edits are sent. Per view and never in the tab's /// snapshot, so a restored tab starts from the default. edit_mode: EditMode, /// The `WHERE` expression this preview narrows the relation by, without /// the keyword; empty means none. The fifth control of the same kind as /// the sort, the limit and the offset: a change regenerates the /// statement rather than patching it. Unlike `offset`, it persists in /// the tab's snapshot — a tab that forgot its filter would come back as /// a different tab. /// /// Derived from `filters` on every apply, never edited directly: it is /// what runs, what keys the snapshot and what the tab strip shows. filter: String, /// The filter bars, stacked above the grid, which are the editable /// state (spec §2.4). Per tab, because the filter is. filters: Vec, /// The joiner the next bar added will carry, shown on the "Add filter" /// row. Not persisted: it is a choice about a bar that does not exist /// yet, and a restart that forgot it has forgotten nothing. next_join: Conjunction, /// How many rows this preview asks for, `None` for every row. This is /// the tab's own copy of the cap, so raising it for one wide table does /// not raise it everywhere. limit: Option, /// How far into the relation this preview's page starts, in rows. /// Always a multiple of `limit`, and zero without one: paging moves it /// by one page, and a change of sort or limit puts it back to zero, /// because a window into an ordering that no longer exists is not a /// page of anything. offset: usize, /// Whether the rows on screen are owed a refresh that keeps them on /// screen until it lands: rows that came off disk or over a connection /// since replaced, which are refreshed on the tab's next activation /// rather than at startup or reconnect -- a session of restored tabs /// would otherwise open by firing one query per tab at a database /// nobody has looked at yet -- and rows a refresh has just been asked /// for. Spent by the run that refreshes them, or by the refusal of one /// that never could. stale: bool, /// Whether this tab's snapshot has been looked for yet. See /// [`QueryTab::hydrated`]. hydrated: bool, /// Whether this tab's row-inspector panel is folded away. Per tab: /// see `RowPanel`. row_panel_folded: bool, /// See [`QueryTab::row_panel_editing`]. row_panel_editing: bool, /// See [`QueryTab::row_panel_filter`]. row_panel_filter: gpui::SharedString, /// The row-inspector split's state, per tab. See /// [`QueryTab::row_panel_split`]. row_panel_split: Entity, /// `COUNT(*)` under the current `filter`, run only when the user asks: /// on a large table it is a full scan holding the connection. count: RowCount, /// The statement last sent, with the one it was paged from. An engine /// that pages by key writes the key's `ORDER BY` into the first, which /// the headers must not show as a sort the user chose. sent_from: Option<(String, String)>, }, /// A relation's definition, opened only when asked for. It runs no query: /// the structure is all it loads. Structure { structure: StructureState, /// Over whichever section its chips picked. grid: Entity>, /// The filter of the data tab that last switched here, which going back /// to Data returns to: a relation can have several, filtered ones among /// them, and its unfiltered rows are not the ones the user left. The /// filter rather than the id, because ids do not survive a restart. /// A filter edited since names no tab, and Data falls back to any. origin: Option, }, Routine(Routine), /// A schema's ER diagram. One per schema: the table in focus and where /// the cards are are the view's state, not the tab's identity. Diagram { view: Entity, /// The side connection the read runs on while it runs, so closing the /// tab can cancel it. Dropped when the read lands, so an open diagram /// holds no connection. side: Option>>, /// Read before a Refresh or a reconnect, so read again the next time /// the tab is looked at, with the old diagram on screen meanwhile. stale: bool, }, } /// A relation's row count, each state carrying the filter it was asked under so /// that an answer for an older filter is never shown under a newer one. pub(crate) enum RowCount { Unasked, /// In flight. `started` tells this run's answer from an earlier one's, and /// `cancelling` says a Cancel has gone out, as `QueryState::Running`'s does. Counting { filter: String, started: std::time::Instant, cancel: CancelToken, cancelling: bool, }, Counted(String, u64), } impl RowCount { pub(crate) fn answers(&self, filter: &str) -> bool { match self { Self::Unasked => false, Self::Counting { filter: asked, .. } | Self::Counted(asked, _) => asked == filter, } } } /// What the status bar says a relation tab's relation holds, or `None` to leave /// it to the rows on screen: a count the user asked for under the current /// filter, else the catalog's estimate for an unfiltered tab. /// /// No estimate when the first page came back short (`whole`), since that page /// is the whole relation and its own readout is exact; and none of zero unless /// it is `exact`, because zero is what a table never analyzed reads as on /// several engines, and claiming an empty table is the misleading way to be /// wrong. pub(crate) fn relation_rows( count: &RowCount, filter: &str, estimate: Option, exact: bool, whole: bool, ) -> Option { if let RowCount::Counted(asked, rows) = count && asked == filter { return Some(row_readout(*rows as usize, *rows as usize)); } let rows = estimate.filter(|_| filter.trim().is_empty() && !whole)? as usize; match exact { true => Some(row_readout(rows, rows)), false => (rows > 0).then(|| format!("\u{2248}{}", row_readout(rows, rows))), } } pub(crate) enum StructureState { Loading, Loaded(Structure), Failed(String), } /// Put a snapshot's rows on screen. pub(crate) fn show_snapshot( results: &Entity>, grid: &store::StoredGrid, mode: Mode, target: Target, cx: &mut Context, ) { results.update(cx, |table, cx| { *table.delegate_mut() = ResultGrid::restored(grid, mode).with_target(target); table.refresh(cx); }); } /// The state a tab restored from a snapshot is in. /// /// `Complete` rather than `Idle`, for two reasons: the rows are a result and /// the status bar has to be able to count them, and it is what makes /// `load_relation` leave a restored tab's rows alone instead of re-querying /// them the moment the tab is reached. The cost fields are zero because a /// snapshot knows none of them -- it is not the run, it is what the run left -- /// and the status readout says "snapshot" rather than reporting the zeroes. /// /// `rows` is the result's own size, which can be larger than the rows the grid /// holds: a snapshot is capped. `row_readout` is what says so, and /// `export_results` asks which rows to write rather than writing a short file /// unasked. pub(crate) fn restored_state(grid: &store::StoredGrid) -> QueryState { QueryState::Complete { rows: grid.total_rows, bytes: 0, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: grid.messages.clone(), } } /// What runs once a generated batch has succeeded. pub(crate) enum Refresh { /// The query tab's stashed `SELECT`. `verify` is what an applied edit's run /// is checked against (see `Relation`); `None` for the tab's own re-run. Statement { sql: String, verify: Option, }, /// A queue's earlier result, `index` in `done`, which the batch runs in: /// it is lent the slot as the batch starts, and `sql`, its own statement, /// reads it again there. On the profile's own connection rather than one /// of its own, which would see neither the session's settings and /// temporary tables nor a transaction the batch wrote into, and in its /// own grid, so the last result is never blanked for it. Earlier { index: usize, sql: String, verify: Option, }, /// `Earlier`'s re-read, which gives the slot back once it lands. That run /// is the user's statement and not dbdelve's, so it keeps the row limit. Return, /// A relation tab, refreshed the way its own controls refresh it — so it /// picks up whatever sort and row limit the tab is now set to. `verify` is /// what a reviewed draft's run is checked against, which a run held by the /// mode prompt keeps with it. Relation { id: u64, verify: Option, }, /// A Row-mode send of one row's `UPDATE`, whose verified step reads the row /// back by its key, landing in `row` of the grid whose rows are `rows_id`. /// No refresh of the relation follows: the row is replaced where it stands. Row { row: usize, rows_id: u64, /// The cells that went with the send, by column, which the landing /// clears: an edit staged on the row while it was out is not among them. sent: Vec<(usize, NewValue)>, /// The row the ring moved to when a row leave started the send, which a /// refusal puts the ring back from; `None` for Save, which does not /// move it. to: Option, /// What the user asked for that this row had to be saved before: a page /// turn, a sort, a tab switch. Carried out only when the send lands. then: Option, /// The row's one verified step: the row read again and compared before /// the `UPDATE`, the write counted, and the row read back inside the /// same transaction. A Row send without one is refused /// (`Workspace::execute_unchecked`). verify: Option, }, } impl Refresh { /// The refresh of a query tab's edit, carrying what the run is checked /// against. Any other refresh is returned as it is. pub(crate) fn verified(mut self, check: Option) -> Self { if let Self::Statement { verify, .. } | Self::Earlier { verify, .. } = &mut self { *verify = check; } self } /// The action a Row send was carrying, for a send that is dropped before /// it runs: its owner puts back what the action had changed. pub(crate) fn into_parked(self) -> Option { match self { Self::Row { then, .. } => then, _ => None, } } } /// `Clone` because a queue keeps the state of every statement it has run /// beside the one on screen; the clone is a finished slot, never a `Running` /// one. #[derive(Clone)] pub(crate) enum QueryState { Idle, /// `cancelling` says when a cancel was *sent* for this slot, and nothing /// more: the statement is still in flight, so this is still `Running` to /// everything that asks. It leaves the flag behind when it leaves the /// variant, which is why nothing resets it. `cancel` is what the run went /// out under, and all a cancel for this slot may stop. Running { started: std::time::Instant, cancelling: Option, cancel: CancelToken, }, Complete { rows: usize, bytes: usize, elapsed: std::time::Duration, rows_affected: Option, /// What the server said while running it (`QueryResult::messages`). /// On the state rather than the grid so it goes wherever the state /// goes: into a queue's `done`, through a lend and back, and onto a /// restored tab. messages: Vec, }, /// An `EXPLAIN` came back. Its own variant rather than a `Complete` because /// the rows it returned are not results and never reach the grid: the grid /// still holds whatever the last real run put there, and a readout claiming /// this many rows had just arrived would be describing the plan while /// pointing at someone else's data. Explained { elapsed: std::time::Duration, mode: ExplainMode, /// As `Complete`'s: an `EXPLAIN ANALYZE` runs the statement, and /// whatever it raises is said while it does. messages: Vec, }, Failed(DbError), } /// How many files a profile's recent list keeps. pub(crate) const RECENT_FILES_CAP: usize = 20; /// The recent files as `profiles.toml` holds them, as [`remember_recent`] /// would have left them: no saved query, each once, newest first, twenty. /// /// ponytail: compared as written, not resolved through links, since a stat /// per path at launch waits on a stalled mount as long as it does. Every /// path DBDelve writes is already resolved, so only a hand edit can list a /// file twice; resolving on the blocking pool with the look at launch is /// the upgrade. pub(crate) fn restored_recent(stored: Vec, query_directory: &Path) -> Vec { let mut recent = Vec::new(); for path in stored { if recent.len() == RECENT_FILES_CAP { break; } if path.parent() != Some(query_directory) && !recent.contains(&path) { recent.push(path); } } recent } fn still_missing( looked_at: u64, now: u64, gone: HashSet, recent: &[PathBuf], ) -> Option> { (looked_at == now).then(|| { gone.into_iter() .filter(|path| recent.contains(path)) .collect() }) } /// `path`, already resolved through its links, to the front of `recent`, once. pub(crate) fn remember_recent(recent: &mut Vec, path: PathBuf) { recent.retain(|held| *held != path); recent.insert(0, path); recent.truncate(RECENT_FILES_CAP); } /// The stored tabs, each holding a saved query by name as a build before file /// tabs wrote it, bound to that query's file instead. Nothing moves: the next /// Save writes the file where it is. fn adopted( stored: Vec, query_directory: &Path, ) -> Vec { stored .into_iter() .map(|mut stored| { if let Some(name) = stored.name.take() { stored.path = stored.path.or_else(|| { Some(sql_file::canonical( &query_directory.join(format!("{name}.sql")), )) }); } stored }) .collect() } /// What a stored tab comes back as. struct StoredText { file: Option, text: String, /// What went wrong reading the file or the scratch file. notice: Option, /// The scratch file is there, could not be read, and could not be moved /// aside: it may hold unsaved text the buffer does not, so nothing writes /// or removes it. scratch_unread: bool, } /// What a stored tab comes back as. An untitled tab holds its scratch file. /// A file tab holds its scratch file when it was left with unsaved text, /// which is what makes it come back dirty, and its file when not; one whose /// file has gone stays bound to it, holding what it last had. fn stored_text(profile_id: &str, stored: &store::StoredQueryTab) -> StoredText { let path = stored.path.as_deref().map(sql_file::canonical); let scratch = match &path { None => store::read_scratch(profile_id, stored.id), Some(_) => store::read_own_scratch(profile_id, stored.id), }; // Set aside, the tab is free to keep its unsaved text again; left where // it is, nothing may write or remove it, and so nothing keeps the tab's. let (scratch, notice, scratch_unread) = match scratch { Ok(scratch) => (scratch, None, false), Err(message) => match store::set_aside_scratch(profile_id, stored.id) { Ok(aside) => ( None, Some(format!("{message} It was kept as {}.", aside.display())), false, ), Err(_) => (None, Some(message), true), }, }; let Some(path) = path else { return StoredText { file: None, text: scratch.unwrap_or_default(), notice, scratch_unread, }; }; // ponytail: read on the window's thread, as the scratch files beside it // are, so a file on a stalled mount holds the launch; reading the bound // files on the blocking pool before the tabs are built is the upgrade. match sql_file::read(&path) { Ok(on_disk) => { let bom = on_disk.as_ref().is_some_and(|on_disk| on_disk.bom); let stamp = on_disk.as_ref().map(|on_disk| on_disk.stamp); let saved = on_disk.map(|on_disk| on_disk.text); let text = scratch.or_else(|| saved.clone()).unwrap_or_default(); let conflict = restored_conflict(stored, saved.as_deref(), bom, &text); StoredText { file: Some(FileBinding { path, saved, bom, stamp, conflict, }), text, notice, scratch_unread, } } // Unbound rather than bound to text nobody has seen: Save would put // the buffer over whatever the file holds. Err(message) => StoredText { file: None, text: scratch.unwrap_or_default(), notice: notice.or(Some(message)), scratch_unread, }, } } /// The conflict a file tab left with unsaved text comes back with, its file /// reading `saved` and its buffer `text`: the bar, when the file is not what /// that text was written against or the bar was left up, or Keep Mine, as it /// was left. fn restored_conflict( stored: &store::StoredQueryTab, saved: Option<&str>, bom: bool, text: &str, ) -> Option { let saved = saved.filter(|saved| *saved != text)?; match &stored.saved_hash { Some(hash) if *hash != sql_file::text_hash(saved, bom) => Some(Conflict::Asking), _ if stored.asking => Some(Conflict::Asking), _ => stored.kept_mine.then_some(Conflict::KeptMine), } } impl QueryState { pub(crate) fn messages(&self) -> &[String] { match self { QueryState::Complete { messages, .. } | QueryState::Explained { messages, .. } => { messages } _ => &[], } } } /// Write every one of a profile's buffers to its scratch file, or remove the /// scratch of a file tab with nothing unsaved. A scratch file that could not /// be read back is left as it is (`QueryTab::scratch_unread`). /// /// All of them rather than the one in front: a buffer that is not visible is /// still someone's unsaved work. The first failure is the one reported and /// the rest are still attempted — a full disk must not cost more buffers /// than it has to. pub(crate) fn write_buffer(profile: &Profile, cx: &App) -> Result<(), String> { let mut failure = None; for tab in profile .session .queries .iter() .filter(|tab| !tab.scratch_unread) { let sql = tab.editor.read(cx).value().to_string(); // Never the file itself: only Save writes the user's file. let written = match &tab.file { Some(file) if !is_dirty(Some(file), &sql) => store::delete_scratch(&profile.id, tab.id), _ => store::write_scratch(&profile.id, tab.id, &sql), }; if let Err(message) = written { failure = failure.or(Some(message)); } } match failure { Some(message) => Err(message), None => Ok(()), } } /// Snapshot every tab's grid, so reopening a profile shows the rows it was /// showing rather than an empty grid waiting on a re-run. /// /// Only a `Complete` tab is written: an empty or failed grid is not a result, /// and writing one would replace a good snapshot with nothing. Failures are /// dropped rather than reported, unlike the buffers this runs beside -- a cache /// that did not land costs a re-run, not somebody's unsaved work. /// /// A queue's results are written one per key beside the tab's own, each /// carrying its statement as `last_query`, which is what a restored chip is /// labelled from. They do not wait on the tab's own state: a statement that /// finished is a result whether or not the one after it is still running. pub(crate) fn write_grids(profile: &Profile, cx: &App) { for tab in &profile.session.queries { for (index, finished) in tab .queue .iter() .flat_map(|queue| queue.done.iter().enumerate()) { // A statement still running at once with others has rows in its // grid that are not yet its result. if !matches!(finished.state, QueryState::Complete { .. }) { continue; } let grid = finished.grid.read(cx).delegate().stored(); let messages = tab.state_of(finished).messages(); if grid.columns.is_empty() && messages.is_empty() { continue; } let _ = store::write_grid( &profile.id, &store::queued_grid_key(tab.id, index), &store::StoredGrid { last_query: Some(finished.sql.clone()), messages: messages.to_vec(), ..grid }, ); } // An `EXPLAIN` from the command leaves the grid as the last real run // did, and is written for the plan beside it. let explained = matches!(tab.query, QueryState::Explained { .. }); if !explained && !matches!(tab.query, QueryState::Complete { .. }) { continue; } let grid = tab.results.read(cx).delegate().stored(); let messages = tab.query.messages(); // A statement that returned no columns produced no grid to keep, only // whatever the server said running it. A write can still return one // (`RETURNING`, or any MongoDB reply), so a restored grid's // `last_query` is not safe to re-run as it stands. if grid.columns.is_empty() && !explained && messages.is_empty() { continue; } let _ = store::write_grid( &profile.id, &store::query_grid_key(tab.id), &store::StoredGrid { last_query: tab.last_query.clone(), client_sort: tab.sorting.stored(), plan: tab .plan .as_ref() .map(|explained| explained.stored(tab.showing_plan)), messages: messages.to_vec(), ..grid }, ); } for tab in &profile.session.objects { let ObjectBody::Relation { results, query, sort, sorting, filter, limit, .. } = &tab.body else { continue; }; if !matches!(query, QueryState::Complete { .. }) { continue; } let grid = results.read(cx).delegate().stored(); if grid.columns.is_empty() { continue; } let _ = store::write_grid( &profile.id, &store::object_grid_key_in(tab.database.as_deref(), &tab.schema, &tab.name, filter), &store::StoredGrid { limit: Some(limit.unwrap_or(0)), filter: filter.clone(), order_by: sort .iter() .map(|key| (key.expression.clone(), key.ascending)) .collect(), client_sort: sorting.stored(), ..grid }, ); } } /// The id the next new buffer gets. /// /// `stored` is what the profile last wrote, and the maximum over the open tabs /// is the floor: a profile written before the field was kept has none, and one /// written by a build that derived it could hand out an id a tab already holds. /// Never the derived value alone -- that decreases when the highest tab closes, /// and the reused id would hydrate the closed tab's snapshot. pub(crate) fn next_query_id(stored: u64, tabs: &[store::StoredQueryTab]) -> u64 { stored.max(tabs.iter().map(|tab| tab.id + 1).max().unwrap_or(0)) } /// Whether the rows on screen are only waiting to be replaced. A relation /// keeps its rows on screen while it is refreshed, and the result replaces the /// grid wholesale, edits staged on it included. A query tab's run blanks its /// grid first, but for an `EXPLAIN`, which never touches it. pub(crate) fn refreshing(active: Tab, query: Option<&QueryState>) -> bool { matches!(active, Tab::Object(_)) && matches!(query, Some(QueryState::Running { .. })) } pub(crate) fn result_pane_is_expanded(query: &QueryState) -> bool { !matches!(query, QueryState::Idle) } /// Whether a run that just landed brings a hidden results pane back: rows /// (or the columns of an empty set), a plan, an error and what the server /// said while running are answers the user would otherwise not know were /// there. A statement that returned nothing to read, a `CREATE TABLE` say, /// leaves the pane as it was. pub(crate) fn reveals_results(landed: &QueryState, produced_grid: bool) -> bool { produced_grid || match landed { QueryState::Failed(_) | QueryState::Explained { .. } => true, QueryState::Complete { messages, .. } => !messages.is_empty(), _ => false, } } /// The active schema where the engine picks one, the database where that is /// the schema, else the one the server put the session in: on SQL Server, the /// login's default. fn schema_in( target: Target, active: Option<&str>, database: Option, connected: Option<&str>, ) -> Option { match target.catalog_lists_databases() { true => database, false => active.or(connected).map(str::to_string), } } #[cfg(test)] mod tests { use super::*; #[test] fn a_metadata_read_waits_out_a_begin_being_sent_and_then_stays_off_its_transaction() { let connection = Connection::open(crate::db::ConnectionConfig::duckdb( crate::db::DUCKDB_IN_MEMORY.to_string(), 0, )) .expect("an in-memory database opens"); let run = |connection: &Connection, sql: &str| { connection.query( sql, &crate::db::CancelToken::default(), crate::db::Fetch::default(), ) }; let bound = Bound::new(connection); let read = Arc::new(AtomicBool::new(false)); // A tab's BEGIN holds the turn while it is sent (`Bound::leave`). let begin = bound.turn.lock().expect("the turn is free"); let reader = { let (bound, read) = (bound.clone(), read.clone()); std::thread::spawn(move || { bound.metadata(|connection| { read.store(true, Ordering::SeqCst); run( connection, "SELECT count(*) FROM duckdb_tables() WHERE table_name = 'uncommitted'", ) }) }) }; std::thread::sleep(std::time::Duration::from_millis(100)); assert!(!read.load(Ordering::SeqCst), "the read waits for the BEGIN"); bound.transaction.store(true, Ordering::SeqCst); run(&bound.connection, "BEGIN").expect("the transaction opens"); run(&bound.connection, "CREATE TABLE uncommitted (id INTEGER)").expect("created"); drop(begin); let counted = reader .join() .expect("the read does not panic") .expect("the read runs apart"); assert_eq!( counted.rows[0].iter().next().flatten(), Some("0"), "the read did not run inside the transaction" ); } #[test] fn a_hold_overtaken_by_a_newer_one_is_skipped_and_the_newer_one_sent() { let holds = HoldLine::default(); let read_only = holds.stamp(); let read_write = holds.stamp(); let mut sent = Vec::new(); assert!(matches!( holds.send(read_write, || { sent.push("read-write"); Ok(()) }), Ok(true) )); assert!(matches!( holds.send(read_only, || { sent.push("read-only"); Ok(()) }), Ok(false) )); assert_eq!(sent, ["read-write"]); assert!(holds.is_latest(read_write) && !holds.is_latest(read_only)); } #[test] fn read_only_runs_the_unreadable_unasked_only_once_its_hold_has_landed() { let unreadable = sql::classify(Engine::Postgres, "SELCT 1"); let gate = |own_run, mode, held| { sql::gate_own_run( &unreadable, mode, &[], skips_run_once(true, own_run, mode, held), ) }; assert_eq!(gate(true, Mode::ReadOnly, true), None); // On its way, or failed: the prompt, as if nobody had opted in. assert_eq!(gate(true, Mode::ReadOnly, false), Some(sql::Stop::RunOnce)); assert_eq!(gate(true, Mode::ReadWrite, false), None); assert_eq!(gate(false, Mode::ReadWrite, true), Some(sql::Stop::RunOnce)); } use crate::sql; fn complete() -> QueryState { QueryState::Complete { rows: 0, bytes: 0, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: Vec::new(), } } fn binding(database: &str, schema: Option<&str>) -> Binding { Binding { database: database.into(), schema: schema.map(str::to_string), } } #[test] fn only_a_database_or_a_picked_schema_makes_a_binding() { let target = Target::built_in; assert_eq!( Binding::for_target(target(Engine::Sqlite), Some("main"), None), None, "SQLite switches no database" ); assert_eq!( Binding::for_target(target(Engine::Postgres), Some(""), None), None, "a blank name is the login default, which is the profile's own session" ); assert_eq!( Binding::for_target(target(Engine::Postgres), None, Some("s")), None, "a schema alone names no database" ); assert_eq!( Binding::for_target(target(Engine::Postgres), Some("d"), Some("s")), Some(binding("d", Some("s"))) ); assert_eq!( Binding::for_target(target(Engine::Postgres), Some("d"), None), Some(binding("d", None)) ); assert_eq!( Binding::for_target(target(Engine::SqlServer), Some("d"), Some("s")), Some(binding("d", None)), "SQL Server picks no schema, so none is kept" ); } #[test] fn a_schema_row_binds_by_the_levels_of_its_connection() { let target = Target::built_in; assert_eq!( Binding::for_schema_row(target(Engine::MySql), None, "shop"), Some(binding("shop", None)), "MySQL lists a database as a schema" ); assert_eq!( Binding::for_schema_row(target(Engine::Redis), None, "db3"), Some(binding("db3", None)) ); assert_eq!( Binding::for_schema_row(target(Engine::Postgres), Some("app"), "billing"), Some(binding("app", Some("billing"))) ); assert_eq!( Binding::for_schema_row(target(Engine::Postgres), None, "billing"), None, "a schema whose database is not known binds nothing" ); assert_eq!( Binding::for_schema_row(target(Engine::Sqlite), None, "main"), None ); assert_eq!( Binding::for_schema_row(target(Engine::MySql), None, ""), None, "a blank row is never a database" ); } #[test] fn a_statement_that_returns_rows_shows_hidden_results_again() { assert!(reveals_results(&complete(), true)); } #[test] fn a_statement_with_nothing_to_read_leaves_hidden_results_hidden() { assert!(!reveals_results(&complete(), false)); } #[test] fn a_failed_statement_shows_hidden_results_so_its_error_is_seen() { let failed = QueryState::Failed(DbError { message: "relation already exists".into(), position: None, }); assert!(reveals_results(&failed, false)); } #[test] fn a_plan_shows_hidden_results_again() { let explained = QueryState::Explained { elapsed: std::time::Duration::ZERO, mode: ExplainMode::Plan, messages: Vec::new(), }; assert!(reveals_results(&explained, false)); } #[test] fn a_statement_that_only_sent_messages_shows_hidden_results_so_they_are_read() { let notice = QueryState::Complete { rows: 0, bytes: 0, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: vec!["NOTICE: vacuumed".into()], }; assert!(reveals_results(¬ice, false)); } #[test] fn a_failed_queue_statement_says_what_before_it_was_committed() { let complete = || QueryState::Complete { rows: 0, bytes: 0, elapsed: std::time::Duration::ZERO, rows_affected: Some(1), messages: Vec::new(), }; let failed = || { QueryState::Failed(DbError { message: "no".into(), position: None, }) }; let queue = |done: Vec<(&str, QueryState)>| Queue { sql: String::new(), remaining: Vec::new(), done: done .into_iter() .map(|(sql, state)| Finished { sql: sql.into(), start: 0, state, grid: (), }) .collect(), showing: 0, awaiting: true, spare: Vec::new(), }; let engine = Engine::Generic; let insert = "INSERT INTO t VALUES (1)"; assert_eq!(queue(vec![]).committed_note(engine, false), None); assert_eq!( queue(vec![(insert, complete())]).committed_note(engine, false), Some("1 statement before it was already committed.".into()) ); assert_eq!( queue(vec![ (insert, complete()), (insert, failed()), (insert, complete()) ]) .committed_note(engine, false), Some("2 statements before it were already committed.".into()) ); // A transaction open, or a session setting that may have turned // autocommit off, and nothing is claimed. assert_eq!( queue(vec![(insert, complete())]).committed_note(engine, true), None ); // Nor when the queue itself opened or ended one: a `ROLLBACK` took // back what came before it. for bracket in ["BEGIN", "ROLLBACK", "COMMIT"] { assert_eq!( queue(vec![(bracket, complete()), (insert, complete())]) .committed_note(engine, false), None, "{bracket}" ); } // Nor after a procedure or block whose statements the queue does not // show, which may have turned autocommit off or opened a transaction. for (engine, call) in [ (Engine::MySql, "CALL p()"), (Engine::MariaDb, "BEGIN NOT ATOMIC SET autocommit = 0; END"), (Engine::SqlServer, "EXEC p"), (Engine::SqlServer, "BEGIN EXEC p END"), (Engine::Postgres, "CALL p()"), (Engine::Postgres, "DO $$ BEGIN PERFORM 1; END $$"), (Engine::Generic, "CALL DELVETEST.P()"), ] { assert_eq!( queue(vec![(call, complete()), (insert, complete())]).committed_note(engine, false), None, "{engine:?} {call}" ); } } #[test] fn the_schema_a_session_is_in_is_its_database_or_its_default_where_none_is_picked() { let database = || Some("shop".to_string()); for engine in [Engine::MySql, Engine::MariaDb, Engine::ClickHouse] { assert_eq!( schema_in(Target::built_in(engine), None, database(), None).as_deref(), Some("shop"), "{engine:?}" ); } assert_eq!( schema_in( Target::built_in(Engine::SqlServer), None, database(), Some("sales") ) .as_deref(), Some("sales") ); assert_eq!( schema_in( Target::built_in(Engine::Postgres), Some("picked"), database(), Some("public") ) .as_deref(), Some("picked") ); } fn review_from(tab: Tab) -> ApplyReview { ApplyReview { tab, title: "Apply edits", sql: "UPDATE t SET a = 1".into(), notes: Vec::new(), error: None, edits: true, verify: None, ran_on: None, } } #[test] fn a_shortcut_names_the_database_the_shown_catalog_was_read_from() { let read_from = |database: Option<&str>| Catalog { database: database.map(str::to_string), ..Catalog::default() }; let opened_on = || Some("memory".to_string()); // A user's `USE other` then a refresh: the catalog is `other`'s, // whatever the profile was opened or picked on. assert_eq!( shortcut_database( Target::built_in(Engine::DuckDb), Some(&read_from(Some("other"))), opened_on ), ShortcutDatabase::On("other".into()) ); assert_eq!( shortcut_database( Target::built_in(Engine::DuckDb), Some(&read_from(None)), opened_on ), ShortcutDatabase::On("memory".into()) ); assert_eq!( shortcut_database(Target::built_in(Engine::DuckDb), None, || None), ShortcutDatabase::Unknown ); assert_eq!( shortcut_database( Target::built_in(Engine::MySql), Some(&read_from(Some("other"))), opened_on ), ShortcutDatabase::Unnamed ); } #[test] fn the_sidebar_opens_on_the_active_schema_or_where_databases_are_schemas_the_database() { let database = || Some("dbdelve_dev".to_string()); assert_eq!( explorer_opens_on(Target::built_in(Engine::Postgres), Some("public"), database), Some("public".into()) ); for listing_databases in [Engine::MySql, Engine::MariaDb, Engine::ClickHouse] { assert_eq!( explorer_opens_on(Target::built_in(listing_databases), None, database), Some("dbdelve_dev".into()) ); } // Its schemas are `dbo` and the like, never the database it is on. assert_eq!( explorer_opens_on(Target::built_in(Engine::SqlServer), None, database), None ); } #[test] fn shortcuts_read_back_less_what_cannot_be_read_or_repeats() { let entry = |query: Option<&str>, folder: Option<&str>, kind: Option<&str>| store::StoredShortcut { query: query.map(str::to_string), folder: folder.map(str::to_string), schema: Some("public".into()), name: Some("accounts".into()), kind: kind.map(str::to_string), ..Default::default() }; let folders = [ store::StoredFolder { name: "Hot".into(), members: vec![ entry(None, None, Some("table")), entry(None, None, Some("view")), entry(None, None, Some("trigger")), entry(Some("daily"), None, None), ], }, store::StoredFolder { name: "hot".into(), members: Vec::new(), }, ]; let pins = [ entry(None, Some("Hot"), None), entry(None, Some("Gone"), None), entry(Some("daily"), None, None), entry(Some("daily"), None, None), ]; let shortcuts = restored_shortcuts(&folders, &pins); assert_eq!(shortcuts.folders.len(), 1); let held = &shortcuts.folders[0].members; // A table and a view of one name are two objects. assert_eq!(held.len(), 3, "{held:?}"); assert_eq!(held[2], Member::Query("daily".into())); assert_eq!( shortcuts.pins, [ Pin::Folder("Hot".into()), Pin::Member(Member::Query("daily".into())) ] ); } #[test] fn a_review_covers_only_the_tab_it_was_written_from() { let review = review_from(Tab::Query(1)); assert!(review.covers(Tab::Query(1))); assert!(!review.covers(Tab::Query(2))); assert!(!review.covers(Tab::Object(1))); } fn slot(held: Option<&ApplyReview>, from: Tab, replaces_own: bool, open: bool) -> ReviewSlot { ReviewSlot::for_review_from(held, from, replaces_own, |_| open) } #[test] fn a_new_review_is_written_into_an_empty_slot() { assert_eq!(slot(None, Tab::Object(2), false, true), ReviewSlot::Free); assert_eq!(slot(None, Tab::Object(2), true, true), ReviewSlot::Free); } #[test] fn a_new_review_jumps_to_another_open_tab_holding_the_slot() { let held = review_from(Tab::Object(1)); assert_eq!( slot(Some(&held), Tab::Object(2), false, true), ReviewSlot::JumpTo(Tab::Object(1)) ); // Replacing is only ever of the tab's own review. assert_eq!( slot(Some(&held), Tab::Query(1), true, true), ReviewSlot::JumpTo(Tab::Object(1)) ); } #[test] fn a_review_held_by_a_closed_tab_is_stale_and_never_jumped_to() { let held = review_from(Tab::Object(1)); let mut asked = None; let decided = ReviewSlot::for_review_from(Some(&held), Tab::Object(2), false, |tab| { asked = Some(tab); false }); assert_eq!(decided, ReviewSlot::Stale); assert_eq!(asked, Some(Tab::Object(1))); } #[test] fn apply_edits_replaces_its_own_tabs_review() { let held = review_from(Tab::Object(1)); assert_eq!( slot(Some(&held), Tab::Object(1), true, true), ReviewSlot::Replace ); } #[test] fn other_creators_leave_their_own_tabs_review_in_place() { let held = review_from(Tab::Object(1)); assert_eq!( slot(Some(&held), Tab::Object(1), false, true), ReviewSlot::Refuse ); } #[test] fn staging_into_a_reviewed_grid_behind_the_active_tab_is_refused() { // Typed into tab 1's row panel, then tab 2 brought forward: the blur // stages into tab 1's grid, which its review is holding. let (owner, active) = (Tab::Object(1), Tab::Object(2)); let held = review_from(owner); assert!(!may_stage_into(Some(&held), false, owner)); assert!(may_stage_into(Some(&held), false, active)); } #[test] fn staging_behind_the_active_tab_is_allowed_while_only_the_active_tab_is_reviewed() { let (owner, active) = (Tab::Object(1), Tab::Object(2)); let held = review_from(active); assert!(may_stage_into(Some(&held), false, owner)); assert!(may_stage_into(Some(&held), false, Tab::Query(1))); assert!(may_stage_into(None, false, owner)); } #[test] fn staging_is_refused_while_rows_are_being_imported() { assert!(!may_stage_into(None, true, Tab::Object(1))); } fn form_on(tab: Tab) -> InsertForm { InsertForm { tab, schema: "public".into(), table: "t".into(), fields: Vec::new(), } } #[test] fn closing_a_tab_forgets_its_review_and_form() { for closed in [Tab::Object(1), Tab::Query(1)] { let mut form = Some(form_on(closed)); let mut review = Some(review_from(closed)); forget_tab(&mut form, &mut review, closed); assert!(form.is_none()); assert!(review.is_none()); } } #[test] fn closing_a_tab_leaves_another_tabs_review_and_form() { let mut form = Some(form_on(Tab::Object(2))); let mut review = Some(review_from(Tab::Object(2))); forget_tab(&mut form, &mut review, Tab::Object(1)); assert!(form.is_some_and(|form| form.tab == Tab::Object(2))); assert!(review.is_some_and(|review| review.tab == Tab::Object(2))); } #[test] fn discarding_one_tab_leaves_another_tabs_review_in_place() { let mut slot = Some(review_from(Tab::Object(1))); drop_review_of(&mut slot, Tab::Object(2)); assert!( slot.as_ref() .is_some_and(|review| review.tab == Tab::Object(1)) ); drop_review_of(&mut slot, Tab::Object(1)); assert!(slot.is_none()); } #[test] fn a_plan_survives_the_round_trip_through_a_snapshot() { let lines = || { crate::db::rows(vec![ vec![Some( "Seq Scan on t (cost=0.00..1.01 rows=1 width=4)".into(), )], vec![Some(" Filter: (a = 1)".into())], ]) }; let plan_columns = || vec!["QUERY PLAN".to_string()]; let grid = |columns: Vec, rows: Vec| { let mut grid: store::StoredGrid = serde_json::from_str(r#"{"columns":[],"rows":[],"total_rows":0}"#).unwrap(); grid.total_rows = rows.len(); (grid.columns, grid.rows) = (columns, rows); grid }; let typed = ( grid(plan_columns(), lines()), Explained::new( Engine::Postgres, explain::parse(&plan_columns(), &lines()), ExplainMode::Analyze, "EXPLAIN ANALYZE SELECT 1".into(), true, Vec::new(), Vec::new(), ), true, ); // The command's rows are its own: the grid still holds the last run's. let command = ( grid( vec!["id".into()], crate::db::rows(vec![vec![Some("1".into())]]), ), Explained::new( Engine::Postgres, explain::parse(&plan_columns(), &lines()), ExplainMode::Plan, "SELECT 1".into(), false, plan_columns(), lines(), ), false, ); for (grid, explained, showing) in [typed, command] { let snapshot = store::StoredGrid { plan: Some(explained.stored(showing)), ..grid }; let text = serde_json::to_string(&snapshot).unwrap(); let read: store::StoredGrid = serde_json::from_str(&text).unwrap(); assert!(!explained.plan.nodes.is_empty()); assert_eq!( Explained::restored(&read, Engine::Postgres), Some((explained, showing)) ); } } #[test] fn an_edit_mode_reads_back_from_its_slug_and_anything_else_is_classic() { assert_eq!(EditMode::default(), EditMode::Classic); assert_eq!( EditMode::ALL, [EditMode::Classic, EditMode::Draft, EditMode::Row] ); for mode in EditMode::ALL { assert_eq!(EditMode::from_slug(Some(mode.slug())), mode); } for unknown in [None, Some(""), Some("instant")] { assert_eq!( EditMode::from_slug(unknown), EditMode::Classic, "{unknown:?}" ); } assert_eq!( EditMode::Row.on(Target::built_in(Engine::Redis)), EditMode::Draft ); assert_eq!( EditMode::Row.on(Target::built_in(Engine::Postgres)), EditMode::Row ); for engine in Engine::ALL { for mode in [EditMode::Classic, EditMode::Draft] { assert_eq!(mode.on(Target::built_in(engine)), mode, "{engine:?}"); } } } #[test] fn row_mode_is_offered_on_mongodb_through_the_target_predicate() { assert_eq!( EditMode::Row.on(Target::built_in(Engine::MongoDb)), EditMode::Row ); for engine in [ Engine::Redis, Engine::ClickHouse, Engine::Snowflake, Engine::Turso, ] { assert_eq!( EditMode::Row.on(Target::built_in(engine)), EditMode::Draft, "{engine:?}" ); } let odbc = Box::leak(Box::new(crate::db::Plugin { id: "odbc".into(), name: "ODBC".into(), version: "1".into(), executable: "dbdelve-odbc".into(), })); let plugin = Target { engine: Engine::Postgres, driver: crate::db::Driver::Plugin(odbc), }; assert_eq!(EditMode::Row.on(plugin), EditMode::Draft); for engine in Engine::ALL .into_iter() .filter(|engine| Target::built_in(*engine).row_edits()) { assert_eq!( EditMode::Row.on(Target::built_in(engine)), EditMode::Row, "{engine:?}" ); } } #[test] fn a_views_sorting_survives_its_snapshot_and_an_unsorted_client_view_stays_client() { for sorting in [ Sorting::Server, Sorting::Client(Vec::new()), Sorting::Client(vec![ SortKey::new("\"name\"", false), SortKey::new("2", true), ]), ] { assert_eq!(Sorting::restored(sorting.stored().as_deref()), sorting); } } #[test] fn a_snapshot_and_settings_from_before_client_sorting_read_as_the_server() { let grid: store::StoredGrid = serde_json::from_str( r#"{"columns": ["id"], "rows": [["1"]], "total_rows": 1, "sort": [[0, false]], "order_by": [["\"id\"", false]]}"#, ) .expect("an older snapshot must still decode"); assert_eq!( Sorting::restored(grid.client_sort.as_deref()), Sorting::Server ); let settings: store::StoredSettings = toml::from_str("color_titlebar = true").expect("older settings must still decode"); assert_eq!(settings.client_sort, None); assert_eq!(settings.qualify_completions, None); assert_eq!(settings.alias_completions, None); assert_eq!( Sorting::new(settings.client_sort.unwrap_or(false)), Sorting::Server ); } #[test] fn settings_from_before_the_edit_mode_read_as_classic() { let read = |text: &str| -> store::StoredSettings { toml::from_str(text).expect("the settings must still decode") }; let settings = read("color_titlebar = true"); assert_eq!(settings.edit_mode, None); assert_eq!( EditMode::from_slug(settings.edit_mode.as_deref()), EditMode::Classic ); for mode in EditMode::ALL { let settings = read(&format!("edit_mode = \"{}\"", mode.slug())); assert_eq!(EditMode::from_slug(settings.edit_mode.as_deref()), mode); } for unreadable in ["instant", ""] { let settings = read(&format!("edit_mode = \"{unreadable}\"")); assert_eq!( EditMode::from_slug(settings.edit_mode.as_deref()), EditMode::Classic, "{unreadable:?}" ); } } #[test] fn switching_sorting_carries_the_sort_on_screen_across() { let shown = vec![SortKey::new("\"name\"", false)]; // Into memory: what the server sorted by becomes the sort. let mut sorting = Sorting::Server; assert_eq!(sorting.switch(true, shown.clone()), None); assert_eq!(sorting, Sorting::Client(shown.clone())); // Already there: nothing changes. assert_eq!(sorting.switch(true, Vec::new()), None); assert_eq!(sorting, Sorting::Client(shown.clone())); // Out of memory: the server is asked for what is on screen, which // leaves behind a key whose column a re-run dropped. let mut stale = Sorting::Client(vec![SortKey::new("\"gone\"", true), shown[0].clone()]); assert_eq!(stale.switch(false, shown.clone()), Some(shown.clone())); assert_eq!(stale, Sorting::Server); // Nothing sorted, nothing to ask for; and the server staying the // server runs nothing. let mut unsorted = Sorting::Client(Vec::new()); assert_eq!(unsorted.switch(false, Vec::new()), None); assert_eq!(unsorted, Sorting::Server); assert_eq!(unsorted.switch(false, shown), None); assert_eq!(unsorted, Sorting::Server); } #[test] fn a_scroll_scope_tells_apart_tabs_that_share_an_id() { // next_query_id and next_object_id each count from zero per profile, // so a query tab and an object tab in the same profile -- or the same // kind of tab in two profiles -- can share a bare id. assert_ne!( Tab::Query(1).scroll_scope("a"), Tab::Object(1).scroll_scope("a") ); assert_ne!( Tab::Query(1).scroll_scope("a"), Tab::Query(1).scroll_scope("b") ); assert_eq!( Tab::Query(1).scroll_scope("a"), Tab::Query(1).scroll_scope("a") ); } #[test] fn a_queue_asks_after_a_failure_only_when_something_is_left_to_run() { let remaining = [10..18, 20..27]; assert_eq!(next_step(false, &remaining), Step::Next(10..18)); assert_eq!(next_step(true, &remaining), Step::Ask); assert_eq!(next_step(true, &[]), Step::Finished); assert_eq!(next_step(false, &[]), Step::Finished); } #[test] fn only_plain_reads_run_at_once() { let at_once = |engine, statements: &[&str]| runs_at_once(engine, Mode::ReadOnly, statements); assert!(at_once( Engine::Postgres, &[ "SELECT pg_sleep(1), 1", "WITH a AS (SELECT 1) SELECT * FROM a" ] )); assert!(at_once(Engine::MySql, &["SELECT SLEEP(1)", "(SELECT 1)"])); // A batch of reads is one unit, however many sets it answers with. assert!(at_once( Engine::SqlServer, &["SELECT 1; SELECT 2", "SELECT 3"] )); assert!(at_once( Engine::MongoDb, &["db.a.find({})", "db.b.aggregate([{ $match: {} }])"] )); for unsafe_one in [ "INSERT INTO t VALUES (1)", "SELECT * INTO t2 FROM t", "WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d", "SET search_path TO other", "BEGIN", "COMMIT", "CREATE TEMPORARY TABLE t (a int)", "SELEC 1", ] { assert!( !at_once(Engine::Postgres, &["SELECT 1", unsafe_one]), "{unsafe_one}" ); } assert!(!at_once(Engine::MySql, &["USE other", "SELECT 1"])); assert!(!at_once( Engine::SqlServer, &["DECLARE @a int = 1; SELECT @a", "SELECT 1"] )); for unsafe_one in [ "db.a.aggregate([{ $out: 'b' }])", "db.a.aggregate([{ $merge: 'b' }])", "db.a.insertOne({ x: 1 })", ] { assert!( !at_once(Engine::MongoDb, &["db.a.find({})", unsafe_one]), "{unsafe_one}" ); } } #[test] fn a_statement_run_at_once_lands_in_its_own_entry_whatever_lands_ahead_of_it() { let entry = |start: usize, state: QueryState| Finished { sql: format!("SELECT {start}"), start, state, grid: start, }; let running = || QueryState::Running { started: std::time::Instant::now(), cancelling: None, cancel: CancelToken::alongside(), }; let complete = QueryState::Complete { rows: 1, bytes: 1, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: Vec::new(), }; let mut queue = Queue { sql: String::new(), remaining: Vec::new(), done: vec![ entry(0, running()), entry(30, complete.clone()), entry(60, running()), entry(90, QueryState::Idle), ], // Reading the statement that finished first. showing: 1, awaiting: false, spare: vec![100, 101], }; // The batch at 0 finishes last of the three and answers with three // sets: the two after its first go right behind it. let at = queue.lane(0).unwrap(); let (extra, dropped) = queue.land_sets(at + 1, 0, vec![QueryResult::default(); 2]); assert_eq!((extra.len(), dropped), (2, 0)); let labels: Vec<_> = queue.done.iter().map(|f| f.sql.as_str()).collect(); assert_eq!( labels, [ "SELECT 0", "Result 2", "Result 3", "SELECT 30", "SELECT 60", "SELECT 90" ] ); // Every statement still finds its own entry, not the one now at the // position it started in. assert_eq!(queue.lane(30), Some(3)); assert_eq!(queue.lane(60), Some(4)); assert_eq!(queue.done[4].grid, 60); assert_eq!(queue.lane(90), Some(5)); // And the result being read is still the one on screen. assert_eq!(queue.done[queue.showing].sql, "SELECT 30"); // A set past the last reserved grid is counted, not shown. let (extra, dropped) = queue.land_sets(5, 60, vec![QueryResult::default(); 1]); assert_eq!((extra.len(), dropped), (0, 1)); } #[test] fn a_runs_messages_stay_with_the_statements_that_said_them() { let said = |messages: &[&str]| QueryState::Complete { rows: 0, bytes: 0, elapsed: std::time::Duration::ZERO, rows_affected: Some(0), messages: messages.iter().map(|message| message.to_string()).collect(), }; let entry = |sql: &str, start: usize, state: QueryState, grid: usize| Finished { sql: sql.into(), start, state, grid, }; let mut queue = Queue { sql: String::new(), remaining: Vec::new(), done: vec![ entry("CREATE TABLE t (n int)", 0, said(&["created"]), 10), entry("SELECT 1", 30, said(&[]), 11), // The slot's: its live state is the one read, not what was // left here when it landed. entry("PRINT 'done'", 60, said(&["stale"]), 12), ], showing: 1, awaiting: false, spare: vec![13], }; // A batch's later sets carry none: the batch's are on its first. queue.land_sets(1, 0, vec![QueryResult::default()]); assert!(queue.done[1].state.messages().is_empty()); let slot = said(&["done", "twice"]); let strings = |messages: &[&str]| -> Vec { messages.iter().map(|message| message.to_string()).collect() }; let (created, done) = (strings(&["created"]), strings(&["done", "twice"])); assert_eq!( run_messages(Some(&queue), (&12, &slot), None), [ Said { index: 0, sql: "CREATE TABLE t (n int)", messages: &created, }, Said { index: 3, sql: "PRINT 'done'", messages: &done, }, ] ); // With no queue, the slot is the whole run. assert_eq!( run_messages::(None, (&12, &slot), Some("PRINT 'done'")), [Said { index: 0, sql: "PRINT 'done'", messages: &done, }] ); // A run that said nothing, or has not finished, offers no Messages. assert!(run_messages::(None, (&12, &said(&[])), Some("SELECT 1")).is_empty()); let running = QueryState::Running { started: std::time::Instant::now(), cancelling: None, cancel: CancelToken::default(), }; assert!(run_messages::(None, (&12, &running), Some("SELECT 1")).is_empty()); } #[test] fn a_plan_gives_way_to_messages_and_to_another_results_chip() { // Messages picked over the plan win; picking the plan's own result // chip clears them and shows the plan again. assert!(plan_in_front(true, false, true)); assert!(!plan_in_front(true, true, true)); // Another of a queue's results is shown as rows, plan or no plan. assert!(!plan_in_front(true, false, false)); assert!(!plan_in_front(false, false, true)); // A typed `EXPLAIN ANALYZE` reaches the switcher with what it raised. let notice = vec!["NOTICE: f() ran".to_string()]; let explained = QueryState::Explained { elapsed: std::time::Duration::ZERO, mode: ExplainMode::Analyze, messages: notice.clone(), }; assert_eq!( run_messages::(None, (&0, &explained), Some("EXPLAIN ANALYZE SELECT f()")), [Said { index: 0, sql: "EXPLAIN ANALYZE SELECT f()", messages: ¬ice, }] ); // The slot is found wherever it sits in the strip, and a slot that is // none of its results is the one past the end. let queue = finished_queue(0); assert_eq!(queue.slot_index(&12), 2); assert_eq!(queue.slot_index(&99), queue.done.len()); } #[test] fn a_snapshot_keeps_its_messages_and_one_from_before_them_has_none() { let older: store::StoredGrid = serde_json::from_str(r#"{"columns": [], "rows": [], "total_rows": 0}"#) .expect("an older snapshot must still decode"); assert!(restored_state(&older).messages().is_empty()); let said = store::StoredGrid { messages: vec!["Changed database context to 'dbdelve_dev'.".into()], ..older }; let read: store::StoredGrid = serde_json::from_str(&serde_json::to_string(&said).unwrap()).unwrap(); assert_eq!(restored_state(&read).messages(), said.messages); } fn finished_queue(showing: usize) -> Queue { let complete = QueryState::Complete { rows: 1, bytes: 1, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: Vec::new(), }; // A batch at 0 that answered with two sets, then a statement at 40, // whose grid is the slot's. let entry = |sql: &str, start: usize, grid: usize| Finished { sql: sql.into(), start, state: complete.clone(), grid, }; Queue { sql: String::new(), remaining: Vec::new(), done: vec![ entry("SELECT 0", 0, 10), entry("Result 2", 0, 11), entry("SELECT 40", 40, 12), ], showing, awaiting: false, spare: Vec::new(), } } #[test] fn an_edit_on_an_earlier_result_reads_that_result_again() { let last = Some("SELECT 40".to_string()); assert!(matches!( apply_refresh(Some(&finished_queue(0)), &12, last.as_ref()), Some(Refresh::Earlier { index: 0, sql, .. }) if sql == "SELECT 0" )); // A batch's later set has no statement of its own to ask again, and // the slot's is not it. assert!(apply_refresh(Some(&finished_queue(1)), &12, last.as_ref()).is_none()); assert!(matches!( apply_refresh(Some(&finished_queue(2)), &12, last.as_ref()), Some(Refresh::Statement { sql, .. }) if sql == "SELECT 40" )); assert!(matches!( apply_refresh(None::<&Queue>, &12, last.as_ref()), Some(Refresh::Statement { .. }) )); assert!(apply_refresh(Some(&finished_queue(2)), &12, None).is_none()); } #[test] fn a_lent_slot_comes_back_with_the_result_keeping_how_its_run_ended() { let failed = || { QueryState::Failed(DbError { message: "denied".into(), position: None, }) }; let mut queue = Some(finished_queue(0)); let (mut results, mut query, mut lent) = (12, QueryState::Idle, None); lend_slot(queue.as_ref(), 0, (&mut results, &mut query), &mut lent); assert_eq!(results, 10); assert!(matches!(query, QueryState::Complete { .. })); // A second loan would lose the slot's own grid. lend_slot(queue.as_ref(), 1, (&mut results, &mut query), &mut lent); assert_eq!(results, 10); query = failed(); give_slot_back(queue.as_mut(), (&mut results, &mut query), &mut lent); assert_eq!(results, 12); assert!(matches!(query, QueryState::Idle)); assert!(matches!( queue.as_ref().unwrap().done[0].state, QueryState::Failed(_) )); assert!(lent.is_none()); // An abandoned run's result says its rows are gone, without reading // as a statement still to send. lend_slot(queue.as_ref(), 1, (&mut results, &mut query), &mut lent); query = QueryState::Idle; give_slot_back(queue.as_mut(), (&mut results, &mut query), &mut lent); assert!(matches!( queue.as_ref().unwrap().done[1].state, QueryState::Failed(_) )); // The slot's own result is never lent to itself. lend_slot(queue.as_ref(), 2, (&mut results, &mut query), &mut lent); assert!(lent.is_none()); } #[test] fn a_queue_reads_as_at_once_only_while_a_statement_of_it_is_out() { let entry = |start: usize, state: QueryState| Finished { sql: format!("SELECT {start}"), start, state, grid: start, }; let complete = QueryState::Complete { rows: 1, bytes: 1, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: Vec::new(), }; let queue = |done| Queue { sql: String::new(), remaining: Vec::new(), done, showing: 0, awaiting: false, spare: Vec::::new(), }; let running = QueryState::Running { started: std::time::Instant::now(), cancelling: None, cancel: CancelToken::alongside(), }; assert!(queue(vec![entry(0, complete.clone()), entry(9, running)]).at_once()); assert!(queue(vec![entry(0, complete.clone()), entry(9, QueryState::Idle)]).at_once()); // Finished, or run in turn: the statement out is in the tab's slot. assert!(!queue(vec![entry(0, complete.clone()), entry(9, complete)]).at_once()); assert!(!queue(Vec::new()).at_once()); } #[test] fn a_query_label_is_one_clipped_line() { assert_eq!(query_label("SELECT\n 1"), "SELECT 1"); assert_eq!( query_label("SELECT a, b, c, d, e, f, g, h FROM accounts"), "SELECT a, b, c, d, e, f, g, h FR…" ); } #[test] fn a_count_answers_only_the_filter_it_was_asked_under() { let count = RowCount::Counted("id > 3".into(), 40); assert!(count.answers("id > 3")); assert!(!count.answers("")); assert!(!RowCount::Unasked.answers("")); let counting = RowCount::Counting { filter: String::new(), started: std::time::Instant::now(), cancel: CancelToken::default(), cancelling: false, }; assert!(counting.answers("")); assert_eq!(relation_rows(&counting, "", None, false, false), None); } #[test] fn the_status_bar_shows_a_count_over_an_estimate_and_neither_when_unsure() { let unasked = RowCount::Unasked; let counted = RowCount::Counted("id > 3".into(), 1_234); assert_eq!( relation_rows(&unasked, "", Some(1_000_000), false, false).as_deref(), Some("\u{2248}1,000,000 rows") ); // Snowflake's count is the table's, not a sample's. assert_eq!( relation_rows(&unasked, "", Some(1_000_000), true, false).as_deref(), Some("1,000,000 rows") ); assert_eq!( relation_rows(&counted, "id > 3", Some(1_000_000), false, false).as_deref(), Some("1,234 rows") ); // An estimate is of the whole table, so it says nothing under a filter, // and a count asked under another filter says nothing under this one. assert_eq!( relation_rows(&unasked, "id > 3", Some(9), false, false), None ); assert_eq!(relation_rows(&counted, "id > 4", None, false, false), None); // A never-analyzed table's zero, and a short first page whose own // readout is already exact. assert_eq!(relation_rows(&unasked, "", Some(0), false, false), None); assert_eq!( relation_rows(&unasked, "", Some(0), true, false).as_deref(), Some("0 rows") ); assert_eq!(relation_rows(&unasked, "", Some(900), false, true), None); assert_eq!(relation_rows(&unasked, "", None, false, false), None); } #[test] fn one_relation_and_one_filter_is_one_tab() { let open = [ (7u64, None, "public", "customers", ""), (9u64, None, "public", "customers", r#""id" = '42'"#), ]; assert_eq!( matching_tab(open.iter().copied(), None, "public", "customers", ""), Some(7) ); assert_eq!( matching_tab( open.iter().copied(), None, "public", "customers", r#""id" = '42'"# ), Some(9) ); } #[test] fn a_tabs_identity_includes_its_database() { let open = [ (7u64, Some("other"), "main", "t", ""), (9u64, None, "main", "t", ""), ]; assert_eq!( matching_tab(open.iter().copied(), Some("other"), "main", "t", ""), Some(7) ); assert_eq!( matching_tab(open.iter().copied(), None, "main", "t", ""), Some(9), "no database matches only a tab with none" ); assert_eq!( matching_tab(open.iter().copied(), Some("third"), "main", "t", ""), None ); assert_eq!( matching_tab(open[..1].iter().copied(), None, "main", "t", ""), None, "a tab of another database is not the profile's own" ); } #[test] fn a_filtered_relation_does_not_take_over_the_unfiltered_tab() { // The invariant this tier changes: following a key cannot clobber what // the relation's own tab was showing. let open = [(7u64, None, "public", "customers", "")]; assert_eq!( matching_tab( open.iter().copied(), None, "public", "customers", r#""id" = '42'"# ), None ); } #[test] fn two_schemas_can_hold_a_relation_of_the_same_name_and_filter() { let open = [(7u64, None, "public", "customers", r#""id" = '42'"#)]; assert_eq!( matching_tab( open.iter().copied(), None, "archive", "customers", r#""id" = '42'"# ), None ); } #[test] fn a_field_nobody_touched_is_left_out_so_the_servers_default_applies() { // The whole design of the form in one function: absent, NULL, or a // value -- and the first of those is not a value at all. assert_eq!(insert_value(false, false, ""), None); assert_eq!(insert_value(true, false, ""), Some(None)); // Typed and emptied is a value: `''` has to be reachable. assert_eq!(insert_value(false, true, ""), Some(Some(String::new()))); assert_eq!( insert_value(false, true, "42"), Some(Some("42".to_string())) ); // The form keeps the two exclusive; if both were ever set, NULL is the // answer that cannot send stray text. assert_eq!(insert_value(true, true, "42"), Some(None)); } #[test] fn an_emptied_field_reads_as_left_out_where_the_engine_drops_it() { assert_eq!(insert_placeholder(false, true, true), "empty string"); assert!(!insert_left_out(false, true, true, "")); assert_eq!(insert_placeholder(false, true, false), "DEFAULT"); assert!(insert_left_out(false, true, false, "")); assert!(!insert_left_out(false, true, false, "42")); assert_eq!(insert_placeholder(true, false, false), "NULL"); assert!(!insert_left_out(true, false, false, "")); } #[test] fn a_half_filled_form_names_only_the_columns_it_filled() { // `id` untouched so the sequence fills it, `note` deliberately nulled, // `bio` typed and emptied so it inserts an empty string. let filled: Vec<(String, Option)> = [ ("id", false, false, ""), ("name", false, true, "Ada"), ("note", true, false, ""), ("bio", false, true, ""), ] .into_iter() .filter_map(|(column, nulled, touched, typed)| { insert_value(nulled, touched, typed).map(|value| (column.to_string(), value)) }) .collect(); let borrowed: Vec<(&str, Option<&str>)> = filled .iter() .map(|(column, value)| (column.as_str(), value.as_deref())) .collect(); let statement = sql::insert_row(Engine::Postgres, "public", "accounts", &borrowed, &[]).unwrap(); assert_eq!( statement, r#"INSERT INTO "public"."accounts" ("name", "note", "bio") VALUES ('Ada', NULL, '')"# ); assert!( sql::is_generated_write(&statement), "{statement} was refused" ); } #[test] fn the_recent_files_restore_without_saved_queries_or_repeats_and_keep_twenty() { let queries = Path::new("/support/queries/e2e"); let path = |n: usize| PathBuf::from(format!("/work/{n}.sql")); let mut stored = vec![path(0), queries.join("q.sql"), path(1), path(0)]; stored.extend((2..30).map(path)); let recent = restored_recent(stored, queries); assert_eq!(recent.len(), RECENT_FILES_CAP); assert_eq!(recent[..3], [path(0), path(1), path(2)]); assert_eq!(recent[19], path(19)); } #[test] fn a_look_at_the_recent_files_lands_only_if_nothing_changed_since() { let gone: HashSet = [PathBuf::from("/a.sql"), PathBuf::from("/b.sql")].into(); let recent = [PathBuf::from("/a.sql")]; assert_eq!(still_missing(3, 4, gone.clone(), &recent), None); assert_eq!( still_missing(4, 4, gone, &recent), Some([PathBuf::from("/a.sql")].into()) ); } #[test] fn the_recent_files_put_the_newest_first_once_and_keep_twenty() { let path = |n: usize| PathBuf::from(format!("/work/{n}.sql")); let mut recent = Vec::new(); for n in 0..25 { remember_recent(&mut recent, path(n)); } assert_eq!(recent.len(), RECENT_FILES_CAP); assert_eq!(recent[0], path(24)); assert_eq!(recent[19], path(5)); remember_recent(&mut recent, path(10)); assert_eq!(recent[0], path(10)); assert_eq!(recent.len(), RECENT_FILES_CAP); assert_eq!(recent.iter().filter(|held| **held == path(10)).count(), 1); } #[test] fn a_tab_holding_a_saved_query_by_name_is_bound_to_its_file_where_it_is() { let tab = |name: Option<&str>, path: Option<&str>| store::StoredQueryTab { id: 3, name: name.map(str::to_string), path: path.map(PathBuf::from), active: true, queued_results: 0, database: None, schema: None, saved_hash: None, kept_mine: false, asking: false, }; let adopted = adopted( vec![ tab(Some("daily"), None), tab(None, None), tab(None, Some("/q/a.sql")), ], Path::new("/support/queries/dev"), ); // Resolved, it is on the current drive on Windows. let daily = sql_file::canonical(Path::new("/support/queries/dev/daily.sql")); assert_eq!( adopted, [ store::StoredQueryTab { path: Some(daily), ..tab(None, None) }, tab(None, None), tab(None, Some("/q/a.sql")), ] ); } #[cfg(unix)] #[test] fn a_saved_query_that_is_a_link_is_bound_to_the_file_it_leads_to() { store::tests::with_home(|| { let home = sql_file::canonical(&store::home().unwrap()); let (queries, target) = (home.join("queries"), home.join("shared.sql")); std::fs::create_dir_all(&queries).unwrap(); std::fs::write(&target, "SELECT 1").unwrap(); std::os::unix::fs::symlink(&target, queries.join("daily.sql")).unwrap(); let stored = |name: Option<&str>, path: Option| store::StoredQueryTab { id: 3, name: name.map(str::to_string), path, active: true, queued_results: 0, database: None, schema: None, saved_hash: None, kept_mine: false, asking: false, }; let adopted = adopted(vec![stored(Some("daily"), None)], &queries); assert_eq!(adopted, [stored(None, Some(target.clone()))]); let restored = stored_text("dev", &stored(None, Some(queries.join("daily.sql")))); assert_eq!(restored.file.map(|file| file.path), Some(target)); }); } #[test] fn a_file_tab_comes_back_holding_its_unsaved_text_and_stays_bound_when_its_file_goes() { store::tests::with_home(|| { let path = sql_file::canonical(&store::home().unwrap().join("q.sql")); std::fs::write(&path, "SELECT 1").unwrap(); let stored = store::StoredQueryTab { id: 3, name: None, path: Some(path.clone()), active: true, queued_results: 0, database: None, schema: None, saved_hash: None, kept_mine: false, asking: false, }; let StoredText { file, text, notice, .. } = stored_text("dev", &stored); assert_eq!(text, "SELECT 1"); assert!(!is_dirty(file.as_ref(), &text)); assert_eq!(notice, None); store::write_scratch("dev", 3, "SELECT 2").unwrap(); let StoredText { file, text, .. } = stored_text("dev", &stored); assert_eq!(text, "SELECT 2"); assert!(is_dirty(file.as_ref(), &text)); std::fs::remove_file(&path).unwrap(); store::delete_scratch("dev", 3).unwrap(); let StoredText { file, text, .. } = stored_text("dev", &stored); let file = file.expect("still bound"); assert_eq!((file.path.as_path(), text.as_str()), (path.as_path(), "")); assert!( is_dirty(Some(&file), &text), "nothing on disk is unsaved work" ); }); } #[test] fn dirty_is_whether_the_text_differs_from_the_saved_text() { let file = FileBinding { path: PathBuf::from("/q/a.sql"), saved: Some("SELECT 1".into()), bom: false, stamp: None, conflict: None, }; assert!( !is_dirty(None, "anything"), "an untitled tab is never dirty" ); assert!(is_dirty(Some(&file), "SELECT 12")); assert!(!is_dirty(Some(&file), "SELECT 1"), "an undo back clears it"); } fn file_read_at(stamp: sql_file::Stamp) -> FileBinding { FileBinding { path: PathBuf::from("/q/a.sql"), saved: Some("SELECT 1".into()), bom: false, stamp: Some(stamp), conflict: None, } } #[test] fn a_file_changed_on_disk_reloads_a_clean_tab_and_asks_a_dirty_one() { let (read, written) = (sql_file::Stamp::of_len(8), sql_file::Stamp::of_len(9)); let mut file = file_read_at(read); assert_eq!(file.settle(Some(read), true), Settle::Keep); assert_eq!(file.settle(Some(written), false), Settle::Reload); assert_eq!(file.settle(Some(written), true), Settle::Ask); assert_eq!(file.settle(None, false), Settle::Gone); file.conflict = Some(Conflict::Asking); assert_eq!( file.settle(Some(written), true), Settle::Keep, "the bar is already up" ); assert_eq!(file.settle(None, true), Settle::Gone); let gone = FileBinding { saved: None, stamp: None, ..file_read_at(read) }; assert_eq!(gone.settle(None, true), Settle::Keep, "already said"); assert_eq!(gone.settle(Some(written), true), Settle::Ask, "back again"); } #[test] fn a_relaunch_asks_again_where_the_file_moved_under_unsaved_text() { let left = |saved_hash: Option<&str>, kept_mine| store::StoredQueryTab { saved_hash: saved_hash.map(str::to_string), kept_mine, ..toml::from_str("id = 1").expect("a tab from before these fields") }; let theirs = sql_file::text_hash("SELECT 1", false); let ours = sql_file::text_hash("SELECT 0", false); let conflict = |stored: &store::StoredQueryTab, text: &str| { restored_conflict(stored, Some("SELECT 1"), false, text) }; assert_eq!(conflict(&left(Some(&theirs), false), "mine"), None); assert_eq!( conflict(&left(Some(&ours), false), "mine"), Some(Conflict::Asking) ); assert_eq!( conflict(&left(Some(&theirs), true), "mine"), Some(Conflict::KeptMine) ); assert_eq!( conflict(&left(Some(&ours), false), "SELECT 1"), None, "clean" ); assert_eq!(conflict(&left(None, false), "mine"), None); } #[test] fn save_asks_before_writing_over_a_file_someone_else_wrote() { let (read, written) = (sql_file::Stamp::of_len(8), sql_file::Stamp::of_len(9)); let unknown = || Err(std::io::Error::other("no stat")); let as_saved = || Some(("SELECT 1".to_string(), false)); let mut file = file_read_at(read); assert!(!file.overwrites(&Ok(Some(read)), as_saved)); assert!(file.overwrites(&Ok(Some(written)), as_saved)); assert!( file.overwrites(&Ok(Some(read)), || Some(("SELECT 2".into(), false))), "the stamp kept, the text not" ); assert!(file.overwrites(&Ok(Some(read)), || None), "will not read"); assert!( !file.overwrites(&Ok(None), as_saved), "a deleted file is written again" ); assert!(!file.overwrites(&unknown(), as_saved), "the write says why"); file.conflict = Some(Conflict::KeptMine); assert!( file.overwrites(&Ok(Some(read)), as_saved), "kept, but still theirs on disk" ); assert!(file.overwrites(&unknown(), as_saved)); assert!( !file.overwrites(&Ok(None), as_saved), "kept, then deleted: nothing to overwrite" ); } #[test] fn a_query_name_is_refused_when_taken_but_a_rename_may_keep_its_own() { let saved = ["daily".to_string(), "weekly".to_string()]; assert_eq!(query_name_refusal("monthly", Some("daily"), &saved), None); assert_eq!(query_name_refusal("daily", Some("daily"), &saved), None); assert_eq!( query_name_refusal("weekly", Some("daily"), &saved).as_deref(), Some("A query named weekly already exists.") ); assert!(query_name_refusal("weekly", None, &saved).is_some()); // A name another query has in another case is that query's file. assert_eq!( query_name_refusal("WEEKLY", Some("daily"), &saved).as_deref(), Some("A query named weekly already exists.") ); assert_eq!(query_name_refusal("Daily", Some("daily"), &saved), None); assert!(query_name_refusal(".hidden", None, &saved).is_some()); assert!(query_name_refusal(" ", None, &saved).is_some()); } #[test] fn a_file_is_a_chip_only_while_a_tab_holds_it() { // The strip draws open tabs and nothing else: a query closed is still // on disk and in the sidebar, but takes no room here. let queries = [ (0, None), (1, Some(Path::new("/q/daily.sql"))), (2, None), (3, Some(Path::new("/q/adhoc.sql"))), ]; assert_eq!( default_chips(queries.into_iter(), [4].into_iter()), [ TabKey::Unsaved(0), TabKey::Unsaved(2), TabKey::File("/q/daily.sql".into()), TabKey::File("/q/adhoc.sql".into()), TabKey::Object(4), ] ); } #[test] fn a_new_tab_opens_at_the_right_end_of_the_strip_as_drawn() { let restored = vec![ TabKey::Unsaved(0), TabKey::File("/q/daily.sql".into()), TabKey::Object(0), ]; // Nothing has been dragged, so the restored chips are in no order but // the default one -- which files a new buffer beside the old one. let mut chips = restored.clone(); chips.insert(1, TabKey::Unsaved(1)); let order = placed_last(strip_order(chips.clone(), &[]), TabKey::Unsaved(1)); assert_eq!( strip_order(chips.clone(), &order), [restored.clone(), vec![TabKey::Unsaved(1)]].concat() ); // And the next one, an object, lands after that. chips.push(TabKey::Object(1)); let order = placed_last(strip_order(chips.clone(), &order), TabKey::Object(1)); assert_eq!( strip_order(chips, &order), [restored, vec![TabKey::Unsaved(1), TabKey::Object(1)]].concat() ); } #[test] fn a_tab_moves_one_slot_and_stops_at_either_end() { let order = vec![TabKey::Unsaved(0), TabKey::Object(1), TabKey::Unsaved(2)]; assert_eq!( moved(order.clone(), &TabKey::Object(1), 1), Some(vec![ TabKey::Unsaved(0), TabKey::Unsaved(2), TabKey::Object(1) ]) ); assert_eq!( moved(order.clone(), &TabKey::Object(1), -1), Some(vec![ TabKey::Object(1), TabKey::Unsaved(0), TabKey::Unsaved(2) ]) ); assert_eq!(moved(order.clone(), &TabKey::Unsaved(0), -1), None); assert_eq!(moved(order, &TabKey::Unsaved(2), 1), None); } #[test] fn stepping_through_the_switcher_wraps_at_either_end() { let chips = [Some(0), Some(2), None]; assert_eq!(stepped(&chips, Some(0), 1), Some(Some(2))); assert_eq!(stepped(&chips, None, 1), Some(Some(0))); assert_eq!(stepped(&chips, Some(0), -1), Some(None)); // A selection the chips no longer offer steps from the first. assert_eq!(stepped(&chips, Some(1), 1), Some(Some(2))); } #[test] fn a_dragged_order_survives_chips_it_does_not_mention() { let chips = vec![TabKey::Unsaved(0), TabKey::Unsaved(1), TabKey::Object(0)]; let dragged = [TabKey::Object(0), TabKey::Unsaved(5), TabKey::Unsaved(0)]; // A key whose tab has gone is skipped, and a chip the order does not // name follows it. assert_eq!( strip_order(chips, &dragged), [TabKey::Object(0), TabKey::Unsaved(0), TabKey::Unsaved(1)] ); } #[test] fn a_closed_tab_hands_the_front_to_its_neighbour_in_the_strip() { let strip = [Tab::Query(0), Tab::Object(3), Tab::Query(7)]; assert_eq!(neighbour(&strip, Tab::Object(3)), Some(Tab::Query(0))); assert_eq!(neighbour(&strip, Tab::Query(7)), Some(Tab::Object(3))); // The first has nothing on its left. assert_eq!(neighbour(&strip, Tab::Query(0)), Some(Tab::Object(3))); // The last of all leaves nothing, and a tab not in the strip names no // neighbour. assert_eq!(neighbour(&[Tab::Query(0)], Tab::Query(0)), None); assert_eq!(neighbour(&strip, Tab::Object(9)), None); } #[test] fn only_a_relation_running_with_rows_kept_holds_them_read_only() { let running = QueryState::Running { started: std::time::Instant::now(), cancelling: None, cancel: CancelToken::default(), }; let landed = QueryState::Complete { rows: 1, bytes: 0, elapsed: std::time::Duration::ZERO, rows_affected: None, messages: Vec::new(), }; assert!(refreshing(Tab::Object(3), Some(&running))); assert!(!refreshing(Tab::Object(3), Some(&landed))); // A query tab running over rows is running an `EXPLAIN`, which leaves // them where they are. assert!(!refreshing(Tab::Query(0), Some(&running))); // A routine runs nothing. assert!(!refreshing(Tab::Object(3), None)); } #[test] fn result_pane_expands_as_soon_as_a_query_starts() { assert!(!result_pane_is_expanded(&QueryState::Idle)); assert!(result_pane_is_expanded(&QueryState::Running { started: std::time::Instant::now(), cancelling: None, cancel: CancelToken::default(), })); } /// A cancel that has been sent has not stopped anything yet, so every /// question asked of a running query has to keep its old answer. #[test] fn a_query_being_cancelled_is_still_running() { let cancelling = QueryState::Running { started: std::time::Instant::now(), cancelling: Some(std::time::Instant::now()), cancel: CancelToken::default(), }; assert!(result_pane_is_expanded(&cancelling)); assert!(matches!(cancelling, QueryState::Running { .. })); } #[test] fn the_next_buffer_id_never_goes_backwards_over_a_closed_tab() { let tabs = |ids: &[u64]| { ids.iter() .map(|id| store::StoredQueryTab { id: *id, name: None, path: None, active: false, queued_results: 0, database: None, schema: None, saved_hash: None, kept_mine: false, asking: false, }) .collect::>() }; // Tab 1 closed, so the highest surviving id is 0 -- and deriving the // next id from it would hand out 1 again, over tab 1's snapshot. assert_eq!(next_query_id(2, &tabs(&[0])), 2); // A profile written before the id was persisted has no stored value, // and the derived one is all there is. assert_eq!(next_query_id(0, &tabs(&[0, 1])), 2); // A stored value behind the open tabs -- an older build's file beside // a newer build's tabs -- must not hand out a live id. assert_eq!(next_query_id(1, &tabs(&[0, 4])), 5); assert_eq!(next_query_id(0, &tabs(&[])), 0); } #[test] fn the_discard_prompt_names_what_discards_the_edits() { let close = ( "Close tab", "This tab has cell edits that have not been applied. Closing it discards them." .to_string(), ); assert_eq!(AfterEdits::Close { deleting: None }.discards(), close); let reading = ( "Discard edits", "This tab has cell edits that have not been applied. Reading the rows again \ discards them." .to_string(), ); for then in [ AfterEdits::Requery { filter: String::new(), sort: Vec::new(), limit: Some(2), offset: 2, }, AfterEdits::Refresh, AfterEdits::Filter { before: None }, AfterEdits::ViewSorting(false), AfterEdits::Sort(1), ] { assert_eq!(then.discards(), reading); } let running = ( "Discard edits", "This tab has cell edits that have not been applied. Running the statement \ discards them." .to_string(), ); assert_eq!(AfterEdits::Run.discards(), running); assert_eq!( AfterEdits::Rerun { index: 0, sql: "select 1".into() } .discards(), running ); } #[test] fn the_prompt_over_a_refused_row_says_whose_edits_go_and_what_discards_them() { let refused = |then: AfterEdits| then.discards_refused_row().1; assert_eq!( refused(AfterEdits::Close { deleting: None }), "The server refused a row of this tab, so its edits have not been applied. \ Closing it discards that row's edits." ); assert!(refused(AfterEdits::Refresh).contains("Reading the rows again discards")); assert!( refused(AfterEdits::Activate(Tab::Query(0))) .contains("Switching to another tab discards") ); assert!( refused(AfterEdits::EditMode(EditMode::Draft)) .contains("Switching the edit mode discards") ); } }