Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion core/crates/mcp/src/query_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ pub async fn execute_query(
let HeldSession { session, database } = context
.held_session(&connection, args.database.as_deref(), &cancel)
.await?;
// The history says where the statement went; None for a file, or a login that named no database. A name the
// client gave that held_session took as the connection's own is still the one it ran in.
let ran_in = database
.clone()
.or_else(|| session.database().map(str::to_owned))
.or_else(|| args.database.clone().filter(|name| !name.is_empty()));
let dialect = session
.current_dialect()
.ok_or_else(|| ToolError::NotConnected(format!("“{}” has no connection right now", connection.name)))?;
Expand Down Expand Up @@ -108,7 +114,10 @@ pub async fn execute_query(
};
context
.host
.record(history_entry(&connection, &text, executed_at, elapsed, &ran), dialect)
.record(
history_entry(&connection, &text, executed_at, elapsed, &ran, ran_in),
dialect,
)
.await;
let (collected, notes) = ran?;
collected.to_json(elapsed, &notes)
Expand Down Expand Up @@ -431,6 +440,7 @@ fn history_entry(
executed_at: SystemTime,
elapsed: Duration,
ran: &Ran,
database: Option<String>,
) -> NewEntry {
let (rows_affected, outcome) = match ran {
Ok((collected, _)) => (
Expand All @@ -451,6 +461,7 @@ fn history_entry(
rows_affected,
outcome,
details: tablepro_storage::query_history::RunDetails {
database,
source: Some(tablepro_storage::query_history::RunSource::Mcp),
..Default::default()
},
Expand Down
3 changes: 3 additions & 0 deletions core/crates/mcp/tests/mcp_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,9 @@ async fn a_database_the_window_holds_answers_from_its_own_session() {
"{counted}"
);
assert!(own_failed, "the connection's own database has no invoices");
let recorded = harness.host.recorded.lock().expect("recorded");
let databases: Vec<Option<&str>> = recorded.iter().map(|entry| entry.details.database.as_deref()).collect();
assert_eq!(databases, [Some("archive")], "the history names where the query went");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
Expand Down
1 change: 1 addition & 0 deletions linux/changelog.d/4775.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Query history recorded on this computer left out the database each query ran in.
9 changes: 6 additions & 3 deletions linux/crates/app/src/ui/editor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,8 @@ impl SqlEditor {
// can move to another engine before it ends.
let dialect = session.current_dialect();
let ran_on = session.clone();
// Where the run begins, before a typed USE moves the tab.
let ran_in = imp.slot.database().or_else(|| session.database().map(str::to_owned));
let started_at = SystemTime::now();
let cancel = CancellationToken::new();
let (events, mut received) = tokio::sync::mpsc::channel(8);
Expand Down Expand Up @@ -565,7 +567,7 @@ impl SqlEditor {
editor.apply_event(event);
if finished {
let dialect = dialect.or_else(|| ran_on.current_dialect());
editor.finish_run(query, &metadata, started_at, dialect);
editor.finish_run(query, &metadata, started_at, dialect, ran_in);
return;
}
}
Expand All @@ -574,7 +576,7 @@ impl SqlEditor {
if let Some(editor) = weak.upgrade() {
editor.apply_event(RunEvent::Finished);
let dialect = dialect.or_else(|| ran_on.current_dialect());
editor.finish_run(query, &metadata, started_at, dialect);
editor.finish_run(query, &metadata, started_at, dialect, ran_in);
}
});
imp.running.replace(Some(RunningScript { cancel, drain }));
Expand Down Expand Up @@ -689,6 +691,7 @@ impl SqlEditor {
metadata: &tablepro_session::ConnectionMetadata,
started_at: SystemTime,
dialect: Option<Arc<dyn SqlDialect>>,
ran_in: Option<String>,
) {
let imp = self.imp();
drop(imp.running.take());
Expand All @@ -704,7 +707,7 @@ impl SqlEditor {
log.summary(),
RunTransaction::of(log),
log.first_to_show(),
run_history::history_entry(query, metadata, started_at, log),
run_history::history_entry(query, metadata, started_at, log, ran_in),
log.outcome(),
)
};
Expand Down
40 changes: 34 additions & 6 deletions linux/crates/app/src/ui/editor/run_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@ use tablepro_storage::query_history::{NewEntry, Outcome, RunDetails, RunSource};
use super::run_log::RunLog;

/// The history line for one press of Run: the SQL that was sent, which
/// is the selection when there was one, and how the run ended.
pub fn history_entry(query: String, metadata: &ConnectionMetadata, executed_at: SystemTime, log: &RunLog) -> NewEntry {
/// is the selection when there was one, the database it went to, and
/// how the run ended.
pub fn history_entry(
query: String,
metadata: &ConnectionMetadata,
executed_at: SystemTime,
log: &RunLog,
database: Option<String>,
) -> NewEntry {
let outcome = if let Some(message) = log.first_failure() {
Outcome::Error(message.to_owned())
} else if log.timed_out() {
Expand All @@ -34,6 +41,7 @@ pub fn history_entry(query: String, metadata: &ConnectionMetadata, executed_at:
rows_affected: log.rows_for_history(),
outcome,
details: RunDetails {
database,
source: Some(RunSource::Editor),
..RunDetails::default()
},
Expand Down Expand Up @@ -74,14 +82,34 @@ mod tests {
let log = log_of(vec![EntryKind::Command { rows_affected: Some(3) }], Verdict::Completed);
let metadata = metadata();

let entry = history_entry("SELECT 2".to_owned(), &metadata, SystemTime::now(), &log);
let entry = history_entry("SELECT 2".to_owned(), &metadata, SystemTime::now(), &log, None);

assert_eq!(entry.query, "SELECT 2");
assert_eq!(entry.connection_id, metadata.id);
assert_eq!(entry.rows_affected, Some(3));
assert_eq!(entry.outcome, Outcome::Success);
}

// A synced run shows another device where it went. A file, or a login that named no database, has none.
#[test]
fn history_records_the_database_the_run_went_to() {
let log = log_of(vec![EntryKind::Command { rows_affected: Some(1) }], Verdict::Completed);
let metadata = metadata();

let moved = history_entry(
"SELECT 1".to_owned(),
&metadata,
SystemTime::now(),
&log,
Some("analytics".to_owned()),
);
let file = history_entry("SELECT 1".to_owned(), &metadata, SystemTime::now(), &log, None);

assert_eq!(moved.details.database.as_deref(), Some("analytics"));
assert_eq!(moved.details.source, Some(RunSource::Editor));
assert_eq!(file.details.database, None);
}

#[test]
fn a_failure_or_a_stop_is_what_history_remembers() {
let failed = log_of(
Expand All @@ -95,17 +123,17 @@ mod tests {

let metadata = metadata();
assert_eq!(
history_entry(String::new(), &metadata, SystemTime::now(), &failed).outcome,
history_entry(String::new(), &metadata, SystemTime::now(), &failed, None).outcome,
Outcome::Error("boom".to_owned())
);
assert_eq!(
history_entry(String::new(), &metadata, SystemTime::now(), &stopped).outcome,
history_entry(String::new(), &metadata, SystemTime::now(), &stopped, None).outcome,
Outcome::Cancelled
);
let mut never_sent = RunLog::new(vec![tablepro_core::UserSql::new("SELECT 2")], Vec::new());
never_sent.apply(RunEvent::Finished);
assert_eq!(
history_entry(String::new(), &metadata, SystemTime::now(), &never_sent).outcome,
history_entry(String::new(), &metadata, SystemTime::now(), &never_sent, None).outcome,
Outcome::Cancelled,
"a run stopped before it began is remembered as a success"
);
Expand Down
61 changes: 59 additions & 2 deletions linux/crates/app/src/ui/editor/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,51 @@ fn export_shown_result_offers_nothing_without_rows() {
assert_eq!(offers.count(), 0);
}

// A run records where it went: the session's own database until the tab is moved, then the one it was moved to.
#[gtk4::test]
fn a_run_records_the_connections_database_and_after_a_pick_the_one_picked() {
let root = tempfile::tempdir().expect("tempdir");
let paths = tablepro_storage::StoragePaths::under(root.path(), "tablepro-test", "app.tablepro.TablePro.Devel");
let database = |name: &str, is_default: bool| tablepro_core::meta::SchemaInfo {
name: name.to_owned(),
is_default,
is_system: false,
};
let harness = scoped_editor_keeping(
mysql_dialect(),
&["shop"],
answering(),
|script, _| {
script.list_databases.always(FakeReply::ok(vec![
database("analytics", false),
database("shop", true),
]));
},
|tasks| {
let preferences = HistoryPreferences {
retention_days: tokio::sync::watch::channel(30).1,
save: tokio::sync::watch::channel(true).1,
};
Some(HistoryService::start(paths, preferences, tasks))
},
);
let button = harness.editor.imp().scope_button.get();
wait_until(WAIT, || button.is_visible()).expect("the database menu");

run_and_wait(&harness);
wait_until(WAIT, || recorded_entries(&harness).len() == 1).expect("the first run recorded");
pick_database(&harness, "analytics");
run_and_wait(&harness);
wait_until(WAIT, || recorded_entries(&harness).len() == 2).expect("both runs recorded");

let mut databases: Vec<Option<String>> = recorded_entries(&harness)
.into_iter()
.map(|entry| entry.details.database)
.collect();
databases.sort();
assert_eq!(databases, [Some("analytics".to_owned()), Some("shop".to_owned())]);
}

#[gtk4::test]
fn history_records_none_for_capped_result() {
let root = tempfile::tempdir().expect("tempdir");
Expand Down Expand Up @@ -2747,6 +2792,17 @@ fn scoped_editor_with(
schemas: &[&str],
runs: Replies<FakeRun>,
setup: impl FnOnce(&mut ConnectionScript, &mut tablepro_session::connect::ConnectRequest),
) -> Harness {
scoped_editor_keeping(dialect, schemas, runs, setup, |_| None)
}

// As `scoped_editor_with`, on a session in "shop", with the history `history` gives.
fn scoped_editor_keeping(
dialect: Arc<dyn tablepro_core::dialect::SqlDialect>,
schemas: &[&str],
runs: Replies<FakeRun>,
setup: impl FnOnce(&mut ConnectionScript, &mut tablepro_session::connect::ConnectRequest),
history: impl FnOnce(&Tasks) -> Option<HistoryService>,
) -> Harness {
crate::register_test_resources();
let runtime = crate::test_support::test_runtime();
Expand Down Expand Up @@ -2786,10 +2842,11 @@ fn scoped_editor_with(
let active = ActiveSession::new();
active.replace(session);
let settings = MemorySettings::new();
let history = history(&runtime.tasks());
let editor = SqlEditor::new(SqlEditorInit {
initial_query: Some("SELECT 1".to_owned()),
settings: settings.get().clone(),
history: None,
history: history.clone(),
tasks: runtime.tasks(),
session: active.clone(),
hold: Rc::new(tablepro_session::runtime::CountingHold::new()),
Expand All @@ -2799,7 +2856,7 @@ fn scoped_editor_with(
Harness {
editor,
fake,
history: None,
history,
active,
settings,
runtime,
Expand Down
3 changes: 2 additions & 1 deletion linux/crates/app/src/ui/workspace/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,8 @@ async fn run_import(run: ImportRun) -> Result<usize, ImportEnd> {
// An import changes the database, so it belongs in the same
// history as a statement run from the editor.
let touched = report.total_rows().and_then(|rows| i64::try_from(rows).ok());
RanStatements::starting(history, connection, Some(dialect), sql)
let database = session.database().map(str::to_owned);
RanStatements::starting(history, connection, database, Some(dialect), sql)
.finished(touched, tablepro_storage::query_history::Outcome::Success)
.await;
Ok(rows)
Expand Down
70 changes: 68 additions & 2 deletions linux/crates/app/src/workspace/ran_statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::time::SystemTime;

use tablepro_core::dialect::SqlDialect;
use tablepro_session::ConnectionMetadata;
use tablepro_storage::query_history::{NewEntry, Outcome};
use tablepro_storage::query_history::{NewEntry, Outcome, RunDetails};

use crate::services::history_service::HistoryService;

Expand All @@ -19,6 +19,8 @@ use crate::services::history_service::HistoryService;
pub(crate) struct RanStatements {
history: Option<HistoryService>,
connection: Option<ConnectionMetadata>,
// The database of the session the batch runs on; None for a file, or a login that named none.
database: Option<String>,
dialect: Option<Arc<dyn SqlDialect>>,
sql: String,
started_at: SystemTime,
Expand All @@ -30,12 +32,14 @@ impl RanStatements {
pub(crate) fn starting(
history: Option<HistoryService>,
connection: Option<ConnectionMetadata>,
database: Option<String>,
dialect: Option<Arc<dyn SqlDialect>>,
statements: impl IntoIterator<Item = String>,
) -> Self {
Self {
history,
connection,
database,
dialect,
sql: join(statements),
started_at: SystemTime::now(),
Expand Down Expand Up @@ -66,7 +70,10 @@ impl RanStatements {
.ok()
.and_then(|elapsed| i64::try_from(elapsed.as_micros()).ok()),
rows_affected,
details: Default::default(),
details: RunDetails {
database: self.database,
..RunDetails::default()
},
outcome,
};
history.record(entry, self.dialect).await;
Expand Down Expand Up @@ -103,6 +110,64 @@ mod tests {
assert_eq!(join(["SELECT 1;".to_owned()]), "SELECT 1;");
}

#[tokio::test]
async fn a_save_records_the_database_it_ran_in() {
use tokio::sync::watch;

use crate::services::history_preferences::HistoryPreferences;

let root = tempfile::tempdir().expect("tempdir");
let paths = tablepro_storage::StoragePaths::under(root.path(), "tablepro-test", "app.tablepro.TablePro.Devel");
let preferences = HistoryPreferences {
retention_days: watch::channel(30).1,
save: watch::channel(true).1,
};
let history = HistoryService::start(paths, preferences, &crate::test_support::paused_tasks());
let connection = ConnectionMetadata {
id: uuid::Uuid::new_v4(),
name: "local".to_owned(),
driver_id: "postgres".to_owned(),
};
let dialect: Arc<dyn SqlDialect> = Arc::new(tablepro_test_support::FakeDialect);
let save_in = |database: Option<&str>, sql: &str| {
RanStatements::starting(
Some(history.clone()),
Some(connection.clone()),
database.map(str::to_owned),
Some(dialect.clone()),
[sql.to_owned()],
)
};

save_in(Some("analytics"), "UPDATE t SET a = 1")
.finished(Some(1), Outcome::Success)
.await;
save_in(None, "UPDATE t SET a = 2")
.finished(Some(1), Outcome::Success)
.await;

let store = history.ready_store().await.expect("the store");
let mut ran_in: Vec<(String, Option<String>)> = store
.search_page(
&tablepro_storage::query_history::HistoryQuery::default(),
tablepro_storage::query_history::HistoryPageRequest::first(100),
)
.await
.expect("search")
.entries
.into_iter()
.map(|entry| (entry.query, entry.details.database))
.collect();
ran_in.sort();
assert_eq!(
ran_in,
[
("UPDATE t SET a = 1;".to_owned(), Some("analytics".to_owned())),
("UPDATE t SET a = 2;".to_owned(), None),
]
);
}

#[tokio::test]
async fn a_save_goes_through_the_history_gate() {
use tokio::sync::watch;
Expand All @@ -127,6 +192,7 @@ mod tests {
RanStatements::starting(
Some(history.clone()),
Some(connection.clone()),
None,
Some(dialect.clone()),
[sql.to_owned()],
)
Expand Down
Loading
Loading