//! What a SQL console in auto-commit mode keeps between its statements. use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, QueryResult}; use std::time::Duration; const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql"); const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql"); const COUNT: &str = "SELECT count(*) FROM t"; async fn setup() -> (tempfile::TempDir, DbManager) { let tmp = tempfile::tempdir().unwrap(); let root = tmp.path().to_path_buf(); std::fs::File::create(root.join("app.db")).unwrap(); let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json"))); let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh); db.save_sources(vec![DataSource { id: "s1".into(), name: "app".into(), driver: DbDriver::Sqlite, file: Some("app.db".into()), ..Default::default() }]) .await .unwrap(); for sql in ["CREATE TABLE t (id INTEGER PRIMARY KEY)", "INSERT INTO t VALUES (1), (2), (3)"] { db.execute("s1", sql, 0, &CancellationToken::new()).await.unwrap(); } (tmp, db) } async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult { db.execute_in_console("s1", sql, 0, 10, &CancellationToken::new(), None, Some(console)).await } async fn run_all(db: &DbManager, console: ConsoleId<'_>, script: &[&str]) -> IdeResult<()> { for sql in script { run(db, console, sql).await.map_err(|e| IdeError::invalid(format!("{sql}: {}", e.message)))?; } Ok(()) } async fn count(db: &DbManager, console: Option>) -> IdeResult { let token = CancellationToken::new(); let result = db.execute_in_console("s1", COUNT, 0, 10, &token, None, console).await?; Ok(result.rows[0][0].clone().unwrap()) } async fn insert_in_table_editor(db: &DbManager, id: &str) -> IdeResult { let values = vec![CellValue { column: "id".into(), value: Some(id.into()) }]; db.apply_edits("s1", "main", "t", &[DbRowEdit::Insert { values }]).await } #[tokio::test] async fn rollback_undoes_the_statements_since_begin() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?; assert_eq!(count(&db, Some(A)).await?, "0"); assert_eq!(count(&db, Some(B)).await?, "3", "another console reads committed rows"); assert_eq!(count(&db, None).await?, "3", "so does a statement outside any console"); run(&db, A, "ROLLBACK").await?; assert_eq!(count(&db, Some(A)).await?, "3"); run_all(&db, A, &["-- comment first\nBEGIN IMMEDIATE", "DELETE FROM t WHERE id = 1", "COMMIT"]).await?; assert_eq!(count(&db, Some(B)).await?, "2"); Ok(()) } #[tokio::test] async fn temporary_tables_and_settings_belong_to_their_console() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "PRAGMA cache_size = 123"]).await?; run_all(&db, A, &["INSERT INTO work SELECT id FROM t"; 3]).await?; assert_eq!(run(&db, A, "SELECT count(*) FROM work").await?.rows, [[Some("9".into())]]); assert_eq!(run(&db, A, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]); assert!(run(&db, B, "SELECT count(*) FROM work").await.is_err()); assert_ne!(run(&db, B, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]); let outside = db.execute("s1", "SELECT count(*) FROM work", 10, &CancellationToken::new()).await; assert!(outside.is_err()); // A later page of the console's own result reads the same session. let page = db .execute_in_console("s1", "SELECT id FROM work ORDER BY id", 3, 3, &CancellationToken::new(), None, Some(A)) .await?; assert_eq!(page.rows, vec![vec![Some("2".to_owned())]; 3]); Ok(()) } #[tokio::test] async fn closing_a_console_rolls_back_and_frees_the_file() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?; db.release_target_console(A, Some("other")).await?; assert_eq!(count(&db, Some(A)).await?, "0", "another target's release leaves this session alone"); db.release_console(A).await?; assert_eq!(count(&db, None).await?, "3"); assert_eq!(insert_in_table_editor(&db, "4").await?, 1); assert_eq!(count(&db, Some(A)).await?, "4"); Ok(()) } #[tokio::test] async fn disconnecting_rolls_back_an_open_transaction() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?; tokio::time::timeout(Duration::from_secs(5), db.disconnect("s1")).await.expect("the pool closes"); assert_eq!(count(&db, Some(A)).await?, "3"); Ok(()) } #[tokio::test] async fn manual_mode_ends_the_console_sessions_of_its_data_source() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?; db.set_manual_commit("s1", true).await?; assert_eq!(count(&db, Some(A)).await?, "3"); run(&db, B, "INSERT INTO t VALUES (4)").await?; db.finish_transaction("s1", true).await?; db.set_manual_commit("s1", false).await?; assert_eq!(count(&db, Some(A)).await?, "4"); Ok(()) } #[tokio::test] async fn a_session_without_a_transaction_leaves_the_table_editor_free() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "BEGIN", "INSERT INTO t VALUES (4)", "COMMIT"]).await?; let token = CancellationToken::new(); // The rows after the first stay unread on the session's connection. assert!(db.execute_in_console("s1", "SELECT id FROM t", 0, 1, &token, None, Some(A)).await?.has_more); let saved = tokio::time::timeout(Duration::from_secs(2), insert_in_table_editor(&db, "5")); assert_eq!(saved.await.expect("the table editor does not wait for the console")?, 1); assert_eq!(count(&db, Some(A)).await?, "5"); Ok(()) } #[tokio::test] async fn cancelling_rolls_back_and_the_next_statement_says_so() -> IdeResult<()> { let (_tmp, db) = setup().await; run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?; let slow = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000000) SELECT sum(i) FROM n"; let token = CancellationToken::new(); let (stopped, ()) = tokio::join!(db.execute_in_console("s1", slow, 0, 10, &token, None, Some(A)), async { tokio::time::sleep(Duration::from_millis(50)).await; token.cancel(); }); assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled); let refused = run(&db, A, "DELETE FROM t WHERE id = 1").await.unwrap_err(); assert_eq!(refused.kind, ErrorKind::OutOfSync, "it would commit outside the transaction: {}", refused.message); assert_eq!(count(&db, Some(A)).await?, "3"); run_all(&db, A, &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?; assert_eq!(count(&db, None).await?, "3"); Ok(()) } #[tokio::test] async fn sessions_are_bounded_and_leave_ordinary_statements_their_connections() -> IdeResult<()> { let (_tmp, db) = setup().await; let paths: Vec<_> = (0..5).map(|n| format!("{n}.sql")).collect(); let consoles: Vec<_> = paths.iter().map(|path| ConsoleId::new("main", path)).collect(); for console in &consoles[..4] { run(&db, *console, "PRAGMA cache_size = 99").await?; } let refused = run(&db, consoles[4], "BEGIN").await.unwrap_err(); assert_eq!(refused.kind, ErrorKind::Unavailable, "{}", refused.message); assert_eq!(count(&db, Some(consoles[4])).await?, "3", "a plain query needs no session"); run(&db, consoles[4], "INSERT INTO t VALUES (4)").await?; db.completion("s1").await?; assert_eq!(insert_in_table_editor(&db, "5").await?, 1); db.release_console(consoles[0]).await?; run_all(&db, consoles[4], &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?; assert_eq!(count(&db, None).await?, "5"); Ok(()) } #[tokio::test] async fn a_transaction_opened_outside_a_console_never_reaches_another_statement() -> IdeResult<()> { let (_tmp, db) = setup().await; let token = CancellationToken::new(); db.execute("s1", "BEGIN", 0, &token).await?; db.execute("s1", "BEGIN; DELETE FROM t", 0, &token).await?; assert_eq!(count(&db, None).await?, "3"); assert_eq!(insert_in_table_editor(&db, "4").await?, 1); db.execute("s1", "BEGIN; DELETE FROM t WHERE id = 1; COMMIT", 0, &token).await?; assert_eq!(count(&db, None).await?, "3"); Ok(()) }