From 6f9413f5d3babee911ee50fc875d6f5d4e6c144e Mon Sep 17 00:00:00 2001 From: Bare7a Date: Tue, 1 Dec 2026 16:14:24 +0200 Subject: [PATCH 1/2] feat(BAR-57): Adds JSON import and a step-by-step import dialog --- Cargo.toml | 2 +- README.md | 6 +- crates/barsql-app/src/boxed.rs | 10 +- crates/barsql-app/src/import.rs | 203 ++- crates/barsql-app/src/lib.rs | 4 +- crates/barsql-app/tests/app_sqlite.rs | 225 +++- crates/barsql-app/tests/e2e/harness.rs | 31 +- crates/barsql-app/tests/e2e/roundtrip.rs | 97 +- crates/barsql-io/src/csv_import.rs | 12 + crates/barsql-io/src/detect.rs | 97 ++ crates/barsql-io/src/json_import.rs | 802 +++++++++++ crates/barsql-io/src/lib.rs | 4 + crates/barsql-sql/src/dialect.rs | 6 + crates/barsql-sql/src/dml.rs | 8 + crates/barsql-ui/locales/bg.json | 41 + crates/barsql-ui/locales/de.json | 41 + crates/barsql-ui/locales/en.json | 41 + crates/barsql-ui/locales/es.json | 41 + crates/barsql-ui/src/file_dialogs.rs | 13 +- crates/barsql-ui/src/import_dialog.rs | 1198 ++++++----------- .../src/import_dialog/columns_step.rs | 199 +++ .../barsql-ui/src/import_dialog/file_step.rs | 213 +++ .../src/import_dialog/preview_step.rs | 201 +++ .../barsql-ui/src/import_dialog/run_step.rs | 215 +++ crates/barsql-ui/src/import_dialog/tests.rs | 416 ++++++ crates/barsql-ui/src/scenarios/import.rs | 87 +- crates/barsql-ui/src/schema_tree.rs | 12 +- crates/barsql-ui/src/screenshots.rs | 5 + crates/barsql-ui/src/screenshots/video.rs | 9 +- docs/index.html | 13 +- guide/README.md | 2 +- guide/import-export.md | 24 +- 32 files changed, 3388 insertions(+), 890 deletions(-) create mode 100644 crates/barsql-io/src/detect.rs create mode 100644 crates/barsql-io/src/json_import.rs create mode 100644 crates/barsql-ui/src/import_dialog/columns_step.rs create mode 100644 crates/barsql-ui/src/import_dialog/file_step.rs create mode 100644 crates/barsql-ui/src/import_dialog/preview_step.rs create mode 100644 crates/barsql-ui/src/import_dialog/run_step.rs create mode 100644 crates/barsql-ui/src/import_dialog/tests.rs diff --git a/Cargo.toml b/Cargo.toml index 0b6fcc6..ff5e138 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std" rustls-native-certs = "0.8" ryu-js = "1" serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] } +serde_json = { version = "1", features = ["float_roundtrip", "preserve_order", "raw_value"] } sha2 = "0.11" sqlformat = "0.5" tar = "0.4" diff --git a/README.md b/README.md index f62d228..812b6be 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Under the hood: - Rename, truncate, drop and back up tables straight from the schema tree - Compare two schemas and get the script that syncs them - Copy any object's DDL in one click -- Import a CSV or run a `.sql` script +- Import a CSV or JSON file, or run a `.sql` script - Save and reuse queries - Export anything in one click - Let AI assistants such as Claude read your databases over MCP - and change them only where you allow it @@ -112,7 +112,7 @@ Under the hood: Plan viewer
Plan viewer - CSV & SQL import
CSV & SQL import + CSV, JSON & SQL import
CSV, JSON & SQL import Structure editor
Structure editor @@ -151,7 +151,7 @@ Every feature in detail, one area per page: | [🧠 SQL Editor](guide/editor.md) | Autocomplete, multiple cursors, scripts, transactions, the query plan viewer, saved queries and history | | [🗃️ Schema Explorer](guide/schema.md) | The schema tree, ER diagrams, schema compare, Copy DDL, schema changes, the structure editor, table backups | | [📊 Results Grid](guide/results.md) | Sorting, selection stats, quick charts, the cell and JSON viewers, editing data | -| [📥 Import & Export](guide/import-export.md) | CSV and SQL import, export formats | +| [📥 Import & Export](guide/import-export.md) | CSV, JSON and SQL import, export formats | | [🤖 AI Assistants (MCP)](guide/ai-assistants.md) | Letting AI apps read your databases, and change them only where you allow it | | [🌍 The App](guide/app.md) | Themes, languages, palettes, the status bar, keyboard shortcuts, the data folder, auto updates | | [🎨 Themes](guide/themes.md) | The 21 built-in themes, Select theme…, and making your own | diff --git a/crates/barsql-app/src/boxed.rs b/crates/barsql-app/src/boxed.rs index 2ab1e81..f602f3f 100644 --- a/crates/barsql-app/src/boxed.rs +++ b/crates/barsql-app/src/boxed.rs @@ -15,8 +15,8 @@ use futures_util::future::BoxFuture; use crate::events::{ImportHandle, RunHandle}; use crate::{ - ApplyError, BackupOutcome, BackupRequest, BarApp, BufferedResult, CsvImportRequest, ResultEdits, ResultTable, - SqlImportRequest, + ApplyError, BackupOutcome, BackupRequest, BarApp, BufferedResult, ResultEdits, ResultTable, SqlImportRequest, + TableImportRequest, }; impl BarApp { @@ -228,13 +228,13 @@ impl BarApp { Box::pin(self.apply_result_edits_inner(connection_id, tab_id, edits)) } - pub fn import_csv<'a>( + pub fn import_table<'a>( &'a self, connection_id: &'a str, import_id: &'a str, - req: CsvImportRequest, + req: TableImportRequest, ) -> BoxFuture<'a, Result> { - Box::pin(self.import_csv_inner(connection_id, import_id, req)) + Box::pin(self.import_table_inner(connection_id, import_id, req)) } pub fn import_sql<'a>( diff --git a/crates/barsql-app/src/import.rs b/crates/barsql-app/src/import.rs index 4885176..1b64007 100644 --- a/crates/barsql-app/src/import.rs +++ b/crates/barsql-app/src/import.rs @@ -7,9 +7,12 @@ use std::time::{Duration, Instant}; use barsql_core::{DriverType, QueryError, SqlDialect, Value}; use barsql_db::{Cancel, ScriptEvent, Session}; use barsql_io::csv_import::open_error; -use barsql_io::{CsvField, CsvOptions, ImportPreview, count_rows, new_reader, preview_file}; +use barsql_io::{ + CsvField, CsvOptions, CsvReader, ImportPreview, JsonCell, JsonError, JsonReader, count_json_rows, count_rows, + json_cell, new_reader, preview_file, preview_json, +}; use barsql_sql::dml::{ - IMPORT_BOOL, IMPORT_DATE, IMPORT_TEXT, IMPORT_TIMESTAMP, MYSQL_BITS, accepts_empty_string, bit_digits, + IMPORT_BOOL, IMPORT_DATE, IMPORT_JSON, IMPORT_TEXT, IMPORT_TIMESTAMP, MYSQL_BITS, accepts_empty_string, bit_digits, build_batch_insert_with, build_import_create_table, build_truncate, is_bit_column, }; use barsql_sql::{Dialect, READ_ONLY_ERROR, split_statement_texts}; @@ -26,13 +29,13 @@ const PROGRESS_INTERVAL: Duration = Duration::from_millis(100); #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CsvImportRequest { +pub struct TableImportRequest { pub path: String, pub schema: String, pub table: String, pub create_table: bool, pub truncate: bool, - pub options: CsvOptions, + pub format: TableFormat, // Target column per file column, empty to skip it. pub mapping: Vec, // Parallel to `mapping`. Used for CREATE TABLE and boolean normalization. @@ -41,6 +44,20 @@ pub struct CsvImportRequest { pub stop_on_error: bool, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TableFormat { + Csv(CsvOptions), + // The key behind each file column, in the preview's order. + Json { keys: Vec }, +} + +impl Default for TableFormat { + fn default() -> Self { + Self::Csv(CsvOptions::default()) + } +} + #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SqlImportRequest { @@ -59,6 +76,9 @@ pub struct ImportResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub errors: Vec, pub cancelled: bool, + // JSON keys the preview never saw, which only a sampled file can have. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub ignored_keys: Vec, } impl ImportResult { @@ -141,11 +161,19 @@ impl BarApp { // Returns once the run is registered, then progress and the outcome arrive as events. // Only its own id cancels it, not other work on the connection. - pub(crate) async fn import_csv_inner( + pub fn preview_json_file(&self, connection_id: &str, path: &str) -> Result { + if path.is_empty() { + return Err(QueryError::message("no file selected")); + } + let cfg = self.config(connection_id)?; + preview_json(Path::new(path), &cfg.driver).map_err(QueryError::message) + } + + pub(crate) async fn import_table_inner( &self, connection_id: &str, import_id: &str, - req: CsvImportRequest, + req: TableImportRequest, ) -> Result { if import_id.is_empty() { return Err(QueryError::message("import id is required")); @@ -160,7 +188,7 @@ impl BarApp { let (targets, sources) = resolve_mapping(&req.mapping)?; let connection = connection_id.to_string(); Ok(self.run_import(import_id, connection_id, move |app, mut emitter, cancel| async move { - app.run_csv_import(&connection, &req, &targets, &sources, &mut emitter, &cancel).await + app.run_table_import(&connection, &req, &targets, &sources, &mut emitter, &cancel).await })) } @@ -214,10 +242,10 @@ impl BarApp { ImportHandle { events: rx } } - async fn run_csv_import( + async fn run_table_import( &self, connection_id: &str, - req: &CsvImportRequest, + req: &TableImportRequest, targets: &[String], sources: &[usize], emitter: &mut Emitter, @@ -227,8 +255,18 @@ impl BarApp { let mut file = File::open(path).map_err(|e| QueryError::message(open_error(path, &e)))?; let total_bytes = file.metadata().map(|m| m.len()).unwrap_or(0) as i64; // Before reading, so bytes_read covers only the import's own pass. - emitter.total_rows = count_rows(&mut file, &req.options, total_bytes as u64) as i64; - let mut reader = new_reader(file, &req.options).map_err(QueryError::message)?; + emitter.total_rows = match &req.format { + TableFormat::Csv(options) => count_rows(&mut file, options, total_bytes as u64), + TableFormat::Json { .. } => count_json_rows(&mut file, total_bytes as u64), + } as i64; + let mut rows = match &req.format { + TableFormat::Csv(options) => Rows::Csv(new_reader(file, options).map_err(QueryError::message)?), + TableFormat::Json { keys } => { + let reader = JsonReader::new(file).map_err(QueryError::message)?; + let columns = keys.iter().enumerate().map(|(i, key)| (key.clone(), i)).collect(); + Rows::Json { reader, columns, width: keys.len() } + } + }; let engine = self.engine(connection_id).await?; let driver = engine.driver(); @@ -243,7 +281,9 @@ impl BarApp { } // Read the header before any DDL, so an unreadable file fails before a table exists. - if req.options.has_header { + if let (Rows::Csv(reader), TableFormat::Csv(options)) = (&mut rows, &req.format) + && options.has_header + { reader.read().map_err(|e| QueryError::message(e.to_string()))?; } if req.create_table { @@ -276,10 +316,16 @@ impl BarApp { result.cancelled = true; break; } - let record = match reader.read() { - Ok(Some(record)) => conv.build_values(record, sources), - Ok(None) => break, - Err(err) => Err(err.to_string()), + let record = match rows.next(&conv, sources, &mut result.ignored_keys) { + Next::Row(record) => record, + Next::End => break, + // The rows before it still load. + Next::Broken(err) if !req.stop_on_error => { + result.skipped += 1; + result.report([err]); + break; + } + Next::Broken(err) => return Err(QueryError::message(err)), }; let record = match record { Ok(record) => record, @@ -310,7 +356,7 @@ impl BarApp { .await?; } // Throttled, so a file smaller than one batch still reports progress. - emitter.progress(processed, result.inserted, result.skipped, reader.bytes_read() as i64, total_bytes); + emitter.progress(processed, result.inserted, result.skipped, rows.bytes_read() as i64, total_bytes); } if !result.cancelled { flush( @@ -327,7 +373,7 @@ impl BarApp { ) .await?; } - emitter.progress_now(processed, result.inserted, result.skipped, reader.bytes_read() as i64, total_bytes); + emitter.progress_now(processed, result.inserted, result.skipped, rows.bytes_read() as i64, total_bytes); Ok(result) } @@ -336,14 +382,18 @@ impl BarApp { &self, engine: &barsql_db::Engine, schema: &str, - req: &CsvImportRequest, + req: &TableImportRequest, targets: &[String], sources: &[usize], ) -> ValueConverter { let driver = engine.driver(); + let (null_literal, trim) = match &req.format { + TableFormat::Csv(options) => (options.null_literal.clone(), options.trim_space), + TableFormat::Json { .. } => (String::new(), false), + }; let mut conv = ValueConverter { - null_literal: req.options.null_literal.clone(), - trim: req.options.trim_space, + null_literal, + trim, // Postgres booleans need real bools. MySQL, SQLite and SQL Server take 1/0. bool_as_bool: match driver.dialect() { Some(SqlDialect::Postgres | SqlDialect::ClickHouse) => true, @@ -372,6 +422,9 @@ impl BarApp { if t == IMPORT_TEXT { conv.text_cols.insert(i); } + if t == IMPORT_JSON { + conv.json_cols.insert(i); + } if mysql && (t == IMPORT_DATE || t == IMPORT_TIMESTAMP) { conv.date_cols.insert(i); } @@ -393,6 +446,9 @@ impl BarApp { if data_type.is_none_or(|t| accepts_empty_string(t)) { conv.text_cols.insert(i); } + if data_type.is_some_and(|t| is_json_type(t)) { + conv.json_cols.insert(i); + } let upper = data_type.map(|t| barsql_sql::to_upper(t.trim())).unwrap_or_default(); if upper.contains("BOOL") { conv.bool_cols.insert(i); @@ -490,6 +546,56 @@ async fn affected_rows(session: &mut Session, stmt: &str, cancel: &Cancel) -> Re result.map(|_| affected) } +enum Rows { + Csv(CsvReader), + // `columns` finds a key's file column. + Json { reader: JsonReader, columns: HashMap, width: usize }, +} + +enum Next { + Row(Result, String>), + End, + // Nothing after this point can be read. + Broken(String), +} + +impl Rows { + fn next(&mut self, conv: &ValueConverter, sources: &[usize], ignored: &mut Vec) -> Next { + match self { + Self::Csv(reader) => match reader.read() { + Ok(Some(record)) => Next::Row(conv.build_values(record, sources)), + Ok(None) => Next::End, + Err(err) => Next::Row(Err(err.to_string())), + }, + Self::Json { reader, columns, width } => match reader.read() { + Ok(Some(record)) => { + let mut cells: Vec>> = vec![None; *width]; + for (key, raw) in &record.fields { + match columns.get(key.as_ref()) { + Some(&column) => cells[column] = Some(json_cell(raw)), + None if ignored.len() < MAX_REPORTED_ERRORS && !ignored.iter().any(|k| k == key) => { + ignored.push(key.to_string()); + } + None => {} + } + } + Next::Row(conv.build_json_values(&cells, sources)) + } + Ok(None) => Next::End, + Err(JsonError::Row(err)) => Next::Row(Err(err)), + Err(JsonError::Fatal(err)) => Next::Broken(err), + }, + } + } + + fn bytes_read(&self) -> u64 { + match self { + Self::Csv(reader) => reader.bytes_read(), + Self::Json { reader, .. } => reader.bytes_read(), + } + } +} + // Retries a failed batch row by row so one bad row doesn't sink the rest. #[allow(clippy::too_many_arguments)] async fn flush( @@ -549,6 +655,13 @@ async fn insert( session.execute_params(&sql, &args).await.map(|_| ()) } +// json and jsonb, not arrays of them. +fn is_json_type(data_type: &str) -> bool { + let lower = data_type.trim().to_ascii_lowercase(); + let base = lower.strip_prefix("nullable(").and_then(|t| t.strip_suffix(')')).unwrap_or(&lower); + matches!(base.trim(), "json" | "jsonb") +} + fn mapped_types(column_types: &[String], sources: &[usize]) -> Vec { sources .iter() @@ -571,6 +684,8 @@ struct ValueConverter { bit_cols: HashMap, // Columns that accept ''. Elsewhere a quoted empty field is still NULL. text_cols: HashSet, + // json and jsonb columns, which a JSON import gives every value as JSON text. + json_cols: HashSet, null_literal: String, trim: bool, bool_as_bool: bool, @@ -592,6 +707,21 @@ impl ValueConverter { .collect() } + // `cells` holds each file column's cell, None where the row lacks its key. + fn build_json_values(&self, cells: &[Option>], sources: &[usize]) -> Result, String> { + sources + .iter() + .enumerate() + .map(|(i, &src)| { + let value = self.json_value(i, cells.get(src).and_then(Option::as_ref)); + match self.bit_cols.get(&i) { + Some(column) => bit_digits(column, &value), + None => Ok(value), + } + }) + .collect() + } + fn value(&self, i: usize, field: Option<&CsvField>) -> Value { let Some(field) = field else { return Value::Null }; let v = if self.trim { field.value.trim() } else { field.value.as_str() }; @@ -601,7 +731,36 @@ impl ValueConverter { if v.is_empty() { return if field.quoted && self.text_cols.contains(&i) { Value::Text(String::new()) } else { Value::Null }; } - let v = undefuse_formula(v); + self.text_value(i, undefuse_formula(v)) + } + + // No NULL text, trimming or formula guard, which are CSV's. + fn json_value(&self, i: usize, cell: Option<&JsonCell<'_>>) -> Value { + let Some(cell) = cell else { return Value::Null }; + if self.json_cols.contains(&i) { + return match cell { + JsonCell::Null => Value::Null, + JsonCell::Bool(b) => Value::Text(b.to_string()), + JsonCell::Number(raw) | JsonCell::Json(raw) => Value::Text(raw.to_string()), + JsonCell::Text(s) => Value::Text(serde_json::to_string(s).unwrap_or_default()), + }; + } + match cell { + JsonCell::Null => Value::Null, + JsonCell::Bool(b) if self.text_cols.contains(&i) && !self.bool_cols.contains(&i) => { + Value::Text(b.to_string()) + } + JsonCell::Bool(b) => normalize_bool(&b.to_string(), self.bool_as_bool && self.bool_cols.contains(&i)), + JsonCell::Text(s) if s.is_empty() && self.text_cols.contains(&i) => Value::Text(String::new()), + JsonCell::Text(s) if s.is_empty() => Value::Null, + JsonCell::Text(s) => self.text_value(i, s), + JsonCell::Number(raw) => self.text_value(i, raw), + JsonCell::Json(raw) => Value::Text(raw.to_string()), + } + } + + // A value that isn't empty, as text from the file. + fn text_value(&self, i: usize, v: &str) -> Value { if self.bool_cols.contains(&i) { normalize_bool(v, self.bool_as_bool) } else if self.bool_int_cols.contains(&i) { diff --git a/crates/barsql-app/src/lib.rs b/crates/barsql-app/src/lib.rs index 4df08bb..5bf8384 100644 --- a/crates/barsql-app/src/lib.rs +++ b/crates/barsql-app/src/lib.rs @@ -28,7 +28,7 @@ use barsql_storage::Stores; pub use backup::{BackupOutcome, BackupRequest}; pub use barsql_db::tls::install_default_provider; -pub use barsql_io::{CsvOptions, ImportPreview}; +pub use barsql_io::{CsvOptions, FileFormat, ImportPreview, JsonShape, detect_format}; pub use barsql_storage::{ BuilderRef, ConnectionFolder, DiagramRef, EditorSession, EditorTab, HISTORY_LIMIT, StructureRef, TablePlace, TableViewRef, @@ -38,7 +38,7 @@ pub use events::{ AppEvent, ImportDone, ImportEvent, ImportHandle, ImportProgress, RunEvent, RunHandle, RunResult, Unsaved, }; pub use files::{find_sqlite_arg, is_sqlite_file, path_from_file_url, sqlite_file_payload}; -pub use import::{CsvImportRequest, ImportResult, SqlImportRequest}; +pub use import::{ImportResult, SqlImportRequest, TableFormat, TableImportRequest}; pub use info::{AppInfo, PathDefaults, app_info, path_defaults}; pub use runs::BufferedResult; pub(crate) use runs::ChangeOutcome; diff --git a/crates/barsql-app/tests/app_sqlite.rs b/crates/barsql-app/tests/app_sqlite.rs index f113260..2bdacbe 100644 --- a/crates/barsql-app/tests/app_sqlite.rs +++ b/crates/barsql-app/tests/app_sqlite.rs @@ -3,8 +3,8 @@ mod support; use std::time::{Duration, Instant}; use barsql_app::{ - AppEvent, BackupOutcome, BackupRequest, CsvImportRequest, CsvOptions, ResultEdits, ResultTable, RunEvent, - SqlImportRequest, Unsaved, + AppEvent, BackupOutcome, BackupRequest, CsvOptions, ResultEdits, ResultTable, RunEvent, SqlImportRequest, + TableFormat, TableImportRequest, Unsaved, }; use barsql_core::schema::primary_keys; use barsql_core::{DriverType, ObjectKind, Row, RowDelete, RowUpdate, SavedQuery, TableDataRequest, Value}; @@ -640,22 +640,22 @@ async fn import_fixture(file: &str, content: &str) -> (Fixture, String, String) (f, id, path) } -async fn run_csv(f: &Fixture, id: &str, req: CsvImportRequest) -> barsql_app::ImportResult { - let (_, done) = import_outcome(f.app.import_csv(id, "imp", req).await.unwrap()).await; +async fn run_import(f: &Fixture, id: &str, req: TableImportRequest) -> barsql_app::ImportResult { + let (_, done) = import_outcome(f.app.import_table(id, "imp", req).await.unwrap()).await; done.result.unwrap_or_else(|| panic!("import failed: {}", done.error)) } #[tokio::test] async fn csv_import_creates_the_table_and_loads_rows() { let (f, id, path) = import_fixture("people.csv", "id,name,score\n1,Alice,9.5\n2,Bob,7\n3,Carol,8.25\n").await; - let result = run_csv( + let result = run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "people".into(), create_table: true, - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "name", "score"]), column_types: names(&["int", "text", "float"]), ..Default::default() @@ -673,13 +673,13 @@ async fn csv_import_creates_the_table_and_loads_rows() { async fn csv_import_mapping_nulls_and_bad_rows() { let (f, id, path) = import_fixture("people.csv", "id,name,ignored\n1,Alice,junk\n2,Bob,junk\n").await; f.exec(&id, "CREATE TABLE people (id INTEGER NOT NULL, name TEXT)").await; - let result = run_csv( + let result = run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "people".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "name", ""]), ..Default::default() }, @@ -690,13 +690,13 @@ async fn csv_import_mapping_nulls_and_bad_rows() { let path = f.write("nulls.csv", "id,name\n1,\n2,\\N\n3,Carol\n"); let options = CsvOptions { has_header: true, null_literal: "\\N".into(), ..Default::default() }; - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "people".into(), - options, + format: TableFormat::Csv(options), mapping: names(&["id", "name"]), ..Default::default() }, @@ -705,13 +705,13 @@ async fn csv_import_mapping_nulls_and_bad_rows() { assert_eq!(f.query(&id, "SELECT COUNT(*) FROM people WHERE name IS NULL").await, [["2"]]); let path = f.write("bad.csv", "id,name\n1,Alice\n2,Bob\n,Carol\n4,Dave\n"); - let result = run_csv( + let result = run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "people".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "name"]), batch_size: 10, ..Default::default() @@ -726,16 +726,16 @@ async fn csv_import_mapping_nulls_and_bad_rows() { async fn csv_import_stop_on_error_keeps_committed_batches() { let (f, id, path) = import_fixture("people.csv", "id,name\n1,Alice\n,Bob\n3,Carol\n").await; f.exec(&id, "CREATE TABLE people (id INTEGER NOT NULL, name TEXT)").await; - let req = CsvImportRequest { + let req = TableImportRequest { path, table: "people".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "name"]), batch_size: 1, stop_on_error: true, ..Default::default() }; - let (_, done) = import_outcome(f.app.import_csv(&id, "imp", req).await.unwrap()).await; + let (_, done) = import_outcome(f.app.import_table(&id, "imp", req).await.unwrap()).await; assert!(done.result.is_none() && !done.error.is_empty()); assert_eq!(f.query(&id, "SELECT COUNT(*) FROM people").await, [["1"]]); } @@ -745,14 +745,14 @@ async fn csv_import_truncates_headerless_and_booleans() { let (f, id, path) = import_fixture("people.csv", "id,name\n9,Zoe\n").await; f.exec(&id, "CREATE TABLE people (id INTEGER, name TEXT)").await; f.exec(&id, "INSERT INTO people (id, name) VALUES (1, 'Old')").await; - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "people".into(), truncate: true, - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "name"]), ..Default::default() }, @@ -761,14 +761,14 @@ async fn csv_import_truncates_headerless_and_booleans() { assert_eq!(f.query(&id, "SELECT name FROM people").await, [["Zoe"]]); let path = f.write("headerless.csv", "1,Alice\n2,Bob\n"); - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "people2".into(), create_table: true, - options: header(false), + format: TableFormat::Csv(header(false)), mapping: names(&["col1", "col2"]), column_types: names(&["int", "text"]), ..Default::default() @@ -778,14 +778,14 @@ async fn csv_import_truncates_headerless_and_booleans() { assert_eq!(f.query(&id, "SELECT col2 FROM people2 ORDER BY col1").await, [["Alice"], ["Bob"]]); let path = f.write("flags.csv", "id,active\n1,true\n2,no\n3,Y\n"); - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "flags".into(), create_table: true, - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "active"]), column_types: names(&["int", "bool"]), ..Default::default() @@ -799,13 +799,13 @@ async fn csv_import_truncates_headerless_and_booleans() { async fn csv_import_value_shapes() { let (f, id, path) = import_fixture("blanks.csv", "id,a,b\n1,,\"\"\n").await; f.exec(&id, "CREATE TABLE t (id INTEGER, a TEXT, b TEXT NOT NULL)").await; - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "t".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "a", "b"]), ..Default::default() }, @@ -815,13 +815,13 @@ async fn csv_import_value_shapes() { f.exec(&id, "CREATE TABLE f (v TEXT)").await; let path = f.write("formulas.csv", "v\n'=1+1\n'@handle\n'-not a number\n'plain\nO'Brien\n"); - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "f".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["v"]), ..Default::default() }, @@ -833,23 +833,29 @@ async fn csv_import_value_shapes() { f.exec(&id, "CREATE TABLE n (v TEXT)").await; let path = f.write("nulls.csv", "v\n\"\\N\"\n"); let options = CsvOptions { has_header: true, null_literal: "\\N".into(), ..Default::default() }; - run_csv( + run_import( &f, &id, - CsvImportRequest { path, table: "n".into(), options, mapping: names(&["v"]), ..Default::default() }, + TableImportRequest { + path, + table: "n".into(), + format: TableFormat::Csv(options), + mapping: names(&["v"]), + ..Default::default() + }, ) .await; assert_eq!(f.query(&id, "SELECT v IS NULL FROM n").await, [["1"]], "the NULL literal beats quoting"); f.exec(&id, "CREATE TABLE b (v TEXT)").await; let path = f.write("flags.csv", "v\ntrue\nf\n"); - run_csv( + run_import( &f, &id, - CsvImportRequest { + TableImportRequest { path, table: "b".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["v"]), column_types: names(&["bool"]), ..Default::default() @@ -863,14 +869,137 @@ async fn csv_import_value_shapes() { async fn csv_import_reports_the_row_target_in_progress() { let (f, id, path) = import_fixture("people.csv", "id,name\n1,Alice\n2,Bob\n3,Carol\n").await; f.exec(&id, "CREATE TABLE people (id INTEGER, name TEXT)").await; - let req = CsvImportRequest { + let req = TableImportRequest { path, table: "people".into(), - options: header(true), + format: TableFormat::Csv(header(true)), mapping: names(&["id", "name"]), ..Default::default() }; - let (progress, done) = import_outcome(f.app.import_csv(&id, "imp", req).await.unwrap()).await; + let (progress, done) = import_outcome(f.app.import_table(&id, "imp", req).await.unwrap()).await; + assert_eq!(done.result.unwrap().inserted, 3); + let last = progress.last().expect("a final progress event"); + assert_eq!((last.total_rows, last.processed, last.inserted), (3, 3, 3)); + assert_eq!(last.bytes_read, last.total_bytes); +} + +fn json(keys: &[&str]) -> TableFormat { + TableFormat::Json { keys: names(keys) } +} + +#[tokio::test] +async fn json_import_creates_the_table_from_its_preview() { + let content = r#"[ + {"id": 1, "name": "Alice", "tags": ["a", "b"], "score": 9.5, "ok": true}, + {"id": 2, "name": "Bob", "tags": null, "score": 7, "ok": false} +]"#; + let (f, id, path) = import_fixture("people.json", content).await; + let preview = f.app.preview_json_file(&id, &path).unwrap(); + assert_eq!(preview.inferred_types, ["int", "text", "json", "float", "bool"]); + assert_eq!(preview.sql_types, ["INTEGER", "TEXT", "TEXT", "REAL", "INTEGER"]); + let result = run_import( + &f, + &id, + TableImportRequest { + path, + table: "people".into(), + create_table: true, + format: TableFormat::Json { keys: preview.keys.clone() }, + mapping: preview.columns.clone(), + column_types: preview.inferred_types.clone(), + ..Default::default() + }, + ) + .await; + assert_eq!((result.inserted, result.skipped), (2, 0)); + assert_eq!( + f.query(&id, "SELECT id, name, tags, score, ok FROM people ORDER BY id").await, + [["1", "Alice", "[\"a\", \"b\"]", "9.5", "1"], ["2", "Bob", "NULL", "7", "0"]] + ); +} + +#[tokio::test] +async fn json_lines_load_into_an_existing_table_by_key() { + let content = "{\"ID\": 1, \"note\": \"plain\", \"amount\": 12345678901234567890123}\n\ + {\"ID\": 2, \"note\": \"\", \"extra\": true}\n\ + {\"ID\": 3, \"note\": {\"nested\": [1, 2]}, \"amount\": null}\n"; + let (f, id, path) = import_fixture("rows.jsonl", content).await; + f.exec(&id, "CREATE TABLE t (id INTEGER, note TEXT, amount TEXT)").await; + let result = run_import( + &f, + &id, + TableImportRequest { + path, + table: "t".into(), + format: json(&["ID", "note", "amount"]), + mapping: names(&["id", "note", "amount"]), + ..Default::default() + }, + ) + .await; + assert_eq!((result.inserted, result.skipped), (3, 0)); + assert_eq!(result.ignored_keys, ["extra"], "a key the preview never saw"); + assert_eq!( + f.query(&id, "SELECT id, note, amount FROM t ORDER BY id").await, + [["1", "plain", "12345678901234567890123"], ["2", "", "NULL"], ["3", "{\"nested\": [1, 2]}", "NULL"]] + ); +} + +#[tokio::test] +async fn json_values_load_by_the_target_columns_type() { + let content = r#"[{"j": "just a string", "k": {"a": 1}, "n": "", "flag": true, "word": false, "skip": 1}]"#; + let (f, id, path) = import_fixture("shapes.json", content).await; + f.exec(&id, "CREATE TABLE s (j JSON, k JSON, n INTEGER, flag BOOLEAN, word TEXT)").await; + let result = run_import( + &f, + &id, + TableImportRequest { + path, + table: "s".into(), + format: json(&["j", "k", "n", "flag", "word", "skip"]), + mapping: names(&["j", "k", "n", "flag", "word", ""]), + ..Default::default() + }, + ) + .await; + assert!(result.ignored_keys.is_empty(), "a skipped column's key was seen: {:?}", result.ignored_keys); + assert_eq!( + f.query(&id, "SELECT j, k, n, flag, word FROM s").await, + [["\"just a string\"", "{\"a\": 1}", "NULL", "1", "false"]] + ); +} + +#[tokio::test] +async fn json_import_skips_bad_rows_and_names_their_lines() { + let (f, id, path) = import_fixture("bad.jsonl", "{\"id\":1}\n{\"id\":}\n[2]\n{\"id\":3}\n").await; + f.exec(&id, "CREATE TABLE t (id INTEGER)").await; + let req = TableImportRequest { + path, + table: "t".into(), + format: json(&["id"]), + mapping: names(&["id"]), + ..Default::default() + }; + let result = run_import(&f, &id, req.clone()).await; + assert_eq!((result.inserted, result.skipped), (2, 2)); + assert_eq!(result.errors, ["line 2: expected value", "line 3: invalid type: sequence, expected a JSON object"]); + let stop = TableImportRequest { stop_on_error: true, ..req }; + let (_, done) = import_outcome(f.app.import_table(&id, "imp", stop).await.unwrap()).await; + assert_eq!(done.error, "line 2: expected value"); +} + +#[tokio::test] +async fn json_import_reports_rows_and_bytes_in_progress() { + let (f, id, path) = import_fixture("p.json", "[{\"id\":1},{\"id\":2},{\"id\":3}]").await; + f.exec(&id, "CREATE TABLE t (id INTEGER)").await; + let req = TableImportRequest { + path, + table: "t".into(), + format: json(&["id"]), + mapping: names(&["id"]), + ..Default::default() + }; + let (progress, done) = import_outcome(f.app.import_table(&id, "imp", req).await.unwrap()).await; assert_eq!(done.result.unwrap().inserted, 3); let last = progress.last().expect("a final progress event"); assert_eq!((last.total_rows, last.processed, last.inserted), (3, 3, 3)); @@ -942,16 +1071,16 @@ async fn sql_import_runs_statements_and_reports_failures() { async fn imports_validate_the_request_and_the_connection() { let (f, id, path) = import_fixture("people.csv", "id\n1\n").await; let base = - CsvImportRequest { path: path.clone(), table: "t".into(), mapping: names(&["id"]), ..Default::default() }; - assert!(f.app.import_csv(&id, "", base.clone()).await.is_err()); - assert!(f.app.import_csv(&id, "i", CsvImportRequest { path: String::new(), ..base.clone() }).await.is_err()); - assert!(f.app.import_csv(&id, "i", CsvImportRequest { table: String::new(), ..base.clone() }).await.is_err()); - assert!(f.app.import_csv(&id, "i", CsvImportRequest { mapping: vec![], ..base.clone() }).await.is_err()); + TableImportRequest { path: path.clone(), table: "t".into(), mapping: names(&["id"]), ..Default::default() }; + assert!(f.app.import_table(&id, "", base.clone()).await.is_err()); + assert!(f.app.import_table(&id, "i", TableImportRequest { path: String::new(), ..base.clone() }).await.is_err()); + assert!(f.app.import_table(&id, "i", TableImportRequest { table: String::new(), ..base.clone() }).await.is_err()); + assert!(f.app.import_table(&id, "i", TableImportRequest { mapping: vec![], ..base.clone() }).await.is_err()); let mut cfg = f.app.list_connections().remove(0); cfg.read_only = true; f.app.save_connection(cfg).await.unwrap(); - assert!(f.app.import_csv(&id, "i", base).await.is_err()); + assert!(f.app.import_table(&id, "i", base).await.is_err()); assert!(f.app.import_sql(&id, "i", SqlImportRequest { path, stop_on_error: false }).await.is_err()); } diff --git a/crates/barsql-app/tests/e2e/harness.rs b/crates/barsql-app/tests/e2e/harness.rs index 6622974..666b93f 100644 --- a/crates/barsql-app/tests/e2e/harness.rs +++ b/crates/barsql-app/tests/e2e/harness.rs @@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use barsql_app::{BarApp, BufferedResult, CsvImportRequest, CsvOptions, ImportResult, RunEvent}; +use barsql_app::{BarApp, BufferedResult, CsvOptions, ImportResult, RunEvent, TableFormat, TableImportRequest}; use barsql_core::{ConnectionConfig, DriverType, QueryError, ResultSummary, Row, TableDataRequest, Value}; use barsql_db::{Cancel, Cell, Engine, ResultChunk}; use barsql_io::{ExportFormat, export_to_string}; @@ -400,17 +400,36 @@ impl E2e { let options = CsvOptions { has_header: true, ..Default::default() }; let preview = self.app.preview_import_file(&self.id, path, &options).unwrap_or_else(|e| panic!("preview: {e:?}")); - let request = CsvImportRequest { + self.import_table(table, columns.to_vec(), path, TableFormat::Csv(options), preview.inferred_types).await + } + + // Keys outside `columns` are skipped. + pub async fn import_json(&self, table: &str, columns: &[String], path: &str) -> ImportResult { + let preview = self.app.preview_json_file(&self.id, path).unwrap_or_else(|e| panic!("preview: {e:?}")); + let mapping = preview.keys.iter().map(|key| if columns.contains(key) { key.clone() } else { String::new() }); + let format = TableFormat::Json { keys: preview.keys.clone() }; + self.import_table(table, mapping.collect(), path, format, preview.inferred_types).await + } + + async fn import_table( + &self, + table: &str, + mapping: Vec, + path: &str, + format: TableFormat, + column_types: Vec, + ) -> ImportResult { + let request = TableImportRequest { path: path.into(), schema: self.schema(), table: table.into(), - options, - mapping: columns.to_vec(), - column_types: preview.inferred_types, + format, + mapping, + column_types, ..Default::default() }; let handle = - self.app.import_csv(&self.id, "roundtrip", request).await.unwrap_or_else(|e| panic!("import: {e:?}")); + self.app.import_table(&self.id, "roundtrip", request).await.unwrap_or_else(|e| panic!("import: {e:?}")); let (_, done) = import_outcome(handle).await; assert!(done.error.is_empty(), "import aborted: {}", done.error); done.result.expect("an import result") diff --git a/crates/barsql-app/tests/e2e/roundtrip.rs b/crates/barsql-app/tests/e2e/roundtrip.rs index b5648e3..a1b2883 100644 --- a/crates/barsql-app/tests/e2e/roundtrip.rs +++ b/crates/barsql-app/tests/e2e/roundtrip.rs @@ -22,6 +22,10 @@ fn write_csv(e: &E2e, csv: &str) -> String { e.write(&format!("{}.csv", unique_table("export")), &format!("{csv}\n")) } +fn write_json(e: &E2e, json: &str) -> String { + e.write(&format!("{}.json", unique_table("export")), &format!("{json}\n")) +} + // NULL vs '' quoting, the formula guard and MySQL datetime literals must survive the trip. each_engine!(async fn round_trip_export_then_import(e) { let columns = match e.kind { @@ -56,6 +60,70 @@ each_engine!(async fn round_trip_export_then_import(e) { assert_eq!(after.rows, before.rows, "the round trip changed the rows\n{exported}"); }); +// A JSON null in a json column comes back as SQL NULL, since the export writes both as null. So no row has one. +each_engine!(async fn round_trip_json_export_then_import(e) { + let columns = match e.kind { + Kind::ClickHouse => "id Int32, nullable_text Nullable(String), empty_text String, payload Nullable(String), \ + amount Nullable(Decimal(10, 2)), flag Nullable(Bool), note Nullable(String)" + .to_string(), + Kind::SqlServer => "id INT, nullable_text NVARCHAR(MAX), empty_text NVARCHAR(MAX) NOT NULL, \ + payload NVARCHAR(MAX), amount DECIMAL(10,2), flag BIT, note NVARCHAR(MAX)" + .to_string(), + Kind::Postgres | Kind::MySql | Kind::MariaDb | Kind::Turso => format!( + "id INT, nullable_text TEXT, empty_text TEXT NOT NULL, payload {}, amount DECIMAL(10,2), flag {}, note TEXT", + e.json_type(), + e.bool_type() + ), + }; + let (src, dst) = fresh_tables(&e, "rtj", &columns).await; + let (yes, no) = if e.is_sqlserver() { ("1", "0") } else { ("TRUE", "FALSE") }; + e.exec(&format!( + r#"INSERT INTO {src} (id, nullable_text, empty_text, payload, amount, flag, note) VALUES + (1, NULL, '', '{{"a": 1, "b": [true, null]}}', 12.34, {yes}, 'plain'), + (2, 'set', 'x', '{{"nested": {{"k": "v, with comma"}}}}', NULL, {no}, ''), + (3, NULL, '', '[1, "two"]', 0.00, NULL, '-not a number')"# + )) + .await; + let cols = names(&["id", "nullable_text", "empty_text", "payload", "amount", "flag", "note"]); + let select = |table: &str| format!("SELECT {} FROM {table} ORDER BY id", cols.join(", ")); + let exported = e.stream(&select(&src)).await.export(ExportFormat::Json); + let result = e.import_json(&dst, &cols, &write_json(&e, &exported)).await; + assert_eq!(result.skipped, 0, "rows were rejected: {}", first_error(&result)); + let (before, after) = (e.query(&select(&src)).await, e.query(&select(&dst)).await); + assert_eq!(after.rows, before.rows, "the round trip changed the rows\n{exported}"); +}); + +// Keys come and go from row to row, so a missing one is NULL. +each_engine!(async fn json_lines_rows_with_their_own_keys(e) { + let (score, flag, payload) = match e.kind { + Kind::ClickHouse => ("Nullable(Decimal(10, 2))", "Nullable(Bool)", "Nullable(String)"), + _ => ("DECIMAL(10,2)", e.bool_type(), e.json_type()), + }; + let name = match e.kind { + Kind::ClickHouse => "Nullable(String)", + Kind::SqlServer => "NVARCHAR(MAX)", + _ => "TEXT", + }; + let columns = format!("id INT, name {name}, score {score}, active {flag}, payload {payload}"); + let (src, dst) = fresh_tables(&e, "jsonl", &columns).await; + let yes = if e.is_sqlserver() { "1" } else { "TRUE" }; + e.exec(&format!( + r#"INSERT INTO {src} (id, name, score, active, payload) VALUES + (1, 'ann', 12.5, NULL, NULL), (2, NULL, NULL, {yes}, '{{"k": [1, 2]}}'), (3, '', NULL, NULL, NULL)"# + )) + .await; + let lines = "{\"id\": 1, \"name\": \"ann\", \"score\": 12.5}\n\ + {\"id\": 2, \"active\": true, \"payload\": {\"k\": [1, 2]}}\n\ + \n\ + {\"id\": 3, \"name\": \"\", \"score\": null}\n"; + let path = e.write(&format!("{}.jsonl", unique_table("lines")), lines); + let cols = names(&["id", "name", "score", "active", "payload"]); + let result = e.import_json(&dst, &cols, &path).await; + assert_eq!((result.inserted, result.skipped), (3, 0), "rejected: {}", first_error(&result)); + let select = |table: &str| format!("SELECT {} FROM {table} ORDER BY id", cols.join(", ")); + assert_eq!(e.query(&select(&dst)).await.rows, e.query(&select(&src)).await.rows); +}); + each_engine!(async fn bit_columns_round_trip_through_csv_and_sql_inserts(e) { if !e.is_mysql() { return; @@ -119,6 +187,14 @@ const SHAPES: &[(&str, &str, &str, &str)] = &[ ]; each_engine!(async fn round_trip_value_shapes(e) { + value_shapes(&e, ExportFormat::Csv).await; +}); + +each_engine!(async fn round_trip_value_shapes_through_json(e) { + value_shapes(&e, ExportFormat::Json).await; +}); + +async fn value_shapes(e: &E2e, format: ExportFormat) { // rid keeps a NULL-only row from exporting as a blank line, which CSV skips. let mut cols = vec!["rid".to_string()]; let mut defs = vec!["rid INT".to_string()]; @@ -164,7 +240,7 @@ each_engine!(async fn round_trip_value_shapes(e) { }; vals.push(value); } - let (src, dst) = fresh_tables(&e, "rt2", &defs.join(", ")).await; + let (src, dst) = fresh_tables(e, "rt2", &defs.join(", ")).await; e.exec(&format!("INSERT INTO {src} ({}) VALUES ({})", cols.join(", "), vals.join(", "))).await; let select = format!("SELECT {} FROM {src}", cols.join(", ")); let before = e.stream(&select).await; @@ -174,22 +250,31 @@ each_engine!(async fn round_trip_value_shapes(e) { for (i, (col, ..)) in SHAPES.iter().enumerate() { let pair = names(&["rid", col]); let types = [before.types[0].clone(), before.types[i + 1].clone()]; - let csv = export_to_string(ExportFormat::Csv, &pair, &types, None, None, [vec![chunk.cell(0, 0), chunk.cell(0, i + 1)]]); + let exported = + export_to_string(format, &pair, &types, None, None, [vec![chunk.cell(0, 0), chunk.cell(0, i + 1)]]); // ClickHouse deletes only with a WHERE. let empty = if e.is_clickhouse() { format!("TRUNCATE TABLE {dst}") } else { format!("DELETE FROM {dst}") }; e.exec(&empty).await; - let result = e.import_csv(&dst, &pair, &write_csv(&e, &csv)).await; + let json = format == ExportFormat::Json; + let result = if json { + e.import_json(&dst, &pair, &write_json(e, &exported)).await + } else { + e.import_csv(&dst, &pair, &write_csv(e, &exported)).await + }; if result.skipped > 0 { failures.push(format!("{col:<18} rejected: {}", first_error(&result))); continue; } let got = e.query(&format!("SELECT {col} FROM {dst}")).await.rows.remove(0).remove(0); - if got != want_row[i + 1] { - failures.push(format!("{col:<18} changed: {:?} -> {got:?}\n{csv}", want_row[i + 1])); + // JSON writes a json column's JSON null like SQL NULL. + let want = + if json && exported.contains(&format!("\"{col}\": null")) { Value::Null } else { want_row[i + 1].clone() }; + if got != want { + failures.push(format!("{col:<18} changed: {want:?} -> {got:?}\n{exported}")); } } assert!(failures.is_empty(), "{}", failures.join("\n")); -}); +} // A file that quotes every field still loads, with '' only where the column can hold one. each_engine!(async fn import_quoted_empty_fields_by_column_type(e) { diff --git a/crates/barsql-io/src/csv_import.rs b/crates/barsql-io/src/csv_import.rs index f7222c9..ae281ec 100644 --- a/crates/barsql-io/src/csv_import.rs +++ b/crates/barsql-io/src/csv_import.rs @@ -7,6 +7,7 @@ use barsql_sql::dml::sql_type_for; use serde::{Deserialize, Serialize}; use crate::csv::{CsvField, CsvReader, Source, csv_values}; +use crate::json_import::JsonShape; const CANDIDATE_DELIMITERS: [char; 4] = [',', ';', '\t', '|']; pub const PREVIEW_ROW_LIMIT: usize = 100; @@ -120,6 +121,8 @@ pub const INFER_FLOAT: &str = "float"; pub const INFER_DATE: &str = "date"; pub const INFER_TIMESTAMP: &str = "timestamp"; pub const INFER_TEXT: &str = "text"; +// JSON imports only. +pub const INFER_JSON: &str = "json"; const INFER_ORDER: [&str; 5] = [INFER_BOOL, INFER_INT, INFER_FLOAT, INFER_DATE, INFER_TIMESTAMP]; @@ -217,6 +220,14 @@ pub struct ImportPreview { // Some bytes weren't UTF-8 and read as U+FFFD. A file too large to count is checked only in the sample. #[serde(default, skip_serializing_if = "is_false")] pub not_utf8: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub json_shape: Option, + // The JSON key behind each column, which unique_column_names may have renamed. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub keys: Vec, + // Columns and types come from the first SAMPLE_ROWS rows only. + #[serde(default, skip_serializing_if = "is_false")] + pub sampled: bool, } pub fn preview_file(path: &Path, driver: &DriverType, opts: &CsvOptions) -> Result { @@ -245,6 +256,7 @@ pub fn preview_file(path: &Path, driver: &DriverType, opts: &CsvOptions) -> Resu truncated, total_rows: scanned.map_or(0, |scan| scan.rows), not_utf8: scanned.is_some_and(|scan| scan.not_utf8) || reader.replaced() > 0, + ..Default::default() }) } diff --git a/crates/barsql-io/src/detect.rs b/crates/barsql-io/src/detect.rs new file mode 100644 index 0000000..d389ed2 --- /dev/null +++ b/crates/barsql-io/src/detect.rs @@ -0,0 +1,97 @@ +use std::fs::File; +use std::io::Read; +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +const SNIFF_BYTES: u64 = 4096; +// Words a script starts with, then a space or ;. A CSV header has its delimiter or a line break there instead. +const SQL_STARTS: [&str; 27] = [ + "alter", "begin", "call", "comment", "commit", "copy", "create", "declare", "delete", "do", "drop", "exec", + "execute", "go", "grant", "insert", "lock", "merge", "pragma", "replace", "select", "set", "start", "truncate", + "update", "use", "with", +]; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FileFormat { + #[default] + Csv, + Json, + Sql, +} + +// By extension, else by the first few KB. A file that can't be read is CSV, whose preview then says why. +pub fn detect_format(path: &Path) -> FileFormat { + let ext = path.extension().and_then(|ext| ext.to_str()).map(str::to_ascii_lowercase); + match ext.as_deref() { + Some("csv" | "tsv" | "tab" | "psv") => return FileFormat::Csv, + Some("json" | "jsonl" | "ndjson") => return FileFormat::Json, + Some("sql") => return FileFormat::Sql, + _ => {} + } + let mut head = Vec::new(); + match File::open(path).and_then(|file| file.take(SNIFF_BYTES).read_to_end(&mut head)) { + Ok(_) => sniff_format(&head), + Err(_) => FileFormat::Csv, + } +} + +pub fn sniff_format(head: &[u8]) -> FileFormat { + let text = String::from_utf8_lossy(head); + let text = text.trim_start_matches('\u{feff}').trim_start(); + if text.starts_with(['[', '{']) { + return FileFormat::Json; + } + if text.starts_with("--") || text.starts_with("/*") { + return FileFormat::Sql; + } + let word = text.split(|c: char| !c.is_ascii_alphabetic()).next().unwrap_or_default(); + let spaced = text[word.len()..].starts_with([' ', '\t', ';']); + if spaced && SQL_STARTS.contains(&word.to_ascii_lowercase().as_str()) { FileFormat::Sql } else { FileFormat::Csv } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_extension_decides_first() { + let dir = tempfile::tempdir().unwrap(); + for (name, want) in [ + ("a.JSON", FileFormat::Json), + ("a.jsonl", FileFormat::Json), + ("a.ndjson", FileFormat::Json), + ("a.csv", FileFormat::Csv), + ("a.tsv", FileFormat::Csv), + ("a.sql", FileFormat::Sql), + ] { + let path = dir.path().join(name); + std::fs::write(&path, "[{\"looks\": \"like json\"}]").unwrap(); + assert_eq!(detect_format(&path), want, "{name}"); + } + let txt = dir.path().join("rows.txt"); + std::fs::write(&txt, "{\"a\":1}\n").unwrap(); + assert_eq!(detect_format(&txt), FileFormat::Json, "a .txt is sniffed"); + assert_eq!(detect_format(&dir.path().join("missing.dat")), FileFormat::Csv); + } + + #[test] + fn content_decides_without_a_known_extension() { + for (head, want) in [ + (&b"[{}]"[..], FileFormat::Json), + (b"\xef\xbb\xbf {\"a\":1}", FileFormat::Json), + (b"-- seed\nINSERT INTO t VALUES (1);", FileFormat::Sql), + (b"/* dump */", FileFormat::Sql), + (b"\n CREATE TABLE t (id int);", FileFormat::Sql), + (b"insert into t values (1);", FileFormat::Sql), + (b"select,count\n1,2\n", FileFormat::Csv), + (b"comment\nfirst one\n", FileFormat::Csv), + (b"COMMIT;", FileFormat::Sql), + (b"name,age\nann,31\n", FileFormat::Csv), + (b"", FileFormat::Csv), + ] { + assert_eq!(sniff_format(head), want, "{:?}", String::from_utf8_lossy(head)); + } + } +} diff --git a/crates/barsql-io/src/json_import.rs b/crates/barsql-io/src/json_import.rs new file mode 100644 index 0000000..5f356cb --- /dev/null +++ b/crates/barsql-io/src/json_import.rs @@ -0,0 +1,802 @@ +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt; +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom}; +use std::path::Path; + +use barsql_core::DriverType; +use barsql_sql::dml::sql_type_for; +use serde::de::{self, MapAccess, Visitor}; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::value::RawValue; + +use crate::csv::Source; +use crate::csv_import::{ + INFER_BOOL, INFER_DATE, INFER_FLOAT, INFER_INT, INFER_JSON, INFER_TEXT, INFER_TIMESTAMP, ImportPreview, + MAX_ROW_COUNT_BYTES, PREVIEW_ROW_LIMIT, open_error, unique_column_names, +}; +use crate::time_layouts::{matches_date, matches_timestamp}; + +// Files too big to read twice take their columns from this many rows. +pub const SAMPLE_ROWS: usize = 1000; +// A row this big means the JSON broke and swallowed the rest of the file. +const MAX_RECORD_BYTES: usize = if cfg!(test) { 1024 } else { 64 << 20 }; +const CHUNK: usize = 64 * 1024; +const NOT_UTF8: &str = "the file isn't UTF-8 text. Save it as UTF-8 and import it again."; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum JsonShape { + Array, + Lines, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JsonError { + // That record is left out and the reading goes on. + Row(String), + // Nothing after this point can be read. + Fatal(String), +} + +impl JsonError { + pub fn message(&self) -> &str { + match self { + Self::Row(message) | Self::Fatal(message) => message, + } + } +} + +// Fields in file order, a repeated key each time it appears. +pub struct JsonRecord<'a> { + pub line: u64, + pub fields: Vec<(Cow<'a, str>, &'a RawValue)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JsonCell<'a> { + Null, + Bool(bool), + // As written, so no digit is lost. + Number(&'a str), + Text(Cow<'a, str>), + // An object or array, as written. + Json(&'a str), +} + +pub fn json_cell(raw: &RawValue) -> JsonCell<'_> { + let text = raw.get(); + match text.as_bytes().first() { + Some(b'n') => JsonCell::Null, + Some(b't') => JsonCell::Bool(true), + Some(b'f') => JsonCell::Bool(false), + Some(b'"') if !text.contains('\\') => JsonCell::Text(Cow::Borrowed(&text[1..text.len() - 1])), + Some(b'"') => JsonCell::Text(Cow::Owned(serde_json::from_str(text).unwrap_or_default())), + Some(b'{' | b'[') => JsonCell::Json(text), + _ => JsonCell::Number(text), + } +} + +// Reads one record at a time, from a top-level array or from JSON Lines. +pub struct JsonReader { + src: Source, + shape: JsonShape, + // JSON Lines takes a record per line, unless its first record spans lines as pretty-printed ones do. + by_line: bool, + line: u64, + ended: bool, + buf: Vec, +} + +impl JsonReader { + pub fn new(inner: R) -> Result { + let mut src = Source::new(inner); + let head = src.peek(3).map_err(|e| e.to_string())?; + if head.starts_with(b"\xff\xfe") || head.starts_with(b"\xfe\xff") { + return Err(NOT_UTF8.into()); + } + if head == b"\xef\xbb\xbf" { + src.discard(3); + } + let mut reader = Self { src, shape: JsonShape::Lines, by_line: false, line: 1, ended: false, buf: Vec::new() }; + match reader.skip_space().map_err(|e| e.to_string())? { + None => return Err("the file is empty".into()), + Some(b'[') => { + reader.src.discard(1); + reader.shape = JsonShape::Array; + } + Some(b'{') => reader.by_line = reader.first_line_holds_a_record().map_err(|e| e.to_string())?, + Some(_) => { + let head = reader.src.peek(4).map_err(|e| e.to_string())?; + let first = String::from_utf8_lossy(head).chars().next().unwrap_or('?'); + return Err(format!("the file isn't JSON: it starts with {first}")); + } + } + Ok(reader) + } + + pub fn shape(&self) -> JsonShape { + self.shape + } + + pub fn bytes_read(&self) -> u64 { + self.src.bytes_read() + } + + pub fn read(&mut self) -> Result>, JsonError> { + let Some(line) = self.next_record()? else { return Ok(None) }; + match serde_json::from_slice::>(&self.buf) { + Ok(Fields(fields)) => Ok(Some(JsonRecord { line, fields })), + Err(err) => Err(JsonError::Row(error_at(line, &err))), + } + } + + // Fills buf with the next record and gives the line it starts on. + fn next_record(&mut self) -> Result, JsonError> { + if self.ended { + return Ok(None); + } + loop { + let next = self.skip_space().map_err(fatal)?; + match (self.shape, next) { + (JsonShape::Array, None) => { + self.ended = true; + return Err(JsonError::Row("the file ends before the JSON array's closing ]".into())); + } + (JsonShape::Lines, None) => return Ok(None), + // Extra and trailing commas are let off. + (JsonShape::Array, Some(b',')) => self.src.discard(1), + (JsonShape::Array, Some(b']')) => { + self.src.discard(1); + self.ended = true; + return match self.skip_space().map_err(fatal)? { + Some(_) => { + Err(JsonError::Row(format!("line {}: text after the JSON array's closing ]", self.line))) + } + None => Ok(None), + }; + } + (JsonShape::Lines, Some(_)) if self.by_line => return self.take_line().map(Some), + (_, Some(_)) => return self.take_value().map(Some), + } + } + } + + fn take_line(&mut self) -> Result { + let start = self.line; + self.buf.clear(); + loop { + let chunk = self.src.peek(CHUNK).map_err(fatal)?; + if chunk.is_empty() { + break; + } + let newline = chunk.iter().position(|&b| b == b'\n'); + let taken = newline.map_or(chunk.len(), |end| end + 1); + self.buf.extend_from_slice(&chunk[..taken]); + self.src.discard(taken); + if self.buf.len() > MAX_RECORD_BYTES { + return Err(runaway(start)); + } + if newline.is_some() { + self.line += 1; + break; + } + } + while self.buf.last().is_some_and(|b| matches!(b, b'\n' | b'\r')) { + self.buf.pop(); + } + Ok(start) + } + + // A value cut off by the end of the file still comes back, for its parse error to name. + fn take_value(&mut self) -> Result { + let start = self.line; + self.buf.clear(); + let mut scan = Scan::default(); + loop { + let chunk = self.src.peek(CHUNK).map_err(fatal)?; + if chunk.is_empty() { + self.ended = true; + return Ok(start); + } + let end = scan.end(chunk); + let taken = end.unwrap_or(chunk.len()); + self.line += newlines(&chunk[..taken]); + self.buf.extend_from_slice(&chunk[..taken]); + self.src.discard(taken); + if self.buf.len() > MAX_RECORD_BYTES { + return Err(runaway(start)); + } + if end.is_some() { + return Ok(start); + } + } + } + + // The next byte that isn't JSON whitespace, left unread. + fn skip_space(&mut self) -> io::Result> { + loop { + let chunk = self.src.peek(CHUNK)?; + if chunk.is_empty() { + return Ok(None); + } + let found = chunk.iter().position(|b| !matches!(b, b' ' | b'\t' | b'\r' | b'\n')); + let skipped = found.unwrap_or(chunk.len()); + let next = found.map(|ix| chunk[ix]); + self.line += newlines(&chunk[..skipped]); + self.src.discard(skipped); + if next.is_some() { + return Ok(next); + } + } + } + + // A first line that's cut off mid-value means the records span lines. + fn first_line_holds_a_record(&mut self) -> io::Result { + let mut want = CHUNK; + loop { + let head = self.src.peek(want)?; + let line = match head.iter().position(|&b| b == b'\n') { + Some(end) => &head[..end], + None if head.len() < want || want >= MAX_RECORD_BYTES => head, + None => { + want *= 2; + continue; + } + }; + return Ok(!serde_json::from_slice::(line).is_err_and(|e| e.is_eof())); + } + } +} + +// Where a top-level value ends: its closing bracket or quote, or for a bare number or word, the next separator. +#[derive(Default)] +struct Scan { + started: bool, + bare: bool, + depth: usize, + in_string: bool, + escaped: bool, +} + +impl Scan { + fn end(&mut self, chunk: &[u8]) -> Option { + for (i, &b) in chunk.iter().enumerate() { + if !self.started { + self.started = true; + match b { + b'"' => self.in_string = true, + b'{' | b'[' => self.depth = 1, + _ => self.bare = true, + } + continue; + } + if self.in_string { + if self.escaped { + self.escaped = false; + } else if b == b'\\' { + self.escaped = true; + } else if b == b'"' { + self.in_string = false; + if self.depth == 0 { + return Some(i + 1); + } + } + } else if self.bare { + if matches!(b, b',' | b']' | b'}' | b' ' | b'\t' | b'\r' | b'\n') { + return Some(i); + } + } else { + match b { + b'"' => self.in_string = true, + b'{' | b'[' => self.depth += 1, + b'}' | b']' => { + self.depth -= 1; + if self.depth == 0 { + return Some(i + 1); + } + } + _ => {} + } + } + } + None + } +} + +fn newlines(bytes: &[u8]) -> u64 { + bytes.iter().filter(|&&b| b == b'\n').count() as u64 +} + +fn fatal(err: io::Error) -> JsonError { + JsonError::Fatal(err.to_string()) +} + +fn runaway(start: u64) -> JsonError { + JsonError::Fatal(format!( + "line {start}: a row runs past {} MB, so the JSON is probably broken there", + MAX_RECORD_BYTES >> 20 + )) +} + +// serde_json counts lines from the record's start, so they move to the file's. +fn error_at(start: u64, err: &serde_json::Error) -> String { + let text = err.to_string(); + let message = text.rfind(" at line ").map_or(text.as_str(), |ix| &text[..ix]); + let line = start + (err.line() as u64).saturating_sub(1); + format!("line {line}: {message}") +} + +struct Fields<'a>(Vec<(Cow<'a, str>, &'a RawValue)>); + +impl<'de> Deserialize<'de> for Fields<'de> { + fn deserialize>(deserializer: D) -> Result { + struct Object; + impl<'de> Visitor<'de> for Object { + type Value = Fields<'de>; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a JSON object") + } + + fn visit_map>(self, mut map: M) -> Result { + let mut fields = Vec::with_capacity(map.size_hint().unwrap_or(0)); + while let Some(Key(key)) = map.next_key()? { + fields.push((key, map.next_value()?)); + } + Ok(Fields(fields)) + } + } + deserializer.deserialize_map(Object) + } +} + +// Borrowed unless the key has escapes. +struct Key<'a>(Cow<'a, str>); + +impl<'de> Deserialize<'de> for Key<'de> { + fn deserialize>(deserializer: D) -> Result { + struct Name; + impl<'de> Visitor<'de> for Name { + type Value = Key<'de>; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a key") + } + + fn visit_borrowed_str(self, v: &'de str) -> Result { + Ok(Key(Cow::Borrowed(v))) + } + + fn visit_str(self, v: &str) -> Result { + Ok(Key(Cow::Owned(v.to_string()))) + } + + fn visit_string(self, v: String) -> Result { + Ok(Key(Cow::Owned(v))) + } + } + deserializer.deserialize_str(Name) + } +} + +#[derive(Clone, Copy)] +struct Kinds { + int: bool, + float: bool, + boolean: bool, + json: bool, + text: bool, + // Over the strings that aren't blank. + all_dates: bool, + all_timestamps: bool, +} + +impl Default for Kinds { + fn default() -> Self { + Self { + int: false, + float: false, + boolean: false, + json: false, + text: false, + all_dates: true, + all_timestamps: true, + } + } +} + +impl Kinds { + fn add(&mut self, cell: &JsonCell<'_>) { + match cell { + JsonCell::Null => {} + JsonCell::Bool(_) => self.boolean = true, + JsonCell::Number(n) if is_integer(n) => self.int = true, + JsonCell::Number(_) => self.float = true, + JsonCell::Json(_) => self.json = true, + JsonCell::Text(s) => { + let s = s.trim(); + if !s.is_empty() { + self.text = true; + self.all_dates &= matches_date(s); + self.all_timestamps &= matches_timestamp(s); + } + } + } + } + + // A string never reads as a number, so "007" stays text. + fn inferred(&self) -> &'static str { + let numbers = self.int || self.float; + match (self.json, numbers, self.boolean, self.text) { + (true, ..) => INFER_JSON, + (false, true, false, false) if self.float => INFER_FLOAT, + (false, true, false, false) => INFER_INT, + (false, false, true, false) => INFER_BOOL, + (false, false, false, true) if self.all_dates => INFER_DATE, + (false, false, false, true) if self.all_timestamps => INFER_TIMESTAMP, + _ => INFER_TEXT, + } + } +} + +// Whole numbers that fit an i64, as CSV infers them. +fn is_integer(n: &str) -> bool { + !n.contains(['.', 'e', 'E']) && n.parse::().is_ok() +} + +// Nested values go on one line. +fn shown(cell: &JsonCell<'_>) -> String { + match cell { + JsonCell::Null => String::new(), + JsonCell::Bool(b) => b.to_string(), + JsonCell::Number(n) => n.to_string(), + JsonCell::Text(s) => s.to_string(), + JsonCell::Json(raw) => { + serde_json::from_str::(raw).map_or_else(|_| raw.to_string(), |value| value.to_string()) + } + } +} + +pub fn preview_json(path: &Path, driver: &DriverType) -> Result { + if path.as_os_str().is_empty() { + return Err("no file selected".into()); + } + let file = File::open(path).map_err(|e| open_error(path, &e))?; + let total_bytes = file.metadata().map(|m| m.len()).unwrap_or(0); + let mut reader = JsonReader::new(file)?; + let mut preview = scan_preview(&mut reader, total_bytes <= MAX_ROW_COUNT_BYTES, driver)?; + preview.total_bytes = total_bytes; + Ok(preview) +} + +// Reads every row when `whole`, else the first SAMPLE_ROWS. +fn scan_preview( + reader: &mut JsonReader, + whole: bool, + driver: &DriverType, +) -> Result { + let mut keys: Vec = Vec::new(); + let mut index: HashMap = HashMap::new(); + let mut kinds: Vec = Vec::new(); + let mut rows: Vec> = Vec::new(); + let (mut good, mut truncated, mut first_error) = (0u64, false, None); + loop { + if !whole && good as usize >= SAMPLE_ROWS { + truncated |= !matches!(reader.read(), Ok(None)); + break; + } + match reader.read() { + Ok(Some(record)) => { + good += 1; + let mut row = (rows.len() < PREVIEW_ROW_LIMIT).then(Vec::new); + truncated |= row.is_none(); + for (key, raw) in &record.fields { + let ix = match index.get(key.as_ref()) { + Some(&ix) => ix, + None => { + index.insert(key.to_string(), keys.len()); + keys.push(key.to_string()); + kinds.push(Kinds::default()); + keys.len() - 1 + } + }; + let cell = json_cell(raw); + kinds[ix].add(&cell); + if let Some(row) = row.as_mut() { + if row.len() <= ix { + row.resize(ix + 1, String::new()); + } + row[ix] = shown(&cell); + } + } + rows.extend(row); + } + Ok(None) => break, + Err(JsonError::Row(error)) => { + first_error.get_or_insert(error); + } + Err(JsonError::Fatal(error)) => return Err(error), + } + } + if good == 0 { + return Err(first_error.unwrap_or_else(|| "the file has no rows".into())); + } + if keys.is_empty() { + return Err("the file has no columns".into()); + } + for row in &mut rows { + row.resize(keys.len(), String::new()); + } + let inferred: Vec = kinds.iter().map(|kinds| kinds.inferred().to_string()).collect(); + let sql_types = inferred.iter().map(|t| sql_type_for(driver, t).to_string()).collect(); + Ok(ImportPreview { + columns: unique_column_names(&keys), + rows, + inferred_types: inferred, + sql_types, + truncated, + total_rows: if whole { good } else { 0 }, + json_shape: Some(reader.shape()), + keys, + sampled: !whole, + ..Default::default() + }) +} + +// Rows that read. 0 when the file is too big to read twice or breaks off. +// Always rewinds the file. +pub fn count_json_rows(file: &mut File, total_bytes: u64) -> u64 { + let counted = (|| { + if total_bytes > MAX_ROW_COUNT_BYTES { + return None; + } + file.seek(SeekFrom::Start(0)).ok()?; + let mut reader = JsonReader::new(&mut *file).ok()?; + let mut rows = 0; + loop { + match reader.read() { + Ok(Some(_)) => rows += 1, + Ok(None) => return Some(rows), + Err(JsonError::Row(_)) => {} + Err(JsonError::Fatal(_)) => return None, + } + } + })(); + let _ = file.seek(SeekFrom::Start(0)); + counted.unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shown(input: &str) -> Vec { + let mut reader = JsonReader::new(input.as_bytes()).unwrap(); + let mut out = Vec::new(); + loop { + match reader.read() { + Ok(Some(record)) => { + let fields: Vec = record.fields.iter().map(|(k, v)| format!("{k}={}", v.get())).collect(); + out.push(format!("{}: {}", record.line, fields.join(" "))); + } + Ok(None) => return out, + Err(JsonError::Row(error)) => out.push(format!("skip {error}")), + Err(JsonError::Fatal(error)) => { + out.push(format!("stop {error}")); + return out; + } + } + } + } + + fn shape(input: &str) -> JsonShape { + JsonReader::new(input.as_bytes()).unwrap().shape() + } + + #[test] + fn reads_an_array_of_objects() { + let input = "[{\"a\":1,\"b\":\"x\"},\n {\"a\":2}]"; + assert_eq!(shown(input), ["1: a=1 b=\"x\"", "2: a=2"]); + assert_eq!(shape(input), JsonShape::Array); + assert_eq!(shown("[]"), Vec::::new()); + assert_eq!(shown("[{\"a\":1},]"), ["1: a=1"], "a trailing comma is let off"); + } + + #[test] + fn reads_json_lines_and_skips_blank_lines() { + let input = "{\"a\":1}\n\n {\"a\":2}\r\n"; + assert_eq!(shown(input), ["1: a=1", "3: a=2"]); + assert_eq!(shape(input), JsonShape::Lines); + } + + // What jq prints: whole objects back to back, each over several lines. + #[test] + fn reads_pretty_printed_objects_back_to_back() { + assert_eq!(shown("{\n \"a\": 1\n}\n{\n \"a\": 2\n}\n"), ["1: a=1", "4: a=2"]); + assert_eq!(shown("{\"a\":\n1}"), ["1: a=1"]); + } + + #[test] + fn strips_a_bom() { + assert_eq!(shown("\u{feff}[{\"a\":1}]"), ["1: a=1"]); + assert_eq!(shown("\u{feff}{\"a\":1}"), ["1: a=1"]); + } + + #[test] + fn a_bad_row_is_skipped_and_the_rest_still_read() { + assert_eq!(shown("[{\"a\":1},\n{\"a\":tru},\n{\"a\":3}]"), ["1: a=1", "skip line 2: expected ident", "3: a=3"]); + assert_eq!(shown("{\"a\":1}\n{\"a\":}\n{\"a\":3}\n"), ["1: a=1", "skip line 2: expected value", "3: a=3"]); + } + + #[test] + fn a_cut_off_line_in_json_lines_loses_only_that_line() { + assert_eq!( + shown("{\"a\":1}\n{\"a\":2\n{\"a\":3}\n"), + ["1: a=1", "skip line 2: EOF while parsing an object", "3: a=3"] + ); + } + + #[test] + fn a_row_that_isnt_an_object_is_skipped() { + assert_eq!( + shown("[{\"a\":1}, 5, \"x\", [1], null]"), + [ + "1: a=1", + "skip line 1: invalid type: integer `5`, expected a JSON object", + "skip line 1: invalid type: string \"x\", expected a JSON object", + "skip line 1: invalid type: sequence, expected a JSON object", + "skip line 1: invalid type: null, expected a JSON object", + ] + ); + } + + #[test] + fn an_array_the_file_never_closes_is_reported_once_at_the_end() { + assert_eq!( + shown("[{\"a\":1},\n{\"a\":2}\n"), + ["1: a=1", "2: a=2", "skip the file ends before the JSON array's closing ]"] + ); + assert_eq!(shown("[{\"a\":1},{\"a\":"), ["1: a=1", "skip line 1: EOF while parsing a value"]); + } + + #[test] + fn text_after_the_array_is_reported() { + assert_eq!(shown("[{\"a\":1}]\nx"), ["1: a=1", "skip line 2: text after the JSON array's closing ]"]); + assert_eq!(shown("[{\"a\":1}]\n\n"), ["1: a=1"]); + } + + #[test] + fn a_row_that_never_ends_stops_the_read() { + let input = format!("[{{\"a\":1}},\n{{\"a\":\"{}", "x".repeat(MAX_RECORD_BYTES + 10)); + let got = shown(&input); + assert_eq!(got[0], "1: a=1"); + assert!(got[1].starts_with("stop line 2: a row runs past"), "{got:?}"); + } + + #[test] + fn values_keep_their_text() { + assert_eq!( + shown("[{\"n\":12345678901234567890123,\"f\":0.10,\"e\":-1E+3,\"o\":{\"k\": [1, 2]}}]"), + ["1: n=12345678901234567890123 f=0.10 e=-1E+3 o={\"k\": [1, 2]}"] + ); + } + + #[test] + fn repeated_keys_are_all_kept_in_order() { + assert_eq!(shown("{\"a\":1,\"a\":2}"), ["1: a=1 a=2"]); + } + + #[test] + fn cells_by_kind() { + let raw = |s: &str| serde_json::from_str::>(s).unwrap(); + assert_eq!(json_cell(&raw("null")), JsonCell::Null); + assert_eq!(json_cell(&raw("true")), JsonCell::Bool(true)); + assert_eq!(json_cell(&raw("false")), JsonCell::Bool(false)); + assert_eq!(json_cell(&raw("-1.50")), JsonCell::Number("-1.50")); + assert_eq!(json_cell(&raw(r#""a\"b\\cé""#)), JsonCell::Text("a\"b\\c\u{e9}".into())); + assert!(matches!(json_cell(&raw(r#""plain""#)), JsonCell::Text(Cow::Borrowed("plain")))); + assert_eq!(json_cell(&raw("[1, {\"a\": null}]")), JsonCell::Json("[1, {\"a\": null}]")); + } + + #[test] + fn files_that_arent_json_are_refused() { + let error = |input: &[u8]| JsonReader::new(input).err().unwrap_or_default(); + assert_eq!(error(b"name,age\n"), "the file isn't JSON: it starts with n"); + assert_eq!(error(b" \n "), "the file is empty"); + assert_eq!(error(b"\xff\xfe[\x00"), "the file isn't UTF-8 text. Save it as UTF-8 and import it again."); + } + + fn preview(content: &str) -> Result { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("rows.json"); + std::fs::write(&path, content).unwrap(); + preview_json(&path, &DriverType::Postgres) + } + + #[test] + fn previews_keys_in_the_order_they_first_appear() { + let content = "{\"id\":1,\"name\":\"ann\"}\n\ + {\"id\":2,\"tags\":[\"x\"],\"when\":\"2026-01-02\"}\n\ + {\"id\":3,\"score\":1.5,\"ok\":true,\"when\":\"2026-02-03\",\"name\":null}\n"; + let preview = preview(content).unwrap(); + assert_eq!(preview.columns, ["id", "name", "tags", "when", "score", "ok"]); + assert_eq!(preview.keys, preview.columns); + assert_eq!(preview.inferred_types, ["int", "text", "json", "date", "float", "bool"]); + assert_eq!(preview.sql_types, ["bigint", "text", "jsonb", "date", "double precision", "boolean"]); + assert_eq!( + preview.rows, + [ + vec!["1", "ann", "", "", "", ""], + vec!["2", "", "[\"x\"]", "2026-01-02", "", ""], + vec!["3", "", "", "2026-02-03", "1.5", "true"], + ] + ); + assert_eq!((preview.json_shape, preview.total_rows, preview.truncated), (Some(JsonShape::Lines), 3, false)); + assert!(!preview.sampled); + } + + #[test] + fn inferred_types_follow_the_json_kinds() { + let types = |rows: &str| preview(rows).unwrap().inferred_types; + assert_eq!(types(r#"[{"zip":"007","n":"1","b":"true"}]"#), ["text", "text", "text"], "strings stay strings"); + assert_eq!(types(r#"[{"a":1,"b":{"x":1}},{"a":"x","b":2}]"#), ["text", "json"]); + assert_eq!(types(r#"[{"a":1,"b":true},{"a":2.5,"b":null}]"#), ["float", "bool"]); + assert_eq!(types(r#"[{"a":null,"b":""},{"a":null,"b":"2026-01-02 10:00:00"}]"#), ["text", "timestamp"]); + assert_eq!(types(r#"[{"big":123456789012345678901234}]"#), ["float"], "past i64, as CSV infers it"); + } + + #[test] + fn nested_values_preview_on_one_line_and_a_repeated_key_keeps_its_last_value() { + let preview = preview("[{\"o\": {\n \"k\": 1\n}, \"a\": 1, \"a\": 2}]").unwrap(); + assert_eq!(preview.columns, ["o", "a"]); + assert_eq!(preview.rows, [vec!["{\"k\":1}", "2"]]); + assert_eq!(preview.json_shape, Some(JsonShape::Array)); + } + + #[test] + fn blank_and_clashing_keys_get_column_names_of_their_own() { + let preview = preview(r#"{"": 1, "a": 2, "A": 3}"#).unwrap(); + assert_eq!(preview.keys, ["", "a", "A"]); + assert_eq!(preview.columns, ["col1", "a", "A_2"]); + } + + #[test] + fn a_file_without_good_rows_says_why() { + assert_eq!(preview("[1, 2]").unwrap_err(), "line 1: invalid type: integer `1`, expected a JSON object"); + assert_eq!(preview("[]").unwrap_err(), "the file has no rows"); + assert_eq!(preview("[{}, {}]").unwrap_err(), "the file has no columns"); + } + + #[test] + fn bad_rows_are_left_out_of_the_preview_and_the_count() { + let preview = preview("{\"a\":1}\n{\"a\":}\n{\"a\":3}\n").unwrap(); + assert_eq!((preview.rows.len(), preview.total_rows), (2, 2)); + } + + #[test] + fn a_file_too_big_to_read_twice_takes_its_columns_from_a_sample() { + let mut rows: String = (0..SAMPLE_ROWS).map(|i| format!("{{\"id\":{i}}}\n")).collect(); + rows.push_str("{\"id\":1,\"late\":true}\n"); + let mut reader = JsonReader::new(rows.as_bytes()).unwrap(); + let preview = scan_preview(&mut reader, false, &DriverType::Postgres).unwrap(); + assert_eq!(preview.columns, ["id"]); + assert_eq!((preview.sampled, preview.total_rows, preview.truncated), (true, 0, true)); + assert_eq!(preview.rows.len(), crate::csv_import::PREVIEW_ROW_LIMIT); + } + + #[test] + fn counts_the_rows_that_read() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("count.jsonl"); + std::fs::write(&path, "{\"a\":1}\n{\"a\":}\n{\"a\":3}\n").unwrap(); + let mut file = File::open(&path).unwrap(); + let len = file.metadata().unwrap().len(); + assert_eq!(count_json_rows(&mut file, len), 2); + let mut first = String::new(); + file.read_to_string(&mut first).unwrap(); + assert!(first.starts_with("{\"a\":1}"), "the count rewinds the file"); + assert_eq!(count_json_rows(&mut file, crate::csv_import::MAX_ROW_COUNT_BYTES + 1), 0); + } +} diff --git a/crates/barsql-io/src/lib.rs b/crates/barsql-io/src/lib.rs index 8d59e90..6e6d998 100644 --- a/crates/barsql-io/src/lib.rs +++ b/crates/barsql-io/src/lib.rs @@ -1,8 +1,10 @@ pub mod array_literal; pub mod csv; pub mod csv_import; +pub mod detect; pub mod export; pub mod format; +pub mod json_import; pub mod row_json; mod time_layouts; pub mod write; @@ -10,9 +12,11 @@ pub mod write; pub use array_literal::{ArrayKind, array_json, array_kind}; pub use csv::{CsvField, CsvReader, csv_values}; pub use csv_import::{CsvOptions, ImportPreview, count_rows, infer_column_type, new_reader, preview_file}; +pub use detect::{FileFormat, detect_format}; pub use export::{ EXPORT_FORMATS, ExportChunk, ExportFormat, Exporter, export_to_string, is_space, restringify_json, sql_literal, }; pub use format::{format_query, format_sql}; +pub use json_import::{JsonCell, JsonError, JsonReader, JsonShape, count_json_rows, json_cell, preview_json}; pub use row_json::{RowField, StagedCells, flag, match_ranges, row_fields, row_json, shown_cell, typed}; pub use write::{WriteOutcome, write_chunks}; diff --git a/crates/barsql-sql/src/dialect.rs b/crates/barsql-sql/src/dialect.rs index 0c8accd..70cf07d 100644 --- a/crates/barsql-sql/src/dialect.rs +++ b/crates/barsql-sql/src/dialect.rs @@ -46,6 +46,7 @@ pub struct ImportTypes { pub date: &'static str, pub timestamp: &'static str, pub text: &'static str, + pub json: &'static str, } // How a dialect writes SQL. Every field is spelled out for every dialect, so a new one is a checklist the compiler @@ -83,6 +84,7 @@ const ANSI_TYPES: ImportTypes = ImportTypes { date: "date", timestamp: "timestamp", text: "text", + json: "jsonb", }; pub static POSTGRES: Dialect = Dialect { @@ -120,6 +122,7 @@ pub static MYSQL: Dialect = Dialect { date: "DATE", timestamp: "DATETIME", text: "TEXT", + json: "JSON", }, max_bind_params: Some(65535), row_edits: true, @@ -147,6 +150,7 @@ pub static SQLITE: Dialect = Dialect { date: "TEXT", timestamp: "TEXT", text: "TEXT", + json: "TEXT", }, max_bind_params: Some(32766), row_edits: true, @@ -174,6 +178,7 @@ pub static TSQL: Dialect = Dialect { date: "DATE", timestamp: "DATETIME2", text: "NVARCHAR(MAX)", + json: "NVARCHAR(MAX)", }, // 2100 per request, one of which tiberius keeps for the statement text. max_bind_params: Some(2099), @@ -204,6 +209,7 @@ pub static CLICKHOUSE: Dialect = Dialect { date: "Nullable(Date32)", timestamp: "Nullable(DateTime64(6))", text: "Nullable(String)", + json: "Nullable(String)", }, max_bind_params: None, row_edits: false, diff --git a/crates/barsql-sql/src/dml.rs b/crates/barsql-sql/src/dml.rs index 73fcb0a..b59a28e 100644 --- a/crates/barsql-sql/src/dml.rs +++ b/crates/barsql-sql/src/dml.rs @@ -317,6 +317,7 @@ pub const IMPORT_FLOAT: &str = "float"; pub const IMPORT_DATE: &str = "date"; pub const IMPORT_TIMESTAMP: &str = "timestamp"; pub const IMPORT_TEXT: &str = "text"; +pub const IMPORT_JSON: &str = "json"; pub fn sql_type_for(driver: &DriverType, import_type: &str) -> &'static str { let types = &Dialect::for_driver(driver).import_types; @@ -326,6 +327,7 @@ pub fn sql_type_for(driver: &DriverType, import_type: &str) -> &'static str { IMPORT_FLOAT => types.float, IMPORT_DATE => types.date, IMPORT_TIMESTAMP => types.timestamp, + IMPORT_JSON => types.json, _ => types.text, } } @@ -643,6 +645,12 @@ mod tests { (DriverType::Turso, IMPORT_FLOAT, "REAL"), (DriverType::SqlServer, IMPORT_TIMESTAMP, "DATETIME2"), (DriverType::ClickHouse, IMPORT_INT, "Nullable(Int64)"), + (DriverType::Postgres, IMPORT_JSON, "jsonb"), + (DriverType::MySql, IMPORT_JSON, "JSON"), + (DriverType::Sqlite, IMPORT_JSON, "TEXT"), + (DriverType::Turso, IMPORT_JSON, "TEXT"), + (DriverType::SqlServer, IMPORT_JSON, "NVARCHAR(MAX)"), + (DriverType::ClickHouse, IMPORT_JSON, "Nullable(String)"), ]; for (driver, t, want) in cases { assert_eq!(sql_type_for(&driver, t), want, "{driver} {t}"); diff --git a/crates/barsql-ui/locales/bg.json b/crates/barsql-ui/locales/bg.json index e7bd05d..c13160c 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -486,6 +486,47 @@ "description": "Всяка стойност влиза в заявката като SQL, затова поставете текста в кавички: 'Ann'. Празна стойност се изпълнява като NULL." }, "import": { + "runDeleting": "Изтрий редовете и импортирай", + "kindJSON": "JSON", + "stepFile": "Файл", + "stepPreview": "Преглед", + "stepColumns": "Колони", + "stepImport": "Импорт", + "dropTitle": "Пуснете тук CSV, JSON или SQL файл", + "dropHint": "Текст с разделители, JSON масиви и JSON Lines или SQL скрипт", + "change": "Смени", + "readAs": "Чети като", + "jsonArray": "JSON масив", + "jsonLines": "JSON Lines", + "scriptRuns": "Изпълнява скрипта команда по команда в {{connection}}.", + "into": "Цел", + "newTableHint": "Създава се с типовете от стъпка Колони. Всички колони допускат NULL.", + "keys_one": "{{keys}} ключ", + "keys_other": "{{keys}} ключа", + "sampled": "Колоните и типовете идват от първите {{rows}} реда.", + "mapped": "{{mapped}} от {{total}} свързани", + "sample": "Примери", + "next": "Напред", + "back": "Назад", + "stopOnErrorHint": "Каквото е заредено преди грешката, остава.", + "summaryFile": "Файл", + "summaryInto": "Цел", + "summaryRows": "Редове", + "summaryColumns": "Колони", + "summaryRunsOn": "Изпълнява се в", + "summaryNewTable": "нова таблица", + "summaryRowsUncounted": "Броят се при зареждането", + "summaryEmptied": "Текущите ѝ редове се изтриват първо. Това не може да бъде отменено.", + "resultRows_one": "Импортиран е {{rows}} ред", + "resultRows_other": "Импортирани са {{rows}} реда", + "resultStatements_one": "Изпълнена е {{statements}} команда", + "resultStatements_other": "Изпълнени са {{statements}} команди", + "skipped_one": "{{skipped}} пропуснат", + "skipped_other": "{{skipped}} пропуснати", + "ignoredKeys": "Не са заредени, защото прегледът не е видял тези ключове: {{keys}}", + "openTable": "Отвори таблицата", + "again": "Импортирай друг файл", + "type": { "json": "JSON" }, "runRows": "Импортиране на {{rows}} ред", "runRows_other": "Импортиране на {{rows}} реда", "notUtf8": "Този файл не е UTF-8 текст, затова знаците, които не могат да се прочетат, ще се импортират като �. Запазете го като UTF-8 и го изберете отново.", diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index 3f8cdef..81eee49 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -487,6 +487,47 @@ "description": "Jeder Wert wird als SQL in die Abfrage eingesetzt, Text also in Anführungszeichen: 'Ann'. Ein leerer Wert läuft als NULL." }, "import": { + "runDeleting": "Zeilen löschen und importieren", + "kindJSON": "JSON", + "stepFile": "Datei", + "stepPreview": "Vorschau", + "stepColumns": "Spalten", + "stepImport": "Import", + "dropTitle": "CSV-, JSON- oder SQL-Datei hier ablegen", + "dropHint": "Text mit Trennzeichen, JSON-Arrays und JSON Lines oder ein SQL-Skript", + "change": "Ändern", + "readAs": "Lesen als", + "jsonArray": "JSON-Array", + "jsonLines": "JSON Lines", + "scriptRuns": "Führt das Skript Anweisung für Anweisung auf {{connection}} aus.", + "into": "Ziel", + "newTableHint": "Wird mit den Typen aus dem Schritt Spalten angelegt. Alle Spalten sind nullable.", + "keys_one": "{{keys}} Schlüssel", + "keys_other": "{{keys}} Schlüssel", + "sampled": "Spalten und Typen stammen aus den ersten {{rows}} Zeilen.", + "mapped": "{{mapped}} von {{total}} zugeordnet", + "sample": "Beispiele", + "next": "Weiter", + "back": "Zurück", + "stopOnErrorHint": "Was vor dem Fehler geladen wurde, bleibt erhalten.", + "summaryFile": "Datei", + "summaryInto": "Ziel", + "summaryRows": "Zeilen", + "summaryColumns": "Spalten", + "summaryRunsOn": "Läuft auf", + "summaryNewTable": "neue Tabelle", + "summaryRowsUncounted": "Werden beim Laden gezählt", + "summaryEmptied": "Ihre vorhandenen Zeilen werden zuerst gelöscht. Das kann nicht rückgängig gemacht werden.", + "resultRows_one": "{{rows}} Zeile importiert", + "resultRows_other": "{{rows}} Zeilen importiert", + "resultStatements_one": "{{statements}} Anweisung ausgeführt", + "resultStatements_other": "{{statements}} Anweisungen ausgeführt", + "skipped_one": "{{skipped}} übersprungen", + "skipped_other": "{{skipped}} übersprungen", + "ignoredKeys": "Nicht geladen, da die Vorschau diese Schlüssel nie gesehen hat: {{keys}}", + "openTable": "Tabelle öffnen", + "again": "Weitere Datei importieren", + "type": { "json": "JSON" }, "runRows": "{{rows}} Zeile importieren", "runRows_other": "{{rows}} Zeilen importieren", "notUtf8": "Diese Datei ist kein UTF-8-Text, daher werden Zeichen, die sich nicht lesen lassen, als � importiert. Speichern Sie sie als UTF-8 und wählen Sie sie erneut.", diff --git a/crates/barsql-ui/locales/en.json b/crates/barsql-ui/locales/en.json index 621191e..898492a 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -512,6 +512,47 @@ "description": "Each value goes into the query as SQL, so put text in quotes: 'Ann'. An empty value runs as NULL." }, "import": { + "runDeleting": "Delete rows and import", + "kindJSON": "JSON", + "stepFile": "File", + "stepPreview": "Preview", + "stepColumns": "Columns", + "stepImport": "Import", + "dropTitle": "Drop a CSV, JSON or SQL file here", + "dropHint": "Delimited text, JSON arrays and JSON Lines, or a SQL script", + "change": "Change", + "readAs": "Read as", + "jsonArray": "JSON array", + "jsonLines": "JSON Lines", + "scriptRuns": "Runs the script statement by statement on {{connection}}.", + "into": "Into", + "newTableHint": "Created with the types on the Columns step. Every column is nullable.", + "keys_one": "{{keys}} key", + "keys_other": "{{keys}} keys", + "sampled": "Columns and types come from the first {{rows}} rows.", + "mapped": "{{mapped}} of {{total}} mapped", + "sample": "Samples", + "next": "Next", + "back": "Back", + "stopOnErrorHint": "Whatever loaded before the error stays loaded.", + "summaryFile": "File", + "summaryInto": "Into", + "summaryRows": "Rows", + "summaryColumns": "Columns", + "summaryRunsOn": "Runs on", + "summaryNewTable": "new table", + "summaryRowsUncounted": "Counted as they load", + "summaryEmptied": "Its current rows are deleted first. This can't be undone.", + "resultRows_one": "Imported {{rows}} row", + "resultRows_other": "Imported {{rows}} rows", + "resultStatements_one": "Ran {{statements}} statement", + "resultStatements_other": "Ran {{statements}} statements", + "skipped_one": "{{skipped}} skipped", + "skipped_other": "{{skipped}} skipped", + "ignoredKeys": "Not loaded, as the preview never saw these keys: {{keys}}", + "openTable": "Open table", + "again": "Import another file", + "type": { "json": "JSON" }, "runRows": "Import {{rows}} row", "runRows_other": "Import {{rows}} rows", "notUtf8": "This file isn't UTF-8 text, so characters it can't read will import as �. Save it as UTF-8 and choose it again.", diff --git a/crates/barsql-ui/locales/es.json b/crates/barsql-ui/locales/es.json index fe4f015..b6d0ac7 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -496,6 +496,47 @@ "description": "Cada valor se incluye en la consulta como SQL, así que escribe el texto entre comillas: 'Ana'. Un valor vacío se ejecuta como NULL." }, "import": { + "runDeleting": "Eliminar filas e importar", + "kindJSON": "JSON", + "stepFile": "Archivo", + "stepPreview": "Vista previa", + "stepColumns": "Columnas", + "stepImport": "Importar", + "dropTitle": "Suelta aquí un archivo CSV, JSON o SQL", + "dropHint": "Texto delimitado, arrays JSON y JSON Lines, o un script SQL", + "change": "Cambiar", + "readAs": "Leer como", + "jsonArray": "Array JSON", + "jsonLines": "JSON Lines", + "scriptRuns": "Ejecuta el script sentencia a sentencia en {{connection}}.", + "into": "Destino", + "newTableHint": "Se crea con los tipos del paso Columnas. Todas las columnas admiten NULL.", + "keys_one": "{{keys}} clave", + "keys_other": "{{keys}} claves", + "sampled": "Las columnas y los tipos salen de las primeras {{rows}} filas.", + "mapped": "{{mapped}} de {{total}} asignadas", + "sample": "Ejemplos", + "next": "Siguiente", + "back": "Atrás", + "stopOnErrorHint": "Lo que se cargó antes del error se conserva.", + "summaryFile": "Archivo", + "summaryInto": "Destino", + "summaryRows": "Filas", + "summaryColumns": "Columnas", + "summaryRunsOn": "Se ejecuta en", + "summaryNewTable": "tabla nueva", + "summaryRowsUncounted": "Se cuentan al cargarlas", + "summaryEmptied": "Antes se eliminan sus filas actuales. No se puede deshacer.", + "resultRows_one": "{{rows}} fila importada", + "resultRows_other": "{{rows}} filas importadas", + "resultStatements_one": "{{statements}} sentencia ejecutada", + "resultStatements_other": "{{statements}} sentencias ejecutadas", + "skipped_one": "{{skipped}} omitida", + "skipped_other": "{{skipped}} omitidas", + "ignoredKeys": "No se cargaron porque la vista previa nunca vio estas claves: {{keys}}", + "openTable": "Abrir tabla", + "again": "Importar otro archivo", + "type": { "json": "JSON" }, "runRows": "Importar {{rows}} fila", "runRows_other": "Importar {{rows}} filas", "notUtf8": "Este archivo no es texto UTF-8, así que los caracteres que no se puedan leer se importarán como �. Guárdalo como UTF-8 y vuelve a elegirlo.", diff --git a/crates/barsql-ui/src/file_dialogs.rs b/crates/barsql-ui/src/file_dialogs.rs index 3d95a00..b7431db 100644 --- a/crates/barsql-ui/src/file_dialogs.rs +++ b/crates/barsql-ui/src/file_dialogs.rs @@ -76,19 +76,16 @@ pub fn pick_extension_files(cx: &App) -> Task> { }) } -pub fn pick_import_file(kind: crate::import_dialog::Kind, cx: &App) -> Task> { +// The dialog reads the format from the file, so one filter covers them all. +pub fn pick_import_file(cx: &App) -> Task> { if let Some(stub) = stubbed(cx) { return stub; } let dialog = rfd::AsyncFileDialog::new().set_title("Select file to import"); #[cfg(not(target_os = "macos"))] - let dialog = match kind { - crate::import_dialog::Kind::Sql => dialog.add_filter("SQL script", &["sql"]), - crate::import_dialog::Kind::Csv => dialog.add_filter("Delimited text", &["csv", "tsv", "txt"]), - } - .add_filter("All Files", &["*"]); - #[cfg(target_os = "macos")] - let _ = kind; + let dialog = dialog + .add_filter("Data files", &["csv", "tsv", "txt", "json", "jsonl", "ndjson", "sql"]) + .add_filter("All Files", &["*"]); run(dialog.pick_file(), cx) } diff --git a/crates/barsql-ui/src/import_dialog.rs b/crates/barsql-ui/src/import_dialog.rs index 57a018a..b886cac 100644 --- a/crates/barsql-ui/src/import_dialog.rs +++ b/crates/barsql-ui/src/import_dialog.rs @@ -1,41 +1,40 @@ +use std::path::Path; use std::rc::Rc; use std::time::Duration; use barsql_app::{ - CsvImportRequest, CsvOptions, ImportEvent, ImportPreview, ImportProgress, ImportResult, SqlImportRequest, + CsvOptions, FileFormat, ImportEvent, ImportPreview, ImportProgress, ImportResult, JsonShape, SqlImportRequest, + TableFormat, TableImportRequest, detect_format, }; use barsql_core::ConnectionConfig; -use barsql_sql::display_type; -use gpui_kit::assets::IconName as Lucide; use gpui_kit::component::button::{Button, ButtonVariants}; use gpui_kit::component::input::{InputEvent, InputState}; -use gpui_kit::component::menu::{PopupMenu, PopupMenuItem}; -use gpui_kit::component::scroll::ScrollbarAxis; -use gpui_kit::component::tooltip::Tooltip; -use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, Sizable, WindowExt, h_flex, v_flex}; +use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, Sizable, StyledExt, WindowExt, h_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use crate::file_dialogs::{path_text, pick_import_file}; -use crate::form::{self, LargeButton as _, SelectMenu}; -use crate::i18n::{count, t, t_count, t_with}; +use crate::form; +use crate::i18n::{count, t, t_count}; use crate::modal::{self, Modal}; use crate::query_tab::new_tab_id; use crate::schema::Columns; -use crate::scrollbars::HoverScrollbar as _; -use crate::spinner::Spinner; -use crate::tokens::{DIMMED, ICON_XS, RADIUS, TEXT_BASE, TEXT_SM, TEXT_XS}; +use crate::tokens::{ICON_2XS, RADIUS, TEXT_SM, TEXT_XS, TINT, TINT_BORDER}; use crate::{schema, state}; +mod columns_step; +mod file_step; +mod preview_step; +mod run_step; +#[cfg(test)] +mod tests; + const PREVIEW_DEBOUNCE: Duration = Duration::from_millis(200); -const DELIMITERS: [(&str, &str); 5] = [ - ("", "import.delimiterAuto"), - (",", "import.delimiterComma"), - (";", "import.delimiterSemicolon"), - ("\t", "import.delimiterTab"), - ("|", "import.delimiterPipe"), -]; -const COLUMN_TYPES: [&str; 6] = ["text", "int", "float", "bool", "date", "timestamp"]; +// Fixed, so the dialog keeps its size from step to step. The modal caps it at 90% of the window. +const DIALOG_REM: f32 = 44.; +const COLUMN_TYPES: [&str; 7] = ["text", "int", "float", "bool", "date", "timestamp", "json"]; +const TABLE_STEPS: [Step; 4] = [Step::File, Step::Preview, Step::Columns, Step::Import]; +const SCRIPT_STEPS: [Step; 2] = [Step::File, Step::Import]; // What a column's type takes, as far as an import's sampled values go. #[derive(Clone, Copy, PartialEq)] @@ -96,9 +95,22 @@ fn fits(inferred: &str, column_type: &str) -> bool { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Csv, - Sql, +pub(crate) enum Step { + File, + Preview, + Columns, + Import, +} + +impl Step { + fn key(self) -> &'static str { + match self { + Self::File => "import.stepFile", + Self::Preview => "import.stepPreview", + Self::Columns => "import.stepColumns", + Self::Import => "import.stepImport", + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -107,6 +119,16 @@ enum Target { Existing, } +// Takes the schema and table the rows went into. +pub type OpenTable = Rc; + +// What the tree does when rows land and when the result's Open table is pressed. +#[derive(Clone)] +pub struct Hooks { + pub imported: Rc, + pub open: OpenTable, +} + // Drops the extension and turns anything but ASCII letters, digits and _ into _. pub fn table_name_for(path: &str) -> String { let base = path.rsplit(['/', '\\']).next().unwrap_or(path); @@ -117,13 +139,32 @@ pub fn table_name_for(path: &str) -> String { stem.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect() } +fn format_key(format: FileFormat) -> &'static str { + match format { + FileFormat::Csv => "import.kindCSV", + FileFormat::Json => "import.kindJSON", + FileFormat::Sql => "import.kindSQL", + } +} + +fn shape_key(shape: JsonShape) -> &'static str { + match shape { + JsonShape::Array => "import.jsonArray", + JsonShape::Lines => "import.jsonLines", + } +} + // Stopping an import keeps whatever was already loaded. pub struct ImportDialog { connection: ConnectionConfig, schema: String, tables: Vec, - kind: Kind, + step: Step, path: String, + // Detected, or picked in Read as. None until the file is read. + format: Option, + picked_format: bool, + file_size: Option, preview: Option, preview_error: Option, previewing: bool, @@ -135,6 +176,8 @@ pub struct ImportDialog { target: Target, existing: String, new_table: Entity, + // The name the last file suggested, replaced by the next file's unless the user changed it. + suggested: String, truncate: bool, stop_on_error: bool, mapping: Vec>, @@ -146,10 +189,13 @@ pub struct ImportDialog { running: Option>, progress: Option, result: Option, + // The table the last run loaded, for Open table. + loaded_table: Option, error: Option, preview_task: Option>, - on_imported: Rc, + hooks: Hooks, errors_scroll: ScrollHandle, + grid_scroll: ScrollHandle, _subscriptions: Vec, } @@ -159,7 +205,7 @@ impl ImportDialog { schema: String, tables: Vec, table: Option, - on_imported: Rc, + hooks: Hooks, window: &mut Window, cx: &mut Context, ) -> Self { @@ -183,8 +229,11 @@ impl ImportDialog { target: if table.is_some() { Target::Existing } else { Target::New }, existing: table.or_else(|| tables.first().cloned()).unwrap_or_default(), tables, - kind: Kind::Csv, + step: Step::File, path: String::new(), + format: None, + picked_format: false, + file_size: None, preview: None, preview_error: None, previewing: false, @@ -194,6 +243,7 @@ impl ImportDialog { null_literal, skip_rows, new_table, + suggested: String::new(), truncate: false, stop_on_error: false, mapping: Vec::new(), @@ -204,10 +254,12 @@ impl ImportDialog { running: None, progress: None, result: None, + loaded_table: None, error: None, preview_task: None, - on_imported, + hooks, errors_scroll: ScrollHandle::new(), + grid_scroll: ScrollHandle::new(), _subscriptions: subscriptions, }; this.load_target_columns(window, cx); @@ -239,23 +291,68 @@ impl ImportDialog { } } + // Rows into a table, rather than a script. Before a file is read, that's what the dialog sets up. + fn is_table(&self) -> bool { + self.format != Some(FileFormat::Sql) + } + + fn steps(&self) -> &'static [Step] { + if self.is_table() { &TABLE_STEPS } else { &SCRIPT_STEPS } + } + + // Preview shows the read as it goes, so it opens as soon as there's a file. The rest need what it read. + fn reachable(&self, step: Step) -> bool { + match step { + Step::File => true, + Step::Preview => !self.path.is_empty(), + Step::Columns => self.preview.is_some(), + Step::Import => self.preview.is_some() || (!self.is_table() && !self.path.is_empty()), + } + } + + fn next_step(&self) -> Option { + let steps = self.steps(); + let ix = steps.iter().position(|step| *step == self.step)?; + steps.get(ix + 1).copied().filter(|step| self.reachable(*step)) + } + + fn back_step(&self) -> Option { + let steps = self.steps(); + let ix = steps.iter().position(|step| *step == self.step)?; + ix.checked_sub(1).map(|ix| steps[ix]) + } + + fn go(&mut self, step: Step, cx: &mut Context) { + let busy = self.running.is_some() || self.result.is_some(); + if !busy && self.steps().contains(&step) && self.reachable(step) { + self.step = step; + cx.notify(); + } + } + + fn on_last_step(&self) -> bool { + self.steps().last() == Some(&self.step) + } + + // The import empties the table before it loads. + fn deleting(&self) -> bool { + self.is_table() && self.target == Target::Existing && self.truncate + } + + fn next(&mut self, cx: &mut Context) { + if let Some(step) = self.next_step() { + self.go(step, cx); + } + } + fn reset_run(&mut self) { self.progress = None; self.result = None; self.error = None; } - fn set_kind(&mut self, kind: Kind, cx: &mut Context) { - self.kind = kind; - self.path.clear(); - self.preview = None; - self.preview_error = None; - self.reset_run(); - cx.notify(); - } - fn pick(&mut self, window: &mut Window, cx: &mut Context) { - let picked = pick_import_file(self.kind, cx); + let picked = pick_import_file(cx); cx.spawn_in(window, async move |this, cx| { let Some(path) = picked.await else { return }; this.update_in(cx, |this, window, cx| { @@ -268,13 +365,44 @@ impl ImportDialog { .detach(); } + fn dropped(&mut self, paths: &ExternalPaths, window: &mut Window, cx: &mut Context) { + if self.running.is_some() { + return; + } + let Some(path) = paths.paths().first() else { return }; + if let Some(path) = path_text(path, cx) { + self.choose(path, window, cx); + } + } + pub(crate) fn choose(&mut self, path: String, window: &mut Window, cx: &mut Context) { self.reset_run(); + self.file_size = std::fs::metadata(&path).ok().map(|meta| meta.len()); self.path = path; + self.format = None; + self.picked_format = false; + self.preview = None; + self.mapping.clear(); + self.column_types.clear(); + self.step = Step::File; + self.load_preview(window, cx); + cx.notify(); + } + + fn set_format(&mut self, format: FileFormat, window: &mut Window, cx: &mut Context) { + if self.format == Some(format) { + return; + } + self.picked_format = true; + self.format = Some(format); self.preview = None; - if self.kind == Kind::Csv { - self.load_preview(window, cx); + self.mapping.clear(); + self.column_types.clear(); + self.reset_run(); + if !self.steps().contains(&self.step) { + self.step = Step::File; } + self.load_preview(window, cx); cx.notify(); } @@ -283,8 +411,13 @@ impl ImportDialog { self.preview.is_some() } + #[cfg(feature = "snapshot")] + pub(crate) fn show_columns(&mut self, cx: &mut Context) { + self.go(Step::Columns, cx); + } + fn schedule_preview(&mut self, window: &mut Window, cx: &mut Context) { - if self.kind != Kind::Csv || self.path.is_empty() { + if self.format != Some(FileFormat::Csv) || self.path.is_empty() { return; } self.preview_task = Some(cx.spawn_in(window, async move |this, cx| { @@ -293,24 +426,43 @@ impl ImportDialog { })); } - // Same reader and options as the import, so the sample matches what it will read. + // Same readers and options as the import, so the sample matches what it will read. A file not read as a format + // the user picked is detected first. fn load_preview(&mut self, window: &mut Window, cx: &mut Context) { + if self.path.is_empty() { + return; + } self.previewing = true; self.preview_error = None; let bar = state::bar(cx); let (connection, path, options) = (self.connection.id.clone(), self.path.clone(), self.options(cx)); - let load = state::spawn(cx, async move { bar.preview_import_file(&connection, &path, &options) }); + let picked = if self.picked_format { self.format } else { None }; + let load = state::spawn(cx, async move { + let format = picked.unwrap_or_else(|| detect_format(Path::new(&path))); + let preview = match format { + FileFormat::Csv => bar.preview_import_file(&connection, &path, &options).map(Some), + FileFormat::Json => bar.preview_json_file(&connection, &path).map(Some), + FileFormat::Sql => Ok(None), + }; + (format, preview) + }); self.preview_task = Some(cx.spawn_in(window, async move |this, cx| { - let result = load.await; + let loaded = load.await; this.update_in(cx, |this, window, cx| { this.previewing = false; - match result { - Some(Ok(preview)) => this.show_preview(preview, window, cx), - Some(Err(error)) => { - this.preview = None; - this.preview_error = Some(error.message.into()); + if let Some((format, preview)) = loaded { + this.format = Some(format); + match preview { + Ok(Some(preview)) => this.show_preview(preview, window, cx), + Ok(None) => this.preview = None, + Err(error) => { + this.preview = None; + this.preview_error = Some(error.message.into()); + } + } + if !this.steps().contains(&this.step) { + this.step = Step::File; } - None => {} } cx.notify(); }) @@ -330,10 +482,12 @@ impl ImportDialog { .collect(); self.column_types = preview.inferred_types.clone(); self.match_target_columns(window, cx); - if self.new_table.read(cx).value().is_empty() && !preview.columns.is_empty() { - let name = table_name_for(&self.path); - self.new_table.update(cx, |state, cx| state.set_value(name, window, cx)); + let name = table_name_for(&self.path); + let typed = self.new_table.read(cx).value().to_string(); + if typed.is_empty() || typed == self.suggested { + self.new_table.update(cx, |state, cx| state.set_value(name.clone(), window, cx)); } + self.suggested = name; self.preview = Some(preview); } @@ -344,6 +498,11 @@ impl ImportDialog { } } + // Schema-qualified when the connection has schemas. + fn qualified(&self, table: &str) -> String { + if self.schema.is_empty() { table.to_string() } else { format!("{}.{table}", self.schema) } + } + fn set_target(&mut self, target: Target, window: &mut Window, cx: &mut Context) { self.target = target; self.load_target_columns(window, cx); @@ -393,121 +552,62 @@ impl ImportDialog { } } - // Whether column `ix`'s values look like they load where it maps. None when it's skipped, or before the table's - // columns are known. - fn fit(&self, ix: usize, cx: &App) -> Option { - let columns = self.existing_columns()?; - let value = self.mapping.get(ix)?.read(cx).value().trim().to_string(); - let inferred = self.preview.as_ref()?.inferred_types.get(ix)?; - (!value.is_empty()) - .then(|| columns.iter().find(|c| c.name == value).is_some_and(|c| fits(inferred, &c.data_type))) - } - - // Why column `ix` is flagged: the table has no such column, or its values don't look like the column's type. - fn misfit(&self, ix: usize, cx: &App) -> SharedString { - let value = self.mapping.get(ix).map(|input| input.read(cx).value().trim().to_string()).unwrap_or_default(); - let column = self.existing_columns().and_then(|columns| columns.iter().find(|c| c.name == value).cloned()); - let inferred = self.preview.as_ref().and_then(|p| p.inferred_types.get(ix).cloned()).unwrap_or_default(); - match column { - None => t_with(cx, "import.notAColumn", &[("table", &self.existing), ("column", &value)]), - Some(column) => { - let kind = t(cx, &format!("import.type.{inferred}")); - let shown = display_type(self.connection.driver.dialect(), &column.data_type); - t_with(cx, "import.mismatch", &[("kind", &kind), ("type", &shown)]) - } - } - } - - // An existing table's column picker, with a mark for how the values fit. Typed names before its columns load, - // and for a new table, whose columns they name. - fn target_cell(&self, ix: usize, running: bool, window: &mut Window, cx: &mut Context) -> AnyElement { - let Some(input) = self.mapping.get(ix).cloned() else { return div().into_any_element() }; - let Some(columns) = self.existing_columns() else { - return form::input(&input, window, cx).disabled(running).into_any_element(); - }; - let value = input.read(cx).value().trim().to_string(); - let label: SharedString = if value.is_empty() { t(cx, "import.skipColumn") } else { value.clone().into() }; - let dialect = self.connection.driver.dialect(); - let this = cx.entity().downgrade(); - let picker = form::select(("import-target", ix), label, cx) - .debug_selector(move || format!("import-target-{ix}")) - .disabled(running) - .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { - let pick = |name: String| { - let (input, this) = (input.clone(), this.clone()); - move |_: &ClickEvent, window: &mut Window, cx: &mut App| { - input.update(cx, |input, cx| input.set_value(name.clone(), window, cx)); - this.update(cx, |_, cx| cx.notify()).ok(); - } - }; - let skip = PopupMenuItem::new(t(cx, "import.skipColumn")).checked(value.is_empty()); - menu = menu.item(skip.on_click(pick(String::new()))); - for column in columns.iter() { - let label = format!("{} · {}", column.name, display_type(dialect, &column.data_type)); - let item = PopupMenuItem::new(label).checked(column.name == value); - menu = menu.item(item.on_click(pick(column.name.clone()))); - } - menu.scrollable(true) - }); - let theme = cx.theme(); - let mark = self.fit(ix, cx).map(|fits| { - let (icon, color) = - if fits { (IconName::Check, theme.success) } else { (IconName::TriangleAlert, theme.warning) }; - let tip = (!fits).then(|| self.misfit(ix, cx)); - div() - .id(("import-fit", ix)) - .debug_selector(move || format!("import-fit-{ix}")) - .flex_none() - .child(Icon::new(icon).size(ICON_XS).text_color(color)) - .when_some(tip, |el, tip| el.tooltip(move |window, cx| Tooltip::new(tip.clone()).build(window, cx))) - }); - h_flex().gap(rems(0.462)).child(div().flex_1().min_w_0().child(picker)).children(mark).into_any_element() - } - fn mapping_values(&self, cx: &App) -> Vec { self.mapping.iter().map(|input| input.read(cx).value().to_string()).collect() } + fn mapped_count(&self, cx: &App) -> usize { + self.mapping_values(cx).iter().filter(|target| !target.trim().is_empty()).count() + } + fn can_run(&self, cx: &App) -> bool { - if self.running.is_some() || self.path.is_empty() { + if self.running.is_some() || self.previewing || self.path.is_empty() { return false; } - if self.kind == Kind::Sql { - return true; + match self.format { + None => false, + Some(FileFormat::Sql) => true, + Some(_) => self.preview.is_some() && !self.target_table(cx).is_empty() && self.mapped_count(cx) > 0, } - let mapped = self.mapping_values(cx).iter().filter(|m| !m.trim().is_empty()).count(); - self.preview.is_some() && !self.target_table(cx).is_empty() && mapped > 0 } + // Shows the run on the last step, wherever it started. fn run(&mut self, window: &mut Window, cx: &mut Context) { if !self.can_run(cx) { return; } self.reset_run(); + self.step = Step::Import; let id = new_tab_id(); self.import_id = Some(id.clone()); let bar = state::bar(cx); let connection = self.connection.id.clone(); - let start = match self.kind { - Kind::Sql => { - let request = SqlImportRequest { path: self.path.clone(), stop_on_error: self.stop_on_error }; - state::spawn(cx, async move { bar.import_sql(&connection, &id, request).await }) - } - Kind::Csv => { - let request = CsvImportRequest { - path: self.path.clone(), - schema: self.schema.clone(), - table: self.target_table(cx), - create_table: self.target == Target::New, - truncate: self.target == Target::Existing && self.truncate, - options: self.options(cx), - mapping: self.mapping_values(cx), - column_types: self.column_types.clone(), - batch_size: 0, - stop_on_error: self.stop_on_error, - }; - state::spawn(cx, async move { bar.import_csv(&connection, &id, request).await }) - } + let start = if self.is_table() { + let format = match self.format { + Some(FileFormat::Json) => { + TableFormat::Json { keys: self.preview.as_ref().map(|p| p.keys.clone()).unwrap_or_default() } + } + _ => TableFormat::Csv(self.options(cx)), + }; + let table = self.target_table(cx); + self.loaded_table = Some(table.clone()); + let request = TableImportRequest { + path: self.path.clone(), + schema: self.schema.clone(), + table, + create_table: self.target == Target::New, + truncate: self.target == Target::Existing && self.truncate, + format, + mapping: self.mapping_values(cx), + column_types: self.column_types.clone(), + batch_size: 0, + stop_on_error: self.stop_on_error, + }; + state::spawn(cx, async move { bar.import_table(&connection, &id, request).await }) + } else { + self.loaded_table = None; + let request = SqlImportRequest { path: self.path.clone(), stop_on_error: self.stop_on_error }; + state::spawn(cx, async move { bar.import_sql(&connection, &id, request).await }) }; self.running = Some(cx.spawn_in(window, async move |this, cx| { match start.await { @@ -544,7 +644,7 @@ impl ImportDialog { && !result.cancelled && (result.inserted > 0 || result.statements > 0) { - (self.on_imported)(cx); + (self.hooks.imported)(cx); } self.result = done.result; } @@ -552,12 +652,15 @@ impl ImportDialog { cx.notify(); } - // Enter imports, but once an import has finished it closes, so a second press can't import the file twice. + // Enter does what the blue button does. Once an import has finished it closes, so a second press can't import + // the file twice. fn enter(&mut self, window: &mut Window, cx: &mut Context) { if self.result.is_some() || self.error.is_some() { window.close_dialog(cx); - } else { + } else if self.on_last_step() { self.run(window, cx); + } else { + self.next(cx); } } @@ -570,449 +673,213 @@ impl ImportDialog { } } - fn progress_view(&self, cx: &App) -> impl IntoElement { - let p = self.progress.clone().unwrap_or(ImportProgress { - total_bytes: self.preview.as_ref().map_or(0, |p| p.total_bytes as i64), - total_rows: if self.kind == Kind::Csv { - self.preview.as_ref().map_or(0, |p| p.total_rows as i64) - } else { - 0 - }, - ..Default::default() - }); - let n = |value: i64| count(cx, value.max(0) as usize); - let (label, value, max) = match self.kind { - Kind::Sql => ( - t_with(cx, "import.progressStatements", &[("done", &n(p.processed)), ("total", &n(p.total_bytes))]), - p.processed, - p.total_bytes, - ), - Kind::Csv if p.total_rows > 0 => ( - t_with( - cx, - "import.progressRowsOf", - &[("done", &n(p.processed.min(p.total_rows))), ("total", &n(p.total_rows))], - ), - p.processed.min(p.total_rows), - p.total_rows, - ), - Kind::Csv => (t_with(cx, "import.progressRows", &[("rows", &n(p.processed))]), p.bytes_read, p.total_bytes), - }; - form::progress("import-progress", label, if max > 0 { value as f32 / max as f32 } else { 0. }, cx) + fn open_table(&mut self, window: &mut Window, cx: &mut Context) { + let Some(table) = self.loaded_table.clone() else { return }; + (self.hooks.open)(self.schema.clone(), table, window, cx); + window.close_dialog(cx); + } + + // Back to the first step for the next file. A table the import just made is that file's target now. + fn again(&mut self, window: &mut Window, cx: &mut Context) { + let made = self.target == Target::New && self.result.as_ref().is_some_and(|result| result.inserted > 0); + if let Some(table) = self.loaded_table.take().filter(|_| made) { + if !self.tables.contains(&table) { + self.tables.push(table.clone()); + } + self.existing = table; + self.target = Target::Existing; + self.load_target_columns(window, cx); + } + self.path.clear(); + self.format = None; + self.picked_format = false; + self.file_size = None; + self.preview = None; + self.preview_error = None; + self.mapping.clear(); + self.column_types.clear(); + self.reset_run(); + self.step = Step::File; + cx.notify(); } + // `rereads` for the options that change how the file reads. fn checkbox( &self, id: &'static str, key: &str, checked: bool, set: fn(&mut Self, bool), + rereads: bool, cx: &mut Context, ) -> Stateful
{ let running = self.running.is_some(); form::checkbox(id, checked, t(cx, key), running, cx).debug_selector(move || id.into()).when(!running, |el| { el.on_click(cx.listener(move |this, _, window, cx| { set(this, !checked); - this.schedule_preview(window, cx); + if rereads { + this.schedule_preview(window, cx); + } cx.notify(); })) }) } - fn csv_fields(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let running = self.running.is_some(); - let target: AnyElement = match self.target { - Target::New => form::group( - t(cx, "import.newTableName"), - form::input(&self.new_table, window, cx).disabled(running), - cx, - ) - .child(form::hint(t(cx, "import.newTableHint"), cx)) - .into_any_element(), - Target::Existing => { - let this = cx.entity().downgrade(); - let (tables, current) = (self.tables.clone(), self.existing.clone()); - let table = form::select("import-existing-table", current.clone(), cx) - .debug_selector(|| "import-existing-table".into()) - .disabled(running) - .select_menu(window, cx, move |mut menu: PopupMenu, _, _| { - for table in tables.clone() { - let this = this.clone(); - let checked = table == current; - menu = menu.item(PopupMenuItem::new(table.clone()).checked(checked).on_click( - move |_, window, cx| { - this.update(cx, |dialog, cx| dialog.set_existing(table.clone(), window, cx)).ok(); - }, - )); - } - menu.scrollable(true) - }); - v_flex() - .gap(rems(0.923)) - .child(form::group(t(cx, "import.existingTable"), table, cx)) - .child( - v_flex() - .child(self.checkbox( - "import-truncate", - "import.truncate", - self.truncate, - |d, v| d.truncate = v, - cx, - )) - .child(form::hint(t(cx, "import.truncateHint"), cx).pl(rems(2.))), - ) - .into_any_element() - } - }; - let this = cx.entity().downgrade(); - let current = self.delimiter; - let delimiter_label = DELIMITERS.iter().find(|(value, _)| *value == current).map_or("", |(_, key)| key); - let delimiter = form::select("import-delimiter", t(cx, delimiter_label), cx) - .debug_selector(|| "import-delimiter".into()) - .disabled(running) - .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { - for (value, key) in DELIMITERS { - let this = this.clone(); - menu = menu.item(PopupMenuItem::new(t(cx, key)).checked(value == current).on_click( - move |_, window, cx| { - this.update(cx, |dialog, cx| { - dialog.delimiter = value; - dialog.schedule_preview(window, cx); - cx.notify(); - }) - .ok(); - }, - )); - } - menu - }); - let fluid = |children: Vec| { - h_flex() - .flex_wrap() - .items_start() - .gap(rems(0.769)) - .children(children.into_iter().map(|child| div().flex_1().min_w_0().child(child))) - }; - let options = form::section(cx) - .child(fluid(vec![ - form::group(t(cx, "import.delimiter"), delimiter, cx).into_any_element(), - form::group(t(cx, "import.skipRows"), form::input(&self.skip_rows, window, cx).disabled(running), cx) - .into_any_element(), - form::group( - t(cx, "import.nullLiteral"), - form::input(&self.null_literal, window, cx).disabled(running), - cx, - ) - .into_any_element(), - ])) - .child(fluid(vec![ - self.checkbox("import-header", "import.hasHeader", self.has_header, |d, v| d.has_header = v, cx) - .into_any_element(), - self.checkbox("import-trim", "import.trimSpace", self.trim_space, |d, v| d.trim_space = v, cx) - .into_any_element(), - self.checkbox("import-stop", "import.stopOnError", self.stop_on_error, |d, v| d.stop_on_error = v, cx) - .into_any_element(), - ])); - v_flex().gap(rems(0.923)).child(target).child(options).child(self.preview_table(window, cx)) + // Cancel until something has run. + fn dismiss_label(&self, cx: &App) -> SharedString { + let ran = self.result.is_some() || self.error.is_some(); + t(cx, if ran { "common.close" } else { "common.cancel" }) } - fn preview_table(&mut self, window: &mut Window, cx: &mut Context) -> AnyElement { - let theme = cx.theme().clone(); - if self.previewing { - return h_flex() - .gap(rems(0.385)) - .text_size(TEXT_XS) - .text_color(theme.muted_foreground) - .child(Spinner::new(ICON_XS)) - .child(t(cx, "import.reading")) - .into_any_element(); - } - if let Some(error) = &self.preview_error { - return form::error(error.clone(), cx).into_any_element(); + fn run_label(&self, cx: &App) -> SharedString { + if self.deleting() { + return t(cx, "import.runDeleting"); } - let Some(preview) = self.preview.clone() else { return div().into_any_element() }; - let delimiter = if preview.delimiter == "\t" { "\\t".to_string() } else { preview.delimiter.clone() }; - let mut meta = String::new(); - if preview.total_rows > 0 { - let rows = count(cx, preview.total_rows as usize); - meta = format!("{} · ", t_count(cx, "import.fileRows", preview.total_rows as i64, &[("rows", &rows)])); + match self.preview.as_ref().filter(|preview| self.is_table() && preview.total_rows > 0) { + Some(preview) => { + let rows = count(cx, preview.total_rows as usize); + t_count(cx, "import.runRows", preview.total_rows as i64, &[("rows", &rows)]) + } + None => t(cx, "import.run"), } - meta.push_str(&t_with(cx, "import.detectedDelimiter", &[("delimiter", &delimiter)])); - let new_table = self.target == Target::New; - let running = self.running.is_some(); - let mono = theme.mono_font_family.clone(); - let cell = || div().flex_1().min_w_0().px(rems(0.615)).py(rems(0.308)); - let heading = - |key: &str, cx: &App| cell().text_size(TEXT_XS).text_color(cx.theme().muted_foreground).child(t(cx, key)); - let header = h_flex() - .bg(theme.secondary) - .child(heading("import.sourceColumn", cx)) - .child(heading("import.sample", cx)) - .child(heading("import.targetColumn", cx)) - .when(new_table, |el| el.child(heading("import.columnType", cx))); - let rows: Vec = preview - .columns - .iter() - .enumerate() - .map(|(ix, column)| { - let skipped = self.mapping.get(ix).is_some_and(|input| input.read(cx).value().trim().is_empty()); - let sample = preview.rows.first().and_then(|row| row.get(ix)).cloned().unwrap_or_default(); - let kind = self.column_types.get(ix).cloned().unwrap_or_else(|| "text".into()); - let this = cx.entity().downgrade(); - let picker = form::select(("import-type", ix), t(cx, &format!("import.type.{kind}")), cx) - .disabled(running) - .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { - for option in COLUMN_TYPES { - let this = this.clone(); - menu = menu.item( - PopupMenuItem::new(t(cx, &format!("import.type.{option}"))) - .checked(option == kind) - .on_click(move |_, _, cx| { - this.update(cx, |dialog, cx| { - if let Some(slot) = dialog.column_types.get_mut(ix) { - *slot = option.to_string(); - } - cx.notify(); - }) - .ok(); - }), - ); - } - menu - }); - h_flex() - .text_size(TEXT_SM) - .border_t_1() - .border_color(theme.border) - .child( - cell() - .truncate() - .font_family(mono.clone()) - .when(skipped, |el| el.opacity(DIMMED)) - .child(column.clone()), - ) - .child( - cell() - .truncate() - .font_family(mono.clone()) - .text_size(TEXT_XS) - .text_color(theme.muted_foreground) - .when(skipped, |el| el.opacity(DIMMED)) - .child(sample), - ) - .child(cell().child(self.target_cell(ix, running, window, cx))) - .when(new_table, |el| el.child(cell().child(picker))) - .into_any_element() - }) - .collect(); - v_flex() - .flex_none() - .border_1() - .border_color(theme.border) - .rounded(RADIUS) - .overflow_hidden() - .child( - h_flex() - .justify_between() - .gap(rems(0.615)) - .px(rems(0.615)) - .py(rems(0.385)) - .bg(theme.secondary) - .border_b_1() - .border_color(theme.border) - .child(form::caption(t(cx, "import.columnsHeading"), cx)) - .child(div().text_size(TEXT_XS).text_color(theme.muted_foreground).child(meta)), - ) - .when(preview.not_utf8, |el| { - el.child( - div() - .debug_selector(|| "import-not-utf8".into()) - .px(rems(0.615)) - .py(rems(0.385)) - .border_b_1() - .border_color(theme.border) - .text_size(TEXT_XS) - .text_color(theme.warning) - .child(t(cx, "import.notUtf8")), - ) - }) - .child(header) - .children(rows) - .into_any_element() } - fn footer(&self, cx: &mut Context) -> impl IntoElement { - let running = self.running.is_some(); - // A counted CSV says how many rows the click will load. - let rows = self.preview.as_ref().filter(|preview| self.kind != Kind::Sql && preview.total_rows > 0); - let run_label = match (running, rows) { - (true, _) => t(cx, "import.running"), - (false, Some(preview)) => { - let rows = count(cx, preview.total_rows as usize); - t_count(cx, "import.runRows", preview.total_rows as i64, &[("rows", &rows)]) + // Numbered marks joined by lines. Steps already reached take a click. + fn stepper(&self, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + let steps = self.steps(); + let current = steps.iter().position(|step| *step == self.step).unwrap_or(0); + let locked = self.running.is_some() || self.result.is_some(); + let mut strip = h_flex() + .flex_none() + .gap(rems(0.615)) + .px(rems(1.231)) + .py(rems(0.769)) + .border_b_1() + .border_color(theme.border); + for (ix, &step) in steps.iter().enumerate() { + if ix > 0 { + strip = strip.child(div().flex_1().min_w(rems(0.923)).h(px(1.)).bg(theme.border)); } - (false, None) => t(cx, "import.run"), - }; - modal::footer(cx) - .child( - Button::new("import-dismiss") - .large() - .debug_selector(|| "import-dismiss".into()) - .label(t(cx, if running { "import.stop" } else { "common.close" })) - .on_click(cx.listener(|this, _, window, cx| this.dismiss(window, cx))), - ) - .child( - Button::new("import-run") - .large() - .debug_selector(|| "import-run".into()) - .primary() - .label(run_label) - .disabled(!self.can_run(cx)) - .on_click(cx.listener(|this, _, window, cx| this.run(window, cx))), - ) + let (done, here) = (ix < current, ix == current); + let open = !locked && !here && self.reachable(step); + let mark = div() + .flex_none() + .size(rems(1.538)) + .rounded_full() + .flex() + .items_center() + .justify_center() + .border_1() + .text_size(TEXT_XS) + .font_semibold() + .map(|el| match (done, here) { + (true, _) => el + .border_color(theme.primary.opacity(TINT_BORDER)) + .text_color(theme.primary) + .child(Icon::new(IconName::Check).size(ICON_2XS)), + (_, true) => el + .border_color(theme.primary) + .bg(theme.primary.opacity(TINT)) + .text_color(theme.primary) + .child((ix + 1).to_string()), + _ => el.border_color(theme.border).text_color(theme.muted_foreground).child((ix + 1).to_string()), + }); + let label = div() + .whitespace_nowrap() + .text_size(TEXT_SM) + .text_color(if here { theme.foreground } else { theme.muted_foreground }) + .when(here, |el| el.font_medium()) + .child(t(cx, step.key())); + strip = strip.child( + h_flex() + .id(("import-step", ix)) + .debug_selector(move || format!("import-step-{ix}")) + .flex_none() + .gap(rems(0.462)) + .rounded(RADIUS) + .child(mark) + .child(label) + .when(open, |el| el.cursor_pointer().on_click(cx.listener(move |this, _, _, cx| this.go(step, cx)))) + .test_support(), + ); + } + strip } - fn result_view(&self, result: &ImportResult, cx: &App) -> impl IntoElement { - let theme = cx.theme(); - let n = |value: i64| count(cx, value.max(0) as usize); - // The counts go in grouped, as `{{statements}}` and `{{rows}}`, since `{{count}}` would be the bare number. - let skipped = n(result.skipped); - let text = if self.kind == Kind::Sql { - let statements = n(result.statements); - t_count( - cx, - "import.doneStatements", - result.statements, - &[("statements", &statements), ("skipped", &skipped)], - ) - } else { - let rows = n(result.inserted); - t_count(cx, "import.doneRows", result.inserted, &[("rows", &rows), ("skipped", &skipped)]) + fn footer(&self, cx: &mut Context) -> impl IntoElement { + let close = |label: SharedString, cx: &mut Context| { + Button::new("import-dismiss") + .large() + .debug_selector(|| "import-dismiss".into()) + .label(label) + .on_click(cx.listener(|this, _, window, cx| this.dismiss(window, cx))) }; - let tint = if result.skipped > 0 { theme.warning } else { theme.success }; - form::alert(tint) - .flex() - .flex_col() - .gap(rems(0.385)) - .child( - h_flex() - .gap(rems(0.385)) - .child( - Icon::new(if result.cancelled { Lucide::CircleAlert } else { Lucide::CircleCheck }) - .size(ICON_XS), + if self.running.is_some() { + return modal::footer(cx).child(close(t(cx, "import.stop"), cx)); + } + if let Some(result) = &self.result { + let opens = self.loaded_table.is_some() && result.inserted > 0; + let again = Button::new("import-again") + .large() + .debug_selector(|| "import-again".into()) + .label(t(cx, "import.again")) + .on_click(cx.listener(|this, _, window, cx| this.again(window, cx))); + return modal::footer(cx) + .child(h_flex().flex_1().child(again)) + .child(close(t(cx, "common.close"), cx).when(!opens, |button| button.primary())) + .when(opens, |el| { + el.child( + Button::new("import-open-table") + .large() + .primary() + .debug_selector(|| "import-open-table".into()) + .label(t(cx, "import.openTable")) + .on_click(cx.listener(|this, _, window, cx| this.open_table(window, cx))), ) - .child(text), - ) - .when(result.cancelled, |el| { - el.child( - div().text_size(TEXT_XS).text_color(theme.muted_foreground).child(t(cx, "import.cancelledNote")), - ) - }) - .when(!result.errors.is_empty(), |el| { - let errors = v_flex() - .id("import-errors") - .max_h(px(120.)) - .overflow_y_scroll() - .track_scroll(&self.errors_scroll) - .pl(rems(1.231)) - .font_family(theme.mono_font_family.clone()) - .text_size(TEXT_XS) - .text_color(theme.muted_foreground) - .children(result.errors.iter().map(|error| div().child(format!("• {error}")))); - el.child(div().relative().child(errors).hover_scrollbar(&self.errors_scroll, ScrollbarAxis::Vertical)) - }) + }); + } + let back = self.back_step().map(|step| { + Button::new("import-back") + .large() + .debug_selector(|| "import-back".into()) + .label(t(cx, "import.back")) + .on_click(cx.listener(move |this, _, _, cx| this.go(step, cx))) + }); + let forward = match self.on_last_step() { + false => Button::new("import-next") + .large() + .primary() + .debug_selector(|| "import-next".into()) + .label(t(cx, "import.next")) + .disabled(self.next_step().is_none()) + .on_click(cx.listener(|this, _, _, cx| this.next(cx))), + // Red as the app's other deletes are, when the table is emptied first. + true => Button::new("import-run") + .large() + .map(|button| if self.deleting() { button.danger().outline() } else { button.primary() }) + .debug_selector(|| "import-run".into()) + .label(self.run_label(cx)) + .disabled(!self.can_run(cx)) + .on_click(cx.listener(|this, _, window, cx| this.run(window, cx))), + }; + modal::footer(cx) + .child(h_flex().flex_1().children(back)) + .child(close(self.dismiss_label(cx), cx)) + .child(forward) } } impl Render for ImportDialog { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { self.sync_tables(cx); - let running = self.running.is_some(); - let csv = self.kind == Kind::Csv; - let kinds = form::toggle_group() - .child( - form::toggle("import-kind-csv", t(cx, "import.kindCSV"), csv) - .debug_selector(|| "import-kind-csv".into()) - .icon(Icon::new(Lucide::Sheet)) - .disabled(running) - .on_click(cx.listener(|this, _, _, cx| { - if this.kind != Kind::Csv { - this.set_kind(Kind::Csv, cx); - } - })), - ) - .child( - form::toggle("import-kind-sql", t(cx, "import.kindSQL"), !csv) - .debug_selector(|| "import-kind-sql".into()) - .icon(Icon::new(Lucide::FileCode)) - .disabled(running) - .on_click(cx.listener(|this, _, _, cx| { - if this.kind != Kind::Sql { - this.set_kind(Kind::Sql, cx); - } - })), - ); - let no_tables = self.tables.is_empty(); - let targets = form::toggle_group() - .child( - form::toggle("import-target-new", t(cx, "import.targetNew"), self.target == Target::New) - .debug_selector(|| "import-target-new".into()) - .disabled(running) - .on_click(cx.listener(|this, _, window, cx| this.set_target(Target::New, window, cx))), - ) - .child( - form::toggle("import-target-existing", t(cx, "import.targetExisting"), self.target == Target::Existing) - .debug_selector(|| "import-target-existing".into()) - .disabled(running || no_tables) - .when(no_tables, |button| button.tooltip(t(cx, "import.noTables"))) - .on_click(cx.listener(|this, _, window, cx| this.set_target(Target::Existing, window, cx))), - ); - let theme = cx.theme().clone(); - let path: SharedString = if self.path.is_empty() { t(cx, "import.noFile") } else { self.path.clone().into() }; - let path_field = div() - .flex_1() - .min_w_0() - .h(rems(form::FIELD_REM)) - .flex() - .items_center() - .px(rems(0.769)) - .rounded(RADIUS) - .border_1() - .border_color(theme.border) - .bg(theme.background) - .text_size(TEXT_BASE) - .text_color(if self.path.is_empty() { theme.muted_foreground } else { theme.foreground }) - .child(div().min_w_0().truncate().child(path)); - let file_row = h_flex().gap(rems(0.615)).child(path_field).child( - form::field_button("import-browse") - .debug_selector(|| "import-browse".into()) - .large_with_icon(Icon::new(Lucide::FolderOpen), t(cx, "common.browse")) - .disabled(running) - .on_click(cx.listener(|this, _, window, cx| this.pick(window, cx))), - ); - let kind_row = h_flex() - .flex_wrap() - .items_start() - .gap(rems(0.769)) - .child(div().flex_1().min_w_0().child(form::group(t(cx, "import.kind"), kinds, cx))) - .when(csv, |el| el.child(div().flex_1().min_w_0().child(form::group(t(cx, "import.target"), targets, cx)))); - let body = modal::body() - .child(kind_row) - .child(form::group(t(cx, "import.file"), file_row, cx)) - .when(csv, |el| el.child(self.csv_fields(window, cx))) - .when(!csv, |el| { - el.child(self.checkbox( - "import-stop-sql", - "import.stopOnError", - self.stop_on_error, - |d, v| d.stop_on_error = v, - cx, - )) - }) - .when(running, |el| el.child(self.progress_view(cx))) - .when_some(self.error.clone(), |el, error| el.child(form::error(error, cx))) - .when_some(self.result.clone(), |el, result| el.child(self.result_view(&result, cx))); - modal::scroll_content().child(modal::scroll_body(body)).child(self.footer(cx)) + let body = match self.step { + Step::File => self.file_step(window, cx).into_any_element(), + Step::Preview => self.preview_step(window, cx).into_any_element(), + Step::Columns => self.columns_step(window, cx).into_any_element(), + Step::Import => self.run_step(cx).into_any_element(), + }; + modal::scroll_content().child(self.stepper(cx)).child(body).child(self.footer(cx)) } } @@ -1025,7 +892,10 @@ impl Global for Opened {} #[cfg(test)] pub(crate) struct Shown { - pub csv: bool, + pub format: Option, + pub step: Step, + // The file is read: its format is known and no preview is loading. + pub read: bool, pub has_header: bool, pub can_run: bool, pub existing: Option, @@ -1042,7 +912,9 @@ pub(crate) struct Shown { impl ImportDialog { pub(crate) fn shown(&self, cx: &App) -> Shown { Shown { - csv: self.kind == Kind::Csv, + format: self.format, + step: self.step, + read: self.format.is_some() && !self.previewing, has_header: self.has_header, can_run: self.can_run(cx), existing: (self.target == Target::Existing).then(|| self.existing.clone()), @@ -1062,11 +934,11 @@ pub fn open( schema: String, tables: Vec, table: Option, + hooks: Hooks, window: &mut Window, cx: &mut App, - on_imported: impl Fn(&mut App) + 'static, ) { - let dialog = cx.new(|cx| ImportDialog::new(connection, schema, tables, table, Rc::new(on_imported), window, cx)); + let dialog = cx.new(|cx| ImportDialog::new(connection, schema, tables, table, hooks, window, cx)); #[cfg(any(test, feature = "snapshot"))] cx.set_global(Opened(dialog.downgrade())); window.open_dialog(cx, move |frame, window, cx| { @@ -1074,6 +946,7 @@ pub fn open( let entry = dialog.clone(); Modal::new("import", t(cx, "import.title")) .size(modal::Size::Lg) + .height(window.rem_size() * DIALOG_REM) .closable(!running) .build(frame, dialog.clone(), window, cx) .keyboard(!running) @@ -1084,202 +957,3 @@ pub fn open( }) }); } - -#[cfg(test)] -mod tests { - use std::cell::Cell; - use std::rc::Rc; - - use barsql_app::{ImportDone, ImportEvent}; - use barsql_core::Value; - use gpui_kit::component::Root; - use gpui_kit::{AppContext as _, Entity, TestAppContext, VisualTestContext}; - - use super::{ImportDialog, Kind, Target, fits, table_name_for}; - use crate::i18n::I18n; - use crate::test_support::{Env, settle}; - - #[gpui_kit::test] - fn an_import_that_hit_a_bug_says_so_in_the_ui_language(cx: &mut TestAppContext) { - let env = Env::new(cx); - cx.update(|cx| cx.set_global(I18n::new("de"))); - let (view, cx) = open(&env, cx, Rc::new(Cell::new(0))); - let done = ImportDone { error: "BarSQL hit a bug.".into(), bug: true, ..Default::default() }; - view.update(cx, |dialog, cx| dialog.apply(ImportEvent::Done(done), cx)); - let said = "In BarSQL ist ein interner Fehler aufgetreten. Details stehen in crash.log im Datenordner."; - assert_eq!(view.read_with(cx, |dialog, _| dialog.error.clone()).as_deref(), Some(said)); - } - - fn open<'a>( - env: &Env, - cx: &'a mut TestAppContext, - imported: Rc>, - ) -> (Entity, &'a mut VisualTestContext) { - let connection = env.connection.clone(); - let slot = Rc::new(std::cell::RefCell::new(None)); - let out = slot.clone(); - let window = cx.add_window(move |window, cx| { - let on_imported = Rc::new(move |_: &mut gpui_kit::App| imported.set(imported.get() + 1)); - let view = cx.new(|cx| { - ImportDialog::new(connection, "main".into(), vec!["things".into()], None, on_imported, window, cx) - }); - *out.borrow_mut() = Some(view.clone()); - Root::new(view, window, cx) - }); - let cx = VisualTestContext::from_window(window.into(), cx).into_mut(); - let view = slot.borrow_mut().take().unwrap(); - (view, cx) - } - - #[gpui_kit::test] - fn a_csv_previews_then_loads_into_a_new_table(cx: &mut TestAppContext) { - let env = Env::new(cx); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("people list.csv"); - std::fs::write(&path, "name,age,active\nann,31,true\nbob,,false\n").unwrap(); - let imported = Rc::new(Cell::new(0)); - let (view, cx) = open(&env, cx, imported.clone()); - view.update_in(cx, |dialog, window, cx| { - dialog.path = path.display().to_string(); - dialog.load_preview(window, cx); - }); - settle(cx, |cx| view.read_with(cx, |d, _| d.preview.is_some())); - let (columns, types, table) = view.read_with(cx, |d, cx| { - let preview = d.preview.clone().unwrap(); - (preview.columns, d.column_types.clone(), d.new_table.read(cx).value().to_string()) - }); - assert_eq!(columns, ["name", "age", "active"]); - assert_eq!(types, ["text", "int", "bool"]); - assert_eq!(table, "people_list"); - view.update_in(cx, |dialog, window, cx| dialog.run(window, cx)); - settle(cx, |cx| view.read_with(cx, |d, _| d.running.is_none() && (d.result.is_some() || d.error.is_some()))); - let result = view.read_with(cx, |d, _| d.result.clone()).expect("a result"); - assert_eq!((result.inserted, result.skipped, result.cancelled), (2, 0, false)); - assert_eq!(imported.get(), 1); - let rows = env - .runtime - .block_on(env.bar.execute_query(&env.connection.id, "SELECT name, age FROM people_list ORDER BY name")) - .unwrap() - .rows; - assert_eq!( - rows, - [vec![Value::Text("ann".into()), Value::Int(31)], vec![Value::Text("bob".into()), Value::Null]] - ); - } - - // Excel saves CSV in Windows-1252, where é is one byte that isn't UTF-8. - #[gpui_kit::test] - fn a_csv_that_isnt_utf8_says_so_in_the_preview(cx: &mut TestAppContext) { - let env = Env::new(cx); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("cafes.csv"); - std::fs::write(&path, b"name\ncaf\xe9\n").unwrap(); - let (view, cx) = open(&env, cx, Rc::new(Cell::new(0))); - view.update_in(cx, |dialog, window, cx| { - dialog.path = path.display().to_string(); - dialog.load_preview(window, cx); - }); - settle(cx, |cx| view.read_with(cx, |d, _| d.preview.is_some())); - assert!(view.read_with(cx, |d, _| d.preview.as_ref().is_some_and(|p| p.not_utf8))); - cx.run_until_parked(); - cx.update(|window, cx| window.draw(cx).clear(cx)); - assert!(cx.debug_bounds("import-not-utf8").is_some(), "the preview warns"); - } - - #[gpui_kit::test] - fn a_sql_script_runs_its_statements(cx: &mut TestAppContext) { - let env = Env::new(cx); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("seed.sql"); - std::fs::write( - &path, - "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT);\nINSERT INTO notes (body) VALUES ('a'), ('b');\n", - ) - .unwrap(); - let imported = Rc::new(Cell::new(0)); - let (view, cx) = open(&env, cx, imported.clone()); - view.update_in(cx, |dialog, window, cx| { - dialog.set_kind(Kind::Sql, cx); - dialog.path = path.display().to_string(); - dialog.run(window, cx); - }); - settle(cx, |cx| view.read_with(cx, |d, _| d.running.is_none() && (d.result.is_some() || d.error.is_some()))); - let result = view.read_with(cx, |d, _| d.result.clone()).expect("a result"); - assert_eq!((result.statements, result.skipped), (2, 0)); - assert_eq!(imported.get(), 1); - let count = - env.runtime.block_on(env.bar.execute_query(&env.connection.id, "SELECT count(*) FROM notes")).unwrap().rows; - assert_eq!(count[0][0], Value::Int(2)); - } - - // What a column's sampled values look like against the type of the column they load into. - #[test] - fn values_fit_columns_that_can_hold_them() { - let fit = [ - ("int", "INTEGER"), - ("int", "numeric(10,2)"), - ("int", "Nullable(Int32)"), - ("float", "double precision"), - ("bool", "boolean"), - ("bool", "tinyint(1)"), - ("date", "timestamp without time zone"), - ("timestamp", "datetime2"), - ("text", "character varying(50)"), - ("int", "text"), - ("text", "uuid"), - ]; - for (inferred, column) in fit { - assert!(fits(inferred, column), "{inferred} into {column}"); - } - let misfit = - [("text", "integer"), ("float", "bigint"), ("text", "date"), ("timestamp", "date"), ("text", "bool")]; - for (inferred, column) in misfit { - assert!(!fits(inferred, column), "{inferred} into {column}"); - } - } - - // A file's ID loads into the table's id. A column the table lacks is flagged until it's skipped. - #[gpui_kit::test] - fn an_existing_tables_columns_match_the_files_whatever_their_case(cx: &mut TestAppContext) { - let env = Env::new(cx); - let create = "CREATE TABLE crew (id INTEGER PRIMARY KEY, name TEXT)"; - env.runtime.block_on(env.bar.execute_query(&env.connection.id, create)).unwrap(); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("more.csv"); - std::fs::write(&path, "ID,Name,Extra\n9001,nine thousand one,x\n").unwrap(); - let imported = Rc::new(Cell::new(0)); - let (view, cx) = open(&env, cx, imported.clone()); - view.update_in(cx, |dialog, window, cx| { - dialog.set_target(Target::Existing, window, cx); - dialog.set_existing("crew".into(), window, cx); - dialog.path = path.display().to_string(); - dialog.load_preview(window, cx); - }); - let mapped = |cx: &mut VisualTestContext| view.read_with(cx, |d, cx| d.mapping_values(cx)); - settle(cx, |cx| mapped(cx).first().is_some_and(|first| first == "id")); - assert_eq!(mapped(cx), ["id", "name", "Extra"]); - let fits = view.read_with(cx, |d, cx| (0..3).map(|ix| d.fit(ix, cx)).collect::>()); - assert_eq!(fits, [Some(true), Some(true), Some(false)], "Extra is no column of crew"); - view.update_in(cx, |dialog, window, cx| { - dialog.mapping[2].update(cx, |input, cx| input.set_value("", window, cx)); - dialog.run(window, cx); - }); - settle(cx, |cx| view.read_with(cx, |d, _| d.running.is_none() && (d.result.is_some() || d.error.is_some()))); - assert_eq!(view.read_with(cx, |d, _| d.result.as_ref().map(|r| r.inserted)), Some(1)); - let name = env - .runtime - .block_on(env.bar.execute_query(&env.connection.id, "SELECT name FROM crew WHERE id = 9001")) - .unwrap() - .rows; - assert_eq!(name, [vec![Value::Text("nine thousand one".into())]]); - } - - #[test] - fn file_names_become_table_names() { - assert_eq!(table_name_for("/data/Sales 2024.csv"), "Sales_2024"); - assert_eq!(table_name_for("C:\\exports\\orders.v2.tsv"), "orders_v2"); - assert_eq!(table_name_for("/tmp/.hidden"), ""); - assert_eq!(table_name_for("plain"), "plain"); - assert_eq!(table_name_for("file."), "file_"); - } -} diff --git a/crates/barsql-ui/src/import_dialog/columns_step.rs b/crates/barsql-ui/src/import_dialog/columns_step.rs new file mode 100644 index 0000000..96c75e4 --- /dev/null +++ b/crates/barsql-ui/src/import_dialog/columns_step.rs @@ -0,0 +1,199 @@ +use barsql_sql::display_type; +use gpui_kit::component::menu::{PopupMenu, PopupMenuItem}; +use gpui_kit::component::tooltip::Tooltip; +use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +use super::{COLUMN_TYPES, ImportDialog, Target, fits}; +use crate::form::{self, SelectMenu}; +use crate::i18n::{count, t, t_with}; +use crate::modal; +use crate::tokens::{DIMMED, ICON_XS, RADIUS, TEXT_SM, TEXT_XS}; + +// Distinct values a column shows beside its name. +const SAMPLES: usize = 3; + +impl ImportDialog { + pub(super) fn columns_step(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let Some(preview) = self.preview.clone() else { return modal::scroll_body(modal::body()) }; + let theme = cx.theme().clone(); + let new_table = self.target == Target::New; + let running = self.running.is_some(); + let mono = theme.mono_font_family.clone(); + let cell = || div().flex_1().min_w_0().px(rems(0.615)).py(rems(0.308)); + let heading = + |key: &str, cx: &App| cell().text_size(TEXT_XS).text_color(cx.theme().muted_foreground).child(t(cx, key)); + let header = h_flex() + .bg(theme.secondary) + .child(heading("import.sourceColumn", cx)) + .child(heading("import.sample", cx)) + .child(heading("import.targetColumn", cx)) + .when(new_table, |el| el.child(heading("import.columnType", cx))); + let rows: Vec = preview + .columns + .iter() + .enumerate() + .map(|(ix, column)| { + let skipped = self.mapping.get(ix).is_some_and(|input| input.read(cx).value().trim().is_empty()); + let kind = self.column_types.get(ix).cloned().unwrap_or_else(|| "text".into()); + let this = cx.entity().downgrade(); + let picker = form::select(("import-type", ix), t(cx, &format!("import.type.{kind}")), cx) + .disabled(running) + .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { + for option in COLUMN_TYPES { + let this = this.clone(); + menu = menu.item( + PopupMenuItem::new(t(cx, &format!("import.type.{option}"))) + .checked(option == kind) + .on_click(move |_, _, cx| { + this.update(cx, |dialog, cx| { + if let Some(slot) = dialog.column_types.get_mut(ix) { + *slot = option.to_string(); + } + cx.notify(); + }) + .ok(); + }), + ); + } + menu + }); + h_flex() + .text_size(TEXT_SM) + .border_t_1() + .border_color(theme.border) + .child( + cell() + .truncate() + .font_family(mono.clone()) + .when(skipped, |el| el.opacity(DIMMED)) + .child(column.clone()), + ) + .child( + cell() + .truncate() + .font_family(mono.clone()) + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .when(skipped, |el| el.opacity(DIMMED)) + .child(samples(&preview.rows, ix)), + ) + .child(cell().child(self.target_cell(ix, running, window, cx))) + .when(new_table, |el| el.child(cell().child(picker))) + .into_any_element() + }) + .collect(); + let mapped = t_with( + cx, + "import.mapped", + &[("mapped", &count(cx, self.mapped_count(cx))), ("total", &count(cx, preview.columns.len()))], + ); + let table = v_flex() + .flex_none() + .border_1() + .border_color(theme.border) + .rounded(RADIUS) + .overflow_hidden() + .child( + h_flex() + .justify_between() + .gap(rems(0.615)) + .px(rems(0.615)) + .py(rems(0.385)) + .bg(theme.secondary) + .border_b_1() + .border_color(theme.border) + .child(form::caption(t(cx, "import.columnsHeading"), cx)) + .child(div().text_size(TEXT_XS).text_color(theme.muted_foreground).child(mapped)), + ) + .child(header) + .children(rows); + modal::scroll_body(modal::body().child(table)) + } + + // Whether column `ix`'s values look like they load where it maps. None when it's skipped, or before the table's + // columns are known. + pub(super) fn fit(&self, ix: usize, cx: &App) -> Option { + let columns = self.existing_columns()?; + let value = self.mapping.get(ix)?.read(cx).value().trim().to_string(); + let inferred = self.preview.as_ref()?.inferred_types.get(ix)?; + (!value.is_empty()) + .then(|| columns.iter().find(|c| c.name == value).is_some_and(|c| fits(inferred, &c.data_type))) + } + + // Why column `ix` is flagged: the table has no such column, or its values don't look like the column's type. + fn misfit(&self, ix: usize, cx: &App) -> SharedString { + let value = self.mapping.get(ix).map(|input| input.read(cx).value().trim().to_string()).unwrap_or_default(); + let column = self.existing_columns().and_then(|columns| columns.iter().find(|c| c.name == value).cloned()); + let inferred = self.preview.as_ref().and_then(|p| p.inferred_types.get(ix).cloned()).unwrap_or_default(); + match column { + None => t_with(cx, "import.notAColumn", &[("table", &self.existing), ("column", &value)]), + Some(column) => { + let kind = t(cx, &format!("import.type.{inferred}")); + let shown = display_type(self.connection.driver.dialect(), &column.data_type); + t_with(cx, "import.mismatch", &[("kind", &kind), ("type", &shown)]) + } + } + } + + // An existing table's column picker, with a mark for how the values fit. Typed names before its columns load, + // and for a new table, whose columns they name. + fn target_cell(&self, ix: usize, running: bool, window: &mut Window, cx: &mut Context) -> AnyElement { + let Some(input) = self.mapping.get(ix).cloned() else { return div().into_any_element() }; + let Some(columns) = self.existing_columns() else { + return form::input(&input, window, cx).disabled(running).into_any_element(); + }; + let value = input.read(cx).value().trim().to_string(); + let label: SharedString = if value.is_empty() { t(cx, "import.skipColumn") } else { value.clone().into() }; + let dialect = self.connection.driver.dialect(); + let this = cx.entity().downgrade(); + let picker = form::select(("import-target", ix), label, cx) + .debug_selector(move || format!("import-target-{ix}")) + .disabled(running) + .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { + let pick = |name: String| { + let (input, this) = (input.clone(), this.clone()); + move |_: &ClickEvent, window: &mut Window, cx: &mut App| { + input.update(cx, |input, cx| input.set_value(name.clone(), window, cx)); + this.update(cx, |_, cx| cx.notify()).ok(); + } + }; + let skip = PopupMenuItem::new(t(cx, "import.skipColumn")).checked(value.is_empty()); + menu = menu.item(skip.on_click(pick(String::new()))); + for column in columns.iter() { + let label = format!("{} · {}", column.name, display_type(dialect, &column.data_type)); + let item = PopupMenuItem::new(label).checked(column.name == value); + menu = menu.item(item.on_click(pick(column.name.clone()))); + } + menu.scrollable(true) + }); + let theme = cx.theme(); + let mark = self.fit(ix, cx).map(|fits| { + let (icon, color) = + if fits { (IconName::Check, theme.success) } else { (IconName::TriangleAlert, theme.warning) }; + let tip = (!fits).then(|| self.misfit(ix, cx)); + div() + .id(("import-fit", ix)) + .debug_selector(move || format!("import-fit-{ix}")) + .flex_none() + .child(Icon::new(icon).size(ICON_XS).text_color(color)) + .when_some(tip, |el, tip| el.tooltip(move |window, cx| Tooltip::new(tip.clone()).build(window, cx))) + }); + h_flex().gap(rems(0.462)).child(div().flex_1().min_w_0().child(picker)).children(mark).into_any_element() + } +} + +// The column's first few different values that aren't blank. +fn samples(rows: &[Vec], ix: usize) -> String { + let mut seen: Vec<&str> = Vec::new(); + for value in rows.iter().filter_map(|row| row.get(ix)).map(|value| value.trim()) { + if !value.is_empty() && !seen.contains(&value) { + seen.push(value); + if seen.len() == SAMPLES { + break; + } + } + } + seen.join(", ") +} diff --git a/crates/barsql-ui/src/import_dialog/file_step.rs b/crates/barsql-ui/src/import_dialog/file_step.rs new file mode 100644 index 0000000..3f423ba --- /dev/null +++ b/crates/barsql-ui/src/import_dialog/file_step.rs @@ -0,0 +1,213 @@ +use barsql_app::FileFormat; +use gpui_kit::assets::IconName as Lucide; +use gpui_kit::component::button::Button; +use gpui_kit::component::menu::{PopupMenu, PopupMenuItem}; +use gpui_kit::component::tooltip::Tooltip; +use gpui_kit::component::{ActiveTheme, Disableable, Icon, StyledExt, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +use super::{ImportDialog, Target, format_key, shape_key}; +use crate::form::{self, LargeButton as _, SelectMenu, ToolButton as _}; +use crate::i18n::{bytes, count, t, t_count, t_with}; +use crate::modal; +use crate::tokens::{ICON_MD, ICON_XL, RADIUS, TEXT_BASE, TEXT_XS, TINT}; + +const FORMATS: [FileFormat; 3] = [FileFormat::Csv, FileFormat::Json, FileFormat::Sql]; + +impl ImportDialog { + pub(super) fn file_step(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let source = match self.path.is_empty() { + true => self.drop_zone(cx).into_any_element(), + false => self.file_card(window, cx).into_any_element(), + }; + let error = self.preview_error.clone().filter(|_| !self.previewing); + let script = (!self.is_table()) + .then(|| form::hint(t_with(cx, "import.scriptRuns", &[("connection", &self.connection.name)]), cx).mt_0()); + modal::scroll_body( + modal::body() + .child(source) + .when_some(error, |el, error| el.child(form::error(error, cx))) + .children(script) + .when(self.is_table(), |el| el.child(self.target_fields(window, cx))), + ) + } + + fn drop_zone(&self, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + v_flex() + .id("import-drop") + .debug_selector(|| "import-drop".into()) + .items_center() + .gap(rems(0.462)) + .py(rems(2.154)) + .px(rems(1.231)) + .rounded(RADIUS) + .border_1() + .border_dashed() + .border_color(theme.border) + .bg(theme.background) + .drag_over::(|style, _, _, cx| { + style.border_color(cx.theme().primary).bg(cx.theme().primary.opacity(TINT)) + }) + .on_drop(cx.listener(|this, paths: &ExternalPaths, window, cx| this.dropped(paths, window, cx))) + .child(Icon::new(Lucide::Upload).size(ICON_XL).text_color(theme.muted_foreground)) + .child(div().mt(rems(0.308)).text_size(TEXT_BASE).font_medium().child(t(cx, "import.dropTitle"))) + .child(div().text_size(TEXT_XS).text_color(theme.muted_foreground).child(t(cx, "import.dropHint"))) + .child( + div().mt(rems(0.769)).child( + form::field_button("import-browse") + .debug_selector(|| "import-browse".into()) + .large_with_icon(Icon::new(Lucide::FolderOpen), t(cx, "common.browse")) + .on_click(cx.listener(|this, _, window, cx| this.pick(window, cx))), + ), + ) + } + + // The file's name, then its size and what reading it found. Its folder is in the name's tooltip. + fn file_card(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme().clone(); + let running = self.running.is_some(); + let name = self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path).to_string(); + let full: SharedString = self.path.clone().into(); + let icon = match self.format { + Some(FileFormat::Json) => Lucide::Braces, + Some(FileFormat::Sql) => Lucide::FileCode, + _ => Lucide::Sheet, + }; + let mut facts: Vec = self.file_size.iter().map(|size| bytes(cx, *size as i64)).collect(); + match &self.preview { + _ if self.previewing => facts.push(t(cx, "import.reading").to_string()), + Some(preview) => { + facts.extend(preview.json_shape.map(|shape| t(cx, shape_key(shape)).to_string())); + if preview.total_rows > 0 { + let rows = count(cx, preview.total_rows as usize); + facts.push( + t_count(cx, "import.fileRows", preview.total_rows as i64, &[("rows", &rows)]).to_string(), + ); + } + } + None => {} + } + h_flex() + .id("import-file") + .debug_selector(|| "import-file".into()) + .gap(rems(0.769)) + .p(rems(0.769)) + .rounded(RADIUS) + .border_1() + .border_color(theme.border) + .bg(theme.background) + .drag_over::(|style, _, _, cx| { + style.border_color(cx.theme().primary).bg(cx.theme().primary.opacity(TINT)) + }) + .on_drop(cx.listener(|this, paths: &ExternalPaths, window, cx| this.dropped(paths, window, cx))) + .child( + div() + .flex_none() + .size(rems(2.462)) + .rounded(RADIUS) + .flex() + .items_center() + .justify_center() + .bg(theme.primary.opacity(TINT)) + .child(Icon::new(icon).size(ICON_MD).text_color(theme.primary)), + ) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap(rems(0.154)) + .child( + div() + .id("import-file-name") + .truncate() + .text_size(TEXT_BASE) + .font_medium() + .child(name) + .tooltip(move |window, cx| Tooltip::new(full.clone()).build(window, cx)), + ) + .child( + div().truncate().text_size(TEXT_XS).text_color(theme.muted_foreground).child(facts.join(" · ")), + ), + ) + .children(self.format.is_some().then(|| self.format_select(window, cx))) + .child( + Button::new("import-browse") + .debug_selector(|| "import-browse".into()) + .tool_label(t(cx, "import.change")) + .disabled(running) + .on_click(cx.listener(|this, _, window, cx| this.pick(window, cx))), + ) + } + + // Read as: the format the file is read in, detected until the user picks one. + fn format_select(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let current = self.format; + let label = current.map_or_else(SharedString::default, |format| t(cx, format_key(format))); + let this = cx.entity().downgrade(); + form::select_small("import-format", label, cx) + .debug_selector(|| "import-format".into()) + .tooltip(t(cx, "import.readAs")) + .disabled(self.running.is_some()) + .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { + for format in FORMATS { + let this = this.clone(); + let item = PopupMenuItem::new(t(cx, format_key(format))).checked(Some(format) == current); + menu = menu.item(item.on_click(move |_, window, cx| { + this.update(cx, |dialog, cx| dialog.set_format(format, window, cx)).ok(); + })); + } + menu + }) + } + + fn target_fields(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let running = self.running.is_some(); + let no_tables = self.tables.is_empty(); + let targets = form::toggle_group() + .child( + form::toggle("import-target-new", t(cx, "import.targetNew"), self.target == Target::New) + .debug_selector(|| "import-target-new".into()) + .disabled(running) + .on_click(cx.listener(|this, _, window, cx| this.set_target(Target::New, window, cx))), + ) + .child( + form::toggle("import-target-existing", t(cx, "import.targetExisting"), self.target == Target::Existing) + .debug_selector(|| "import-target-existing".into()) + .disabled(running || no_tables) + .when(no_tables, |button| button.tooltip(t(cx, "import.noTables"))) + .on_click(cx.listener(|this, _, window, cx| this.set_target(Target::Existing, window, cx))), + ); + let fields: AnyElement = match self.target { + Target::New => form::group( + t(cx, "import.newTableName"), + form::input(&self.new_table, window, cx).disabled(running), + cx, + ) + .child(form::hint(t(cx, "import.newTableHint"), cx)) + .into_any_element(), + Target::Existing => { + let this = cx.entity().downgrade(); + let (tables, current) = (self.tables.clone(), self.existing.clone()); + let table = form::select("import-existing-table", current.clone(), cx) + .debug_selector(|| "import-existing-table".into()) + .disabled(running) + .select_menu(window, cx, move |mut menu: PopupMenu, _, _| { + for table in tables.clone() { + let this = this.clone(); + let checked = table == current; + menu = menu.item(PopupMenuItem::new(table.clone()).checked(checked).on_click( + move |_, window, cx| { + this.update(cx, |dialog, cx| dialog.set_existing(table.clone(), window, cx)).ok(); + }, + )); + } + menu.scrollable(true) + }); + form::group(t(cx, "import.existingTable"), table, cx).into_any_element() + } + }; + form::section(cx).child(form::group(t(cx, "import.into"), targets, cx)).child(fields) + } +} diff --git a/crates/barsql-ui/src/import_dialog/preview_step.rs b/crates/barsql-ui/src/import_dialog/preview_step.rs new file mode 100644 index 0000000..ec197b2 --- /dev/null +++ b/crates/barsql-ui/src/import_dialog/preview_step.rs @@ -0,0 +1,201 @@ +use barsql_app::{FileFormat, ImportPreview}; +use barsql_io::json_import::SAMPLE_ROWS; +use gpui_kit::assets::IconName as Lucide; +use gpui_kit::component::menu::{PopupMenu, PopupMenuItem}; +use gpui_kit::component::scroll::ScrollbarAxis; +use gpui_kit::component::{ActiveTheme, Disableable, Icon, StyledExt, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +use super::{ImportDialog, shape_key}; +use crate::form::{self, SelectMenu}; +use crate::i18n::{count, t, t_count, t_with}; +use crate::modal; +use crate::scrollbars::HoverScrollbar as _; +use crate::tokens::{ICON_XS, RADIUS, TEXT_SM, TEXT_XS}; + +const DELIMITERS: [(&str, &str); 5] = [ + ("", "import.delimiterAuto"), + (",", "import.delimiterComma"), + (";", "import.delimiterSemicolon"), + ("\t", "import.delimiterTab"), + ("|", "import.delimiterPipe"), +]; +// Enough to check how the file reads. +const GRID_ROWS: usize = 50; +const GRID_COLUMN_REM: f32 = 9.231; + +impl ImportDialog { + // The options stay put and the rows scroll under them. + pub(super) fn preview_step(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let options: AnyElement = match self.format { + Some(FileFormat::Json) => self.json_facts(cx).into_any_element(), + _ => self.csv_options(window, cx).into_any_element(), + }; + let theme = cx.theme().clone(); + let not_utf8 = self.preview.as_ref().is_some_and(|preview| preview.not_utf8); + let rows: AnyElement = if self.previewing { + form::loading_state(t(cx, "import.reading"), cx).into_any_element() + } else if let Some(error) = &self.preview_error { + form::error(error.clone(), cx).into_any_element() + } else if let Some(preview) = &self.preview { + self.grid(preview, cx).into_any_element() + } else { + div().into_any_element() + }; + modal::body() + .flex_1() + .min_h_0() + .child(options) + .when(not_utf8, |el| { + el.child( + form::alert(theme.warning) + .debug_selector(|| "import-not-utf8".into()) + .flex_none() + .text_color(theme.warning) + .child(t(cx, "import.notUtf8")), + ) + }) + .child(rows) + } + + fn csv_options(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let running = self.running.is_some(); + let this = cx.entity().downgrade(); + let current = self.delimiter; + let label = DELIMITERS.iter().find(|(value, _)| *value == current).map_or("", |(_, key)| key); + let delimiter = form::select("import-delimiter", t(cx, label), cx) + .debug_selector(|| "import-delimiter".into()) + .disabled(running) + .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { + for (value, key) in DELIMITERS { + let this = this.clone(); + menu = menu.item(PopupMenuItem::new(t(cx, key)).checked(value == current).on_click( + move |_, window, cx| { + this.update(cx, |dialog, cx| { + dialog.delimiter = value; + dialog.schedule_preview(window, cx); + cx.notify(); + }) + .ok(); + }, + )); + } + menu + }); + let fluid = |children: Vec| { + h_flex() + .flex_wrap() + .items_start() + .gap(rems(0.769)) + .children(children.into_iter().map(|child| div().flex_1().min_w_0().child(child))) + }; + // What was sniffed, beside the automatic pick. + let sniffed = self.preview.as_ref().filter(|_| current.is_empty()).map(|preview| { + let shown = if preview.delimiter == "\t" { "\\t".to_string() } else { preview.delimiter.clone() }; + form::hint(t_with(cx, "import.detectedDelimiter", &[("delimiter", &shown)]), cx) + }); + v_flex() + .flex_none() + .gap(rems(0.923)) + .child(fluid(vec![ + form::group(t(cx, "import.delimiter"), delimiter, cx).children(sniffed).into_any_element(), + form::group(t(cx, "import.skipRows"), form::input(&self.skip_rows, window, cx).disabled(running), cx) + .into_any_element(), + form::group( + t(cx, "import.nullLiteral"), + form::input(&self.null_literal, window, cx).disabled(running), + cx, + ) + .into_any_element(), + ])) + .child( + h_flex() + .flex_wrap() + .gap(rems(1.538)) + .child(self.checkbox( + "import-header", + "import.hasHeader", + self.has_header, + |d, v| d.has_header = v, + true, + cx, + )) + .child(self.checkbox( + "import-trim", + "import.trimSpace", + self.trim_space, + |d, v| d.trim_space = v, + true, + cx, + )), + ) + } + + // What reading found: the shape, the rows and the keys. JSON has no options to set. + fn json_facts(&self, cx: &App) -> impl IntoElement { + let theme = cx.theme(); + let mut facts = Vec::new(); + if let Some(preview) = &self.preview { + facts.extend(preview.json_shape.map(|shape| t(cx, shape_key(shape)).to_string())); + if preview.total_rows > 0 { + let rows = count(cx, preview.total_rows as usize); + facts.push(t_count(cx, "import.fileRows", preview.total_rows as i64, &[("rows", &rows)]).to_string()); + } + let keys = count(cx, preview.columns.len()); + facts.push(t_count(cx, "import.keys", preview.columns.len() as i64, &[("keys", &keys)]).to_string()); + } + let sampled = self.preview.as_ref().is_some_and(|preview| preview.sampled); + v_flex() + .flex_none() + .gap(rems(0.308)) + .child( + h_flex() + .gap(rems(0.462)) + .text_size(TEXT_SM) + .text_color(theme.muted_foreground) + .child(Icon::new(Lucide::Braces).size(ICON_XS)) + .child(facts.join(" · ")), + ) + .when(sampled, |el| { + el.child(form::hint(t_with(cx, "import.sampled", &[("rows", &count(cx, SAMPLE_ROWS))]), cx).mt_0()) + }) + } + + // The first rows as the import will read them, in fixed-width columns that scroll both ways. + fn grid(&self, preview: &ImportPreview, cx: &App) -> impl IntoElement { + let theme = cx.theme(); + let width = rems(GRID_COLUMN_REM * preview.columns.len() as f32); + let cell = || div().flex_none().w(rems(GRID_COLUMN_REM)).px(rems(0.615)).py(rems(0.308)).truncate(); + let header = h_flex().w(width).bg(theme.secondary).border_b_1().border_color(theme.border).children( + preview.columns.iter().map(|column| { + cell().text_size(TEXT_XS).font_semibold().text_color(theme.muted_foreground).child(column.clone()) + }), + ); + let rows = preview.rows.iter().take(GRID_ROWS).enumerate().map(|(ix, row)| { + h_flex() + .w(width) + .when(ix > 0, |el| el.border_t_1().border_color(theme.border)) + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_XS) + .children(row.iter().map(|value| cell().child(value.clone()))) + }); + let table = div() + .id("import-grid") + .debug_selector(|| "import-grid".into()) + .size_full() + .overflow_scroll() + .track_scroll(&self.grid_scroll) + .child(v_flex().w(width).child(header).children(rows)); + div() + .relative() + .flex_1() + .min_h_0() + .rounded(RADIUS) + .border_1() + .border_color(theme.border) + .overflow_hidden() + .child(table) + .hover_scrollbar(&self.grid_scroll, ScrollbarAxis::Both) + } +} diff --git a/crates/barsql-ui/src/import_dialog/run_step.rs b/crates/barsql-ui/src/import_dialog/run_step.rs new file mode 100644 index 0000000..69f798a --- /dev/null +++ b/crates/barsql-ui/src/import_dialog/run_step.rs @@ -0,0 +1,215 @@ +use barsql_app::{ImportProgress, ImportResult}; +use gpui_kit::assets::IconName as Lucide; +use gpui_kit::component::scroll::ScrollbarAxis; +use gpui_kit::component::{ActiveTheme, Icon, StyledExt, h_flex, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; +use gpui_kit::*; + +use super::{ImportDialog, Target, format_key, shape_key}; +use crate::form; +use crate::i18n::{I18n, count, t, t_count, t_with}; +use crate::modal; +use crate::plan_tree::format_ms; +use crate::scrollbars::HoverScrollbar as _; +use crate::tokens::{ICON_XL, ICON_XS, RADIUS, TEXT_MD, TEXT_SM, TEXT_XS}; + +impl ImportDialog { + pub(super) fn run_step(&mut self, cx: &mut Context) -> impl IntoElement { + let body = modal::body(); + let body = match self.result.clone() { + // A clean run sits in the middle. A list of what failed starts at the top. + Some(result) if result.errors.is_empty() && result.ignored_keys.is_empty() => { + body.justify_center().child(self.result_view(&result, cx)) + } + Some(result) => body.child(self.result_view(&result, cx)), + None if self.running.is_some() => body.child(self.summary(cx)).child(self.progress_view(cx)), + None => { + let empties = self.is_table() && self.target == Target::Existing; + body.child(self.summary(cx)) + .when(empties, |el| { + el.child(self.option( + "import-truncate", + ("import.truncate", "import.truncateHint"), + self.truncate, + |d, v| d.truncate = v, + cx, + )) + }) + .child(self.option( + "import-stop", + ("import.stopOnError", "import.stopOnErrorHint"), + self.stop_on_error, + |d, v| d.stop_on_error = v, + cx, + )) + .when_some(self.error.clone(), |el, error| el.child(form::error(error, cx))) + } + }; + modal::scroll_body(body) + } + + // A run option with its hint under the label. + fn option( + &self, + id: &'static str, + (key, hint): (&str, &str), + checked: bool, + set: fn(&mut Self, bool), + cx: &mut Context, + ) -> impl IntoElement { + v_flex().child(self.checkbox(id, key, checked, set, false, cx)).child(form::hint(t(cx, hint), cx).pl(rems(2.))) + } + + // What the click will do, a line per part. + fn summary(&self, cx: &App) -> impl IntoElement { + let theme = cx.theme(); + let line = |label: SharedString, value: String| { + h_flex() + .items_start() + .gap(rems(0.923)) + .child(div().flex_none().w(rems(6.154)).text_color(theme.muted_foreground).child(label)) + .child(div().flex_1().min_w_0().truncate().child(value)) + }; + let name = self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path); + let read_as = match self.preview.as_ref().and_then(|preview| preview.json_shape) { + Some(shape) => t(cx, shape_key(shape)), + None => self.format.map_or_else(Default::default, |format| t(cx, format_key(format))), + }; + let mut lines = vec![line(t(cx, "import.summaryFile"), format!("{name} · {read_as}"))]; + if self.is_table() { + let table = self.qualified(&self.target_table(cx)); + let into = match self.target { + Target::New => format!("{table} · {}", t(cx, "import.summaryNewTable")), + Target::Existing => table, + }; + lines.push(line(t(cx, "import.summaryInto"), into)); + let rows = self.preview.as_ref().map_or(0, |preview| preview.total_rows); + let rows = + if rows > 0 { count(cx, rows as usize) } else { t(cx, "import.summaryRowsUncounted").to_string() }; + lines.push(line(t(cx, "import.summaryRows"), rows)); + let total = self.preview.as_ref().map_or(0, |preview| preview.columns.len()); + let (mapped, total) = (count(cx, self.mapped_count(cx)), count(cx, total)); + let mapped = t_with(cx, "import.mapped", &[("mapped", &mapped), ("total", &total)]); + lines.push(line(t(cx, "import.summaryColumns"), mapped.to_string())); + } else { + lines.push(line(t(cx, "import.summaryRunsOn"), self.connection.name.clone())); + } + let emptied = self.deleting(); + v_flex() + .debug_selector(|| "import-summary".into()) + .gap(rems(0.615)) + .p(rems(0.923)) + .rounded(RADIUS) + .border_1() + .border_color(theme.border) + .bg(theme.background) + .text_size(TEXT_SM) + .children(lines) + .when(emptied, |el| { + el.child( + h_flex() + .debug_selector(|| "import-emptied".into()) + .gap(rems(0.462)) + .text_color(theme.danger) + .child(Icon::new(Lucide::TriangleAlert).size(ICON_XS)) + .child(t(cx, "import.summaryEmptied")), + ) + }) + } + + fn progress_view(&self, cx: &App) -> impl IntoElement { + let p = self.progress.clone().unwrap_or(ImportProgress { + total_bytes: self.preview.as_ref().map_or(0, |p| p.total_bytes as i64), + total_rows: if self.is_table() { self.preview.as_ref().map_or(0, |p| p.total_rows as i64) } else { 0 }, + ..Default::default() + }); + let n = |value: i64| count(cx, value.max(0) as usize); + let (label, value, max) = if !self.is_table() { + ( + t_with(cx, "import.progressStatements", &[("done", &n(p.processed)), ("total", &n(p.total_bytes))]), + p.processed, + p.total_bytes, + ) + } else if p.total_rows > 0 { + let done = p.processed.min(p.total_rows); + ( + t_with(cx, "import.progressRowsOf", &[("done", &n(done)), ("total", &n(p.total_rows))]), + done, + p.total_rows, + ) + } else { + (t_with(cx, "import.progressRows", &[("rows", &n(p.processed))]), p.bytes_read, p.total_bytes) + }; + form::progress("import-progress", label, if max > 0 { value as f32 / max as f32 } else { 0. }, cx) + } + + // A headline with where the rows went and how long it took, then what didn't load. + fn result_view(&self, result: &ImportResult, cx: &App) -> impl IntoElement { + let theme = cx.theme(); + let n = |value: i64| count(cx, value.max(0) as usize); + let headline = if self.is_table() { + t_count(cx, "import.resultRows", result.inserted, &[("rows", &n(result.inserted))]) + } else { + t_count(cx, "import.resultStatements", result.statements, &[("statements", &n(result.statements))]) + }; + let mut details: Vec = self.loaded_table.iter().map(|table| self.qualified(table)).collect(); + details.push(format_ms(Some(result.duration_ms as f64), cx.global::().lang())); + if result.skipped > 0 { + details.push(t_count(cx, "import.skipped", result.skipped, &[("skipped", &n(result.skipped))]).to_string()); + } + let (icon, color) = match result.cancelled || result.skipped > 0 { + true => (Lucide::CircleAlert, theme.warning), + false => (Lucide::CircleCheck, theme.success), + }; + let errors = (!result.errors.is_empty()).then(|| { + let list = v_flex() + .id("import-errors") + .max_h(px(140.)) + .overflow_y_scroll() + .track_scroll(&self.errors_scroll) + .px(rems(0.769)) + .py(rems(0.615)) + .font_family(theme.mono_font_family.clone()) + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .children(result.errors.iter().map(|error| div().child(format!("• {error}")))); + div() + .relative() + .w_full() + .rounded(RADIUS) + .border_1() + .border_color(theme.border) + .bg(theme.background) + .child(list) + .hover_scrollbar(&self.errors_scroll, ScrollbarAxis::Vertical) + }); + let ignored = (!result.ignored_keys.is_empty()).then(|| { + form::hint(t_with(cx, "import.ignoredKeys", &[("keys", &result.ignored_keys.join(", "))]), cx) + .debug_selector(|| "import-ignored-keys".into()) + }); + v_flex() + .debug_selector(|| "import-result".into()) + .gap(rems(0.923)) + .child( + v_flex() + .items_center() + .text_center() + .gap(rems(0.462)) + .pt(rems(1.231)) + .pb(rems(0.462)) + .child(Icon::new(icon).size(ICON_XL).text_color(color)) + .child(div().text_size(TEXT_MD).font_semibold().child(headline)) + .child(div().text_size(TEXT_SM).text_color(theme.muted_foreground).child(details.join(" · "))) + .when(result.cancelled, |el| { + el.child( + div() + .text_size(TEXT_XS) + .text_color(theme.muted_foreground) + .child(t(cx, "import.cancelledNote")), + ) + }), + ) + .children(errors) + .children(ignored) + } +} diff --git a/crates/barsql-ui/src/import_dialog/tests.rs b/crates/barsql-ui/src/import_dialog/tests.rs new file mode 100644 index 0000000..6745707 --- /dev/null +++ b/crates/barsql-ui/src/import_dialog/tests.rs @@ -0,0 +1,416 @@ +use std::cell::{Cell, RefCell}; +use std::path::Path; +use std::rc::Rc; + +use barsql_app::{FileFormat, ImportDone, ImportEvent, ImportResult}; +use barsql_core::Value; +use gpui_kit::component::Root; +use gpui_kit::{AppContext as _, Entity, ExternalPaths, FileDropEvent, TestAppContext, VisualTestContext}; + +use super::{Hooks, ImportDialog, Step, Target, fits, table_name_for}; +use crate::i18n::I18n; +use crate::test_support::{Env, settle}; + +struct Fixture { + dialog: Entity, + imported: Rc>, + opened: Rc>>, +} + +fn open<'a>(env: &Env, cx: &'a mut TestAppContext) -> (Fixture, &'a mut VisualTestContext) { + let connection = env.connection.clone(); + let (imported, opened) = (Rc::new(Cell::new(0)), Rc::new(RefCell::new(Vec::new()))); + let slot = Rc::new(RefCell::new(None)); + let (out, count, tables) = (slot.clone(), imported.clone(), opened.clone()); + let window = cx.add_window(move |window, cx| { + let hooks = Hooks { + imported: Rc::new(move |_| count.set(count.get() + 1)), + open: Rc::new(move |schema, table, _, _| tables.borrow_mut().push((schema, table))), + }; + let view = + cx.new(|cx| ImportDialog::new(connection, "main".into(), vec!["things".into()], None, hooks, window, cx)); + *out.borrow_mut() = Some(view.clone()); + Root::new(view, window, cx) + }); + let cx = VisualTestContext::from_window(window.into(), cx).into_mut(); + let dialog = slot.borrow_mut().take().unwrap(); + (Fixture { dialog, imported, opened }, cx) +} + +fn file(dir: &tempfile::TempDir, name: &str, content: impl AsRef<[u8]>) -> std::path::PathBuf { + let path = dir.path().join(name); + std::fs::write(&path, content).unwrap(); + path +} + +// Picks the file and waits until it's read. +fn choose(f: &Fixture, cx: &mut VisualTestContext, path: &Path) { + let path = path.display().to_string(); + f.dialog.update_in(cx, |dialog, window, cx| dialog.choose(path, window, cx)); + settle(cx, |cx| f.dialog.read_with(cx, |d, _| !d.previewing && d.format.is_some())); +} + +fn run(f: &Fixture, cx: &mut VisualTestContext) -> ImportResult { + f.dialog.update_in(cx, |dialog, window, cx| dialog.run(window, cx)); + settle(cx, |cx| f.dialog.read_with(cx, |d, _| d.running.is_none() && (d.result.is_some() || d.error.is_some()))); + f.dialog + .read_with(cx, |d, _| d.result.clone()) + .unwrap_or_else(|| panic!("{:?}", f.dialog.read_with(cx, |d, _| d.error.clone()))) +} + +fn query(env: &Env, sql: &str) -> Vec> { + env.runtime.block_on(env.bar.execute_query(&env.connection.id, sql)).unwrap().rows +} + +fn step(f: &Fixture, cx: &mut VisualTestContext) -> Step { + f.dialog.read_with(cx, |d, _| d.step) +} + +fn draw(cx: &mut VisualTestContext) { + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); +} + +fn enter(f: &Fixture, cx: &mut VisualTestContext) { + f.dialog.update_in(cx, |dialog, window, cx| dialog.enter(window, cx)); +} + +#[gpui_kit::test] +fn an_import_that_hit_a_bug_says_so_in_the_ui_language(cx: &mut TestAppContext) { + let env = Env::new(cx); + cx.update(|cx| cx.set_global(I18n::new("de"))); + let (f, cx) = open(&env, cx); + let done = ImportDone { error: "BarSQL hit a bug.".into(), bug: true, ..Default::default() }; + f.dialog.update(cx, |dialog, cx| dialog.apply(ImportEvent::Done(done), cx)); + let said = "In BarSQL ist ein interner Fehler aufgetreten. Details stehen in crash.log im Datenordner."; + assert_eq!(f.dialog.read_with(cx, |dialog, _| dialog.error.clone()).as_deref(), Some(said)); +} + +#[gpui_kit::test] +fn a_csv_previews_then_loads_into_a_new_table(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people list.csv", "name,age,active\nann,31,true\nbob,,false\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + let (format, columns, types, table) = f.dialog.read_with(cx, |d, cx| { + let preview = d.preview.clone().unwrap(); + (d.format, preview.columns, d.column_types.clone(), d.new_table.read(cx).value().to_string()) + }); + assert_eq!(format, Some(FileFormat::Csv)); + assert_eq!(columns, ["name", "age", "active"]); + assert_eq!(types, ["text", "int", "bool"]); + assert_eq!(table, "people_list"); + let result = run(&f, cx); + assert_eq!((result.inserted, result.skipped, result.cancelled), (2, 0, false)); + assert_eq!(f.imported.get(), 1); + assert_eq!( + query(&env, "SELECT name, age FROM people_list ORDER BY name"), + [vec![Value::Text("ann".into()), Value::Int(31)], vec![Value::Text("bob".into()), Value::Null]] + ); +} + +#[gpui_kit::test] +fn a_json_file_loads_its_nested_values_into_a_json_column(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "crew.json", r#"[{"id": 1, "who": {"name": "ann"}}, {"id": 2, "who": null}]"#); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + let (format, types) = f.dialog.read_with(cx, |d, _| (d.format, d.column_types.clone())); + assert_eq!((format, types), (Some(FileFormat::Json), vec!["int".to_string(), "json".to_string()])); + assert_eq!(run(&f, cx).inserted, 2); + assert_eq!( + query(&env, "SELECT who FROM crew ORDER BY id"), + [vec![Value::Text("{\"name\": \"ann\"}".into())], vec![Value::Null]] + ); +} + +// Excel saves CSV in Windows-1252, where é is one byte that isn't UTF-8. +#[gpui_kit::test] +fn a_csv_that_isnt_utf8_says_so_in_the_preview(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "cafes.csv", b"name\ncaf\xe9\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + assert!(f.dialog.read_with(cx, |d, _| d.preview.as_ref().is_some_and(|p| p.not_utf8))); + f.dialog.update(cx, |dialog, cx| dialog.go(Step::Preview, cx)); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!(cx.debug_bounds("import-not-utf8").is_some(), "the preview warns"); +} + +#[gpui_kit::test] +fn a_sql_script_skips_the_table_steps_and_runs_its_statements(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let script = + "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT);\nINSERT INTO notes (body) VALUES ('a'), ('b');\n"; + let path = file(&dir, "seed.sql", script); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + let steps = f.dialog.read_with(cx, |d, _| d.steps().to_vec()); + assert_eq!(steps, [Step::File, Step::Import]); + let result = run(&f, cx); + assert_eq!((result.statements, result.skipped), (2, 0)); + assert_eq!(f.imported.get(), 1); + assert_eq!(query(&env, "SELECT count(*) FROM notes")[0][0], Value::Int(2)); +} + +#[gpui_kit::test] +fn next_and_back_walk_the_steps_the_file_has_reached(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people.csv", "id,name\n1,ann\n"); + let (f, cx) = open(&env, cx); + assert_eq!(step(&f, cx), Step::File); + assert_eq!(f.dialog.read_with(cx, |d, _| d.next_step()), None, "nothing to preview yet"); + choose(&f, cx, &path); + for want in [Step::Preview, Step::Columns, Step::Import] { + f.dialog.update(cx, |dialog, cx| dialog.next(cx)); + assert_eq!(step(&f, cx), want); + } + assert_eq!(f.dialog.read_with(cx, |d, _| d.next_step()), None); + let back = f.dialog.read_with(cx, |d, _| d.back_step()); + assert_eq!(back, Some(Step::Columns)); + f.dialog.update(cx, |dialog, cx| dialog.go(Step::File, cx)); + assert_eq!(step(&f, cx), Step::File); +} + +// Next leads up to the last step, and only there does the footer import, so the summary is always seen first. +#[gpui_kit::test] +fn only_the_last_step_imports(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people.csv", "id,name\n1,ann\n2,bob\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + for _ in 0..3 { + draw(cx); + let at = step(&f, cx); + assert!(cx.debug_bounds("import-next").is_some(), "Next on {at:?}"); + assert!(cx.debug_bounds("import-run").is_none(), "no Import on {at:?}"); + f.dialog.update(cx, |dialog, cx| dialog.next(cx)); + } + assert_eq!(step(&f, cx), Step::Import); + draw(cx); + assert!(cx.debug_bounds("import-run").is_some() && cx.debug_bounds("import-next").is_none()); + assert_eq!(run(&f, cx).inserted, 2); +} + +// The delete is picked beside the button it runs before, which then names it, and the summary warns. +#[gpui_kit::test] +fn deleting_existing_rows_is_picked_beside_the_import_and_named_on_its_button(cx: &mut TestAppContext) { + let env = Env::new(cx); + for sql in ["CREATE TABLE crew (id INTEGER, name TEXT)", "INSERT INTO crew VALUES (1, 'old')"] { + env.runtime.block_on(env.bar.execute_query(&env.connection.id, sql)).unwrap(); + } + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "crew.csv", "id,name\n2,new\n"); + let (f, cx) = open(&env, cx); + f.dialog.update_in(cx, |dialog, window, cx| { + dialog.set_target(Target::Existing, window, cx); + dialog.set_existing("crew".into(), window, cx); + }); + choose(&f, cx, &path); + draw(cx); + assert!(cx.debug_bounds("import-truncate").is_none(), "not among the File step's fields"); + f.dialog.update(cx, |dialog, cx| dialog.go(Step::Import, cx)); + draw(cx); + assert_eq!(f.dialog.read_with(cx, |d, cx| d.run_label(cx)).as_ref(), "Import 1 row"); + assert!(cx.debug_bounds("import-emptied").is_none()); + let tick = cx.debug_bounds("import-truncate").expect("Delete existing rows first").center(); + cx.simulate_click(tick, gpui_kit::Modifiers::none()); + draw(cx); + assert_eq!(f.dialog.read_with(cx, |d, cx| d.run_label(cx)).as_ref(), "Delete rows and import"); + assert!(cx.debug_bounds("import-emptied").is_some(), "the summary warns"); + assert_eq!(run(&f, cx).inserted, 1); + assert_eq!(query(&env, "SELECT name FROM crew"), [vec![Value::Text("new".into())]]); +} + +#[gpui_kit::test] +fn read_as_reads_the_file_again_that_way(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "rows.txt", "{\"a\":1}\n{\"a\":2}\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + assert_eq!(f.dialog.read_with(cx, |d, _| d.format), Some(FileFormat::Json)); + f.dialog.update_in(cx, |dialog, window, cx| dialog.set_format(FileFormat::Csv, window, cx)); + settle(cx, |cx| { + f.dialog.read_with(cx, |d, _| !d.previewing && d.preview.as_ref().is_some_and(|p| p.json_shape.is_none())) + }); + assert_eq!(f.dialog.read_with(cx, |d, _| d.format), Some(FileFormat::Csv)); + f.dialog.update_in(cx, |dialog, window, cx| dialog.set_format(FileFormat::Sql, window, cx)); + settle(cx, |cx| f.dialog.read_with(cx, |d, _| !d.previewing)); + assert_eq!(f.dialog.read_with(cx, |d, _| (d.preview.is_none(), d.steps().len())), (true, 2)); +} + +#[gpui_kit::test] +fn a_file_dropped_on_the_dialog_is_chosen(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "dropped.csv", "id\n1\n"); + let (f, cx) = open(&env, cx); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let position = cx.debug_bounds("import-drop").expect("the drop zone").center(); + let paths = ExternalPaths([path.clone()].into_iter().collect()); + cx.simulate_event(FileDropEvent::Entered { position, paths }); + cx.simulate_event(FileDropEvent::Pending { position }); + cx.simulate_event(FileDropEvent::Submit { position }); + settle(cx, |cx| f.dialog.read_with(cx, |d, _| d.format.is_some() && !d.previewing)); + assert_eq!(f.dialog.read_with(cx, |d, _| d.path.clone()), path.display().to_string()); +} + +#[gpui_kit::test] +fn open_table_opens_the_table_the_rows_went_into(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people.csv", "id,name\n1,ann\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + assert_eq!(f.dialog.read_with(cx, |d, cx| d.dismiss_label(cx)).as_ref(), "Cancel"); + run(&f, cx); + assert_eq!(f.dialog.read_with(cx, |d, cx| d.dismiss_label(cx)).as_ref(), "Close"); + f.dialog.update_in(cx, |dialog, window, cx| dialog.open_table(window, cx)); + assert_eq!(*f.opened.borrow(), [("main".to_string(), "people".to_string())]); +} + +// The table the first file made exists now, so the next file goes into it unless the user says otherwise. +#[gpui_kit::test] +fn another_file_goes_into_the_table_just_made(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people.csv", "id,name\n1,ann\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + run(&f, cx); + f.dialog.update_in(cx, |dialog, window, cx| dialog.again(window, cx)); + let state = + f.dialog.read_with(cx, |d, _| (d.step, d.path.clone(), d.target, d.existing.clone(), d.result.is_none())); + assert_eq!(state, (Step::File, String::new(), Target::Existing, "people".to_string(), true)); + let second = file(&dir, "more.csv", "id,name\n2,bob\n"); + choose(&f, cx, &second); + assert_eq!(run(&f, cx).inserted, 1); + assert_eq!(query(&env, "SELECT count(*) FROM people")[0][0], Value::Int(2)); +} + +// Enter does what the blue button does: on a step at a time, then the import once it can run. +#[gpui_kit::test] +fn enter_follows_the_blue_button(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people.csv", "id,name\n1,ann\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + for want in [Step::Preview, Step::Columns, Step::Import] { + enter(&f, cx); + assert_eq!(step(&f, cx), want, "a ready import still goes a step at a time"); + } + f.dialog + .update_in(cx, |dialog, window, cx| dialog.new_table.update(cx, |input, cx| input.set_value("", window, cx))); + enter(&f, cx); + cx.run_until_parked(); + assert!(f.dialog.read_with(cx, |d, _| d.running.is_none() && d.result.is_none()), "no table name, no import"); + f.dialog.update_in(cx, |dialog, window, cx| { + dialog.new_table.update(cx, |input, cx| input.set_value("crew", window, cx)) + }); + enter(&f, cx); + settle(cx, |cx| f.dialog.read_with(cx, |d, _| d.result.is_some())); + assert_eq!(query(&env, "SELECT name FROM crew")[0][0], Value::Text("ann".into())); +} + +// Ticking an option that doesn't change how the file reads keeps the columns as the user mapped them. +#[gpui_kit::test] +fn ticking_a_run_option_keeps_the_mapping(cx: &mut TestAppContext) { + let env = Env::new(cx); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "people.csv", "id,name\n1,ann\n"); + let (f, cx) = open(&env, cx); + choose(&f, cx, &path); + f.dialog + .update_in(cx, |dialog, window, cx| dialog.mapping[1].update(cx, |input, cx| input.set_value("", window, cx))); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + f.dialog.update(cx, |dialog, cx| dialog.go(Step::Import, cx)); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let stop = cx.debug_bounds("import-stop").expect("Stop at the first error").center(); + cx.simulate_click(stop, gpui_kit::Modifiers::none()); + // Past the re-read's debounce, had the click asked for one. + cx.executor().advance_clock(super::PREVIEW_DEBOUNCE * 2); + settle(cx, |cx| f.dialog.read_with(cx, |d, _| !d.previewing)); + let mapped = f.dialog.read_with(cx, |d, cx| (d.stop_on_error, d.mapping_values(cx))); + assert_eq!(mapped, (true, vec!["id".to_string(), String::new()])); +} + +// What a column's sampled values look like against the type of the column they load into. +#[test] +fn values_fit_columns_that_can_hold_them() { + let fit = [ + ("int", "INTEGER"), + ("int", "numeric(10,2)"), + ("int", "Nullable(Int32)"), + ("float", "double precision"), + ("bool", "boolean"), + ("bool", "tinyint(1)"), + ("date", "timestamp without time zone"), + ("timestamp", "datetime2"), + ("text", "character varying(50)"), + ("int", "text"), + ("text", "uuid"), + ("json", "jsonb"), + ("json", "text"), + ]; + for (inferred, column) in fit { + assert!(fits(inferred, column), "{inferred} into {column}"); + } + let misfit = [ + ("text", "integer"), + ("float", "bigint"), + ("text", "date"), + ("timestamp", "date"), + ("text", "bool"), + ("json", "integer"), + ]; + for (inferred, column) in misfit { + assert!(!fits(inferred, column), "{inferred} into {column}"); + } +} + +// A file's ID loads into the table's id. A column the table lacks is flagged until it's skipped. +#[gpui_kit::test] +fn an_existing_tables_columns_match_the_files_whatever_their_case(cx: &mut TestAppContext) { + let env = Env::new(cx); + let create = "CREATE TABLE crew (id INTEGER PRIMARY KEY, name TEXT)"; + env.runtime.block_on(env.bar.execute_query(&env.connection.id, create)).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = file(&dir, "more.csv", "ID,Name,Extra\n9001,nine thousand one,x\n"); + let (f, cx) = open(&env, cx); + f.dialog.update_in(cx, |dialog, window, cx| { + dialog.set_target(Target::Existing, window, cx); + dialog.set_existing("crew".into(), window, cx); + }); + choose(&f, cx, &path); + let mapped = |cx: &mut VisualTestContext| f.dialog.read_with(cx, |d, cx| d.mapping_values(cx)); + settle(cx, |cx| mapped(cx).first().is_some_and(|first| first == "id")); + assert_eq!(mapped(cx), ["id", "name", "Extra"]); + let fits = f.dialog.read_with(cx, |d, cx| (0..3).map(|ix| d.fit(ix, cx)).collect::>()); + assert_eq!(fits, [Some(true), Some(true), Some(false)], "Extra is no column of crew"); + f.dialog + .update_in(cx, |dialog, window, cx| dialog.mapping[2].update(cx, |input, cx| input.set_value("", window, cx))); + assert_eq!(run(&f, cx).inserted, 1); + assert_eq!(query(&env, "SELECT name FROM crew WHERE id = 9001"), [vec![Value::Text("nine thousand one".into())]]); +} + +#[test] +fn file_names_become_table_names() { + assert_eq!(table_name_for("/data/Sales 2024.csv"), "Sales_2024"); + assert_eq!(table_name_for("C:\\exports\\orders.v2.tsv"), "orders_v2"); + assert_eq!(table_name_for("/logs/events.jsonl"), "events"); + assert_eq!(table_name_for("/tmp/.hidden"), ""); + assert_eq!(table_name_for("plain"), "plain"); + assert_eq!(table_name_for("file."), "file_"); +} diff --git a/crates/barsql-ui/src/scenarios/import.rs b/crates/barsql-ui/src/scenarios/import.rs index a7998ea..b3047b7 100644 --- a/crates/barsql-ui/src/scenarios/import.rs +++ b/crates/barsql-ui/src/scenarios/import.rs @@ -4,7 +4,7 @@ use gpui_kit::{Entity, TestAppContext}; use super::driver::{Driver, open}; use crate::file_dialogs::Stub; -use crate::import_dialog::{ImportDialog, Opened, Shown}; +use crate::import_dialog::{ImportDialog, Opened, Shown, Step}; const IMPORT_INTO_TABLE: usize = 5; @@ -25,15 +25,22 @@ fn prepared<'a>(cx: &'a mut TestAppContext, seed: &str) -> Driver<'a> { app } -// Stub makes the file picker return `path`. +// Stub makes the file picker return `path`. Waits until the file is read. fn browse(app: &mut Driver, path: &Path) { app.cx.update(|_, cx| cx.set_global(Stub(Some(path.to_path_buf())))); app.click("import-browse"); let dialog = dialog(app); - app.settle(|cx| cx.update(|_, cx| dialog.read(cx).shown(cx).preview_rows.is_some())); + app.settle(|cx| cx.update(|_, cx| dialog.read(cx).shown(cx).read)); } +// Next up to the last step, whose button imports. fn import(app: &mut Driver) -> (i64, i64) { + for _ in 0..3 { + if app.shown("import-run") { + break; + } + app.click("import-next"); + } app.click("import-run"); let dialog = dialog(app); app.settle(|cx| { @@ -51,26 +58,39 @@ fn toolbar_import(app: &mut Driver) { } #[gpui_kit::test] -fn the_toolbar_import_opens_on_csv_with_its_parse_options(cx: &mut TestAppContext) { +fn the_toolbar_import_opens_on_the_file_step(cx: &mut TestAppContext) { let mut app = open(cx); app.connect(); toolbar_import(&mut app); assert!(app.dialog_open()); let state = shown(&mut app); - assert!(state.csv && state.has_header && !state.can_run); - assert!(app.shown("import-delimiter") && app.shown("import-header")); + assert!(state.step == Step::File && state.format.is_none() && state.has_header && !state.can_run); + assert!(app.shown("import-drop") && app.shown("import-target-new")); + assert!(!app.shown("import-delimiter"), "the parse options wait for the Preview step"); } #[gpui_kit::test] -fn sql_mode_hides_the_csv_parse_options(cx: &mut TestAppContext) { +fn a_sql_file_goes_from_its_file_straight_to_the_import(cx: &mut TestAppContext) { let mut app = open(cx); app.connect(); toolbar_import(&mut app); - app.click("import-kind-sql"); - assert!(!app.shown("import-delimiter") && !app.shown("import-header")); - assert!(app.shown("import-stop-sql"), "Stop at the first error"); - app.click("import-kind-csv"); - assert!(app.shown("import-delimiter")); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("seed.sql"); + std::fs::write( + &path, + "CREATE TABLE e2e_seeded (id INTEGER); +INSERT INTO e2e_seeded VALUES (1); +", + ) + .unwrap(); + browse(&mut app, &path); + assert!(!app.shown("import-target-new"), "a script loads no table of its own"); + assert!(app.shown("import-step-1") && !app.shown("import-step-2"), "File and Import, nothing between"); + app.click("import-next"); + assert_eq!(shown(&mut app).step, Step::Import); + assert!(app.shown("import-stop"), "Stop at the first error"); + assert_eq!(import(&mut app), (1, 0), "the INSERT's row"); + assert_eq!(app.query("SELECT count(*) FROM e2e_seeded")[0][0], barsql_core::Value::Int(1)); } #[gpui_kit::test] @@ -133,15 +153,54 @@ fn an_exported_csv_reimports_with_nulls_and_formula_text_intact(cx: &mut TestApp assert_eq!(app.query(exact)[0][0], barsql_core::Value::Int(6), "each row came back exactly"); } -// Enter imports. Once the import is through Enter closes, so a second press can't load the file twice. #[gpui_kit::test] -fn enter_imports_and_then_closes(cx: &mut TestAppContext) { +fn an_exported_json_reimports_with_nulls_and_quotes_intact(cx: &mut TestAppContext) { + let mut app = prepared( + cx, + "CREATE TABLE e2e_json_rt (id INTEGER, txt TEXT, n REAL); + INSERT INTO e2e_json_rt VALUES (1, NULL, 1.5), (2, '', NULL), (3, 'say \"hi\"', 0)", + ); + app.run("SELECT * FROM e2e_json_rt ORDER BY id;"); + app.click("export-results"); + app.menu_pick("export-format", 2); + app.click("export-copy"); + app.pause(); + let json = app.cx.read_from_clipboard().and_then(|item| item.text()).unwrap_or_default(); + assert!( + json.starts_with( + "[ + {" + ), + "{json}" + ); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("roundtrip.json"); + std::fs::write(&path, &json).unwrap(); + app.context_menu("tree:t:main.e2e_json_rt", IMPORT_INTO_TABLE); + browse(&mut app, &path); + assert_eq!(shown(&mut app).format, Some(barsql_app::FileFormat::Json)); + assert_eq!(import(&mut app), (3, 0)); + let exact = "SELECT count(*) FROM e2e_json_rt WHERE (id = 1 AND txt IS NULL AND n = 1.5) + OR (id = 2 AND txt = '' AND n IS NULL) OR (id = 3 AND txt = 'say \"hi\"' AND n = 0)"; + assert_eq!(app.query(exact)[0][0], barsql_core::Value::Int(6), "each row came back exactly"); +} + +// Enter walks the steps and imports on the last. Once the import is through it closes, so a second press can't +// load the file twice. +#[gpui_kit::test] +fn enter_walks_to_the_import_runs_it_and_closes(cx: &mut TestAppContext) { let mut app = prepared(cx, "CREATE TABLE e2e_import_enter (id INTEGER PRIMARY KEY, name TEXT)"); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("enter.csv"); std::fs::write(&path, "id,name\n1,ann\n2,bob\n").unwrap(); app.context_menu("tree:t:main.e2e_import_enter", IMPORT_INTO_TABLE); browse(&mut app, &path); + for want in [Step::Preview, Step::Columns, Step::Import] { + app.keys("enter"); + assert_eq!(shown(&mut app).step, want); + } + assert!(shown(&mut app).result.is_none(), "nothing has run yet"); app.keys("enter"); let dialog = dialog(&mut app); app.settle(|cx| cx.update(|_, cx| dialog.read(cx).shown(cx).result.is_some())); diff --git a/crates/barsql-ui/src/schema_tree.rs b/crates/barsql-ui/src/schema_tree.rs index 4e70d01..d1f1fd4 100644 --- a/crates/barsql-ui/src/schema_tree.rs +++ b/crates/barsql-ui/src/schema_tree.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::ops::Range; +use std::rc::Rc; use std::time::Duration; use barsql_core::capabilities::DefaultSchema; @@ -329,9 +330,14 @@ impl SchemaTree { .map(|tables| tables.iter().map(|t| t.name.clone()).collect()) .unwrap_or_default(); let (id, driver) = (connection.id.clone(), connection.driver.clone()); - crate::import_dialog::open(connection, schema, tables, table, window, cx, move |cx| { - schema::reload(&id, driver.clone(), cx); - }); + let tree = cx.entity().downgrade(); + let hooks = crate::import_dialog::Hooks { + imported: Rc::new(move |cx| schema::reload(&id, driver.clone(), cx)), + open: Rc::new(move |schema, table, _, cx| { + tree.update(cx, |_, cx| cx.emit(SchemaTreeEvent::Browse { schema, table })).ok(); + }), + }; + crate::import_dialog::open(connection, schema, tables, table, hooks, window, cx); } fn refresh(&mut self, cx: &mut Context) { diff --git a/crates/barsql-ui/src/screenshots.rs b/crates/barsql-ui/src/screenshots.rs index 634ea07..8488cc9 100644 --- a/crates/barsql-ui/src/screenshots.rs +++ b/crates/barsql-ui/src/screenshots.rs @@ -775,6 +775,11 @@ ORDER BY 1;"; dialog.is_some_and(|dialog| dialog.read(cx).preview_loaded()) }) .await?; + robot.act(cx, |_, _, cx| { + let dialog = cx.try_global::().and_then(|opened| opened.0.upgrade())?; + dialog.update(cx, |dialog, cx| dialog.show_columns(cx)); + Some(()) + })?; robot.capture(cx, &shot(11)).await?; robot.close_dialog(cx).await?; diff --git a/crates/barsql-ui/src/screenshots/video.rs b/crates/barsql-ui/src/screenshots/video.rs index fb08c5b..a5b6e1e 100644 --- a/crates/barsql-ui/src/screenshots/video.rs +++ b/crates/barsql-ui/src/screenshots/video.rs @@ -700,7 +700,14 @@ async fn data(cam: &Camera<'_>, cx: &mut AsyncApp) -> Res<()> { cam.robot .settle(cx, "the CSV preview", |_, _, cx| importer(cx).is_some_and(|dialog| dialog.read(cx).preview_loaded())) .await?; - // After the preview grows the dialog, so the caption starts beside it. + // Columns shows where each of the file's columns goes. + let columns = cam.robot.center(cx, ("import-step", 2usize))?; + cam.mimic(cx, columns).await?; + cam.robot.act(cx, |_, _, cx| { + importer(cx)?.update(cx, |dialog, cx| dialog.show_columns(cx)); + Some(()) + })?; + // Once the columns show, so the caption starts beside them. cam.caption(cx, Some("Import a CSV into any table")); cam.hold(cx, 2200).await?; cam.caption(cx, None); diff --git a/docs/index.html b/docs/index.html index 7d868b6..5843d15 100644 --- a/docs/index.html +++ b/docs/index.html @@ -295,7 +295,7 @@

Change a table without writing ALTER

Import and export -

Data in, data out

-

Load a CSV into a new or existing table, or run a .sql script, and export any result in the format you need.

+

Load a CSV or JSON file into a new or existing table, or run a .sql script, and export any result in the format you need.

    -
  • Delimiter detected, columns mapped, types inferred for a new table
  • +
  • Format detected, rows previewed, columns mapped, types inferred for a new table
  • +
  • JSON arrays or JSON Lines, with nested objects kept as JSON
  • Bad rows skipped and reported, with live progress and Stop
  • Export as Text, CSV, JSON, Markdown, or SQL INSERTs in your engine's own syntax
  • -
  • CSV and SQL exports import back cleanly, NULLs included
  • +
  • CSV, JSON and SQL exports import back cleanly, NULLs included
More about import and export
@@ -475,7 +476,7 @@

Everything you need. Nothing you don't.

Table backups

Structure and rows to a .sql file. The server writes every value as a literal, so dates, JSON and binary survive the round trip.

Edit data in the grid

In a table, or a query's results from one: staged edits, deletes and new rows with undo, paste and foreign-key jumps, checkboxes for booleans and pickers for enums.

Cell and JSON viewers

A cell editor for large values (JSON, XML, HTML or text), and a JSON view of the row. PostgreSQL arrays and ClickHouse maps and tuples read as JSON too.

-

CSV and SQL import

Column mapping, inferred types, configurable NULL text and header rows, or a .sql script run statement by statement.

+

CSV, JSON and SQL import

Delimited files and JSON, arrays or JSON Lines, with a preview, column mapping and inferred types, or a .sql script run statement by statement.

One-click export

Text, CSV, JSON, Markdown or SQL INSERT written for your engine, for all or the selected rows, to the clipboard or a file.

Saved queries and history

Save and reuse queries with unsaved-change tracking, plus per-connection history with status and duration, filterable to failed runs.

Safety nets

Ask before changes on production connections, a check before an UPDATE or DELETE without WHERE, and read-only mode the server enforces too, where it can.

@@ -504,7 +505,7 @@

Screenshots

Quick Search
DDL viewer
Plan viewer
-
CSV & SQL import
+
CSV, JSON & SQL import
Structure editor
ER diagram
Quick charts
diff --git a/guide/README.md b/guide/README.md index 3b604a0..f4e3ac1 100644 --- a/guide/README.md +++ b/guide/README.md @@ -9,7 +9,7 @@ Everything BarSQL does, one area per page. For screenshots, see the [README](../ | [🧠 SQL Editor](editor.md) | Autocomplete, multiple cursors, scripts, transactions, the query plan viewer, the relational algebra graph, query builder tabs, saved queries and history | | [🗃️ Schema Explorer](schema.md) | The databases list, the schema tree, ER diagrams, schema compare, Copy DDL, schema changes, the structure editor, table backups | | [📊 Results Grid](results.md) | Sorting, selection stats, quick charts, the cell and JSON viewers, editing data | -| [📥 Import & Export](import-export.md) | CSV and SQL import, export formats | +| [📥 Import & Export](import-export.md) | CSV, JSON and SQL import, export formats | | [🤖 AI Assistants (MCP)](ai-assistants.md) | Letting AI apps read your databases, and change them only where you allow it | | [🌍 The App](app.md) | Themes, languages, palettes, the status bar, keyboard shortcuts, the data folder, auto updates | | [🎨 Themes](themes.md) | The 21 built-in themes, Select theme…, and making your own | diff --git a/guide/import-export.md b/guide/import-export.md index 60709eb..b71fb13 100644 --- a/guide/import-export.md +++ b/guide/import-export.md @@ -1,6 +1,15 @@ # 📥 Import & Export -Load a **CSV** (or any delimited file) or run a **`.sql` script**, from the ⬆ button in the Schema Explorer or a schema's or table's right-click menu. +Load a **CSV** (or any delimited file) or a **JSON** file, or run a **`.sql` script**, from the ⬆ button in the Schema Explorer or a schema's or table's right-click menu. + +The importer has four steps: **File**, **Preview**, **Columns** and **Import**. A SQL script needs only the first and the last. + +- **Drop a file** onto it or browse for one. The format comes from the file (its extension, then its first few KB), and **Read as** changes it when the guess is wrong +- **Preview** shows the first rows as the import will read them, with the delimiter and other CSV options above them +- **Columns** maps each of the file's columns to a column of the table, with the types a new table gets +- **Import** sums up what will happen, then shows progress and the result: rows loaded, rows skipped and why, and **Open table** to see them +- **Next** (or Enter) walks the steps, and the import runs only from the last one, so its summary is always seen first. The step marks jump back, or ahead to any step the file has reached +- **Delete existing rows first** sits on the Import step beside the button it runs before, which then reads **Delete rows and import** in red ## CSV @@ -14,6 +23,17 @@ Load a **CSV** (or any delimited file) or run a **`.sql` script**, from the ⬆ - **Bad rows are skipped and reported**, not fatal - or tick **stop at the first error** if you'd rather nothing partial lands - Rows load in batches with live progress, and **Stop** ends a long run +## JSON + +- **An array of objects**, as BarSQL's own JSON export writes, or **JSON Lines** with one object per line (mongoexport, BigQuery, log pipelines). Objects printed one after another over several lines, as `jq` prints them, load too +- **Each key is a column**, in the order the keys first appear. Rows don't need the same keys: a missing one loads as `NULL` +- **Nested objects and arrays load as JSON** into one column: `jsonb` on Postgres, `JSON` on MySQL, text elsewhere. A new table gets that type for them +- **Types come from the values**: whole numbers, decimals, booleans, dates and timestamps. Strings stay text even when they look like numbers, so `"007"` keeps its zeros +- **Numbers keep every digit**: they load as written, never through a float +- Files up to 64 MB are read whole to find their columns and count their rows. Bigger ones take their columns from the first 1,000 rows, and a key that only shows up later is named in the result rather than dropped silently +- **A bad row is skipped and reported** with its line number. In JSON Lines only that line is lost +- **A BarSQL JSON export loads back unchanged**, with one exception: a JSON `null` stored in a json column comes back as SQL `NULL`, because the export writes both as `null` + ## SQL scripts A `.sql` file runs statement by statement on one connection, so `SET`, temp tables and scripted transactions behave. You get a progress bar and a count - not thousands of result tabs. It's also how a [table backup](schema.md#-table-backups) comes back. The file must be UTF-8 (a BOM is fine); any other encoding is refused rather than loaded with `�` in place of what it can't read. @@ -27,4 +47,4 @@ A `.sql` file runs statement by statement on one connection, so `SET`, temp tabl - Export all or **selected** rows and columns - Copy to clipboard or **save to file** - Remembers your last export format -- **CSV and SQL exports import back cleanly** - `NULL` stays apart from an empty string, and cells that spreadsheets would treat as formulas are guarded on the way out and unguarded on the way in +- **CSV, JSON and SQL exports import back cleanly** - `NULL` stays apart from an empty string, and cells that spreadsheets would treat as formulas are guarded on the way out of a CSV and unguarded on the way in From aa4da82d552372f3f7479b8a8e100e7c4bcd6e18 Mon Sep 17 00:00:00 2001 From: Bare7a Date: Tue, 1 Dec 2026 17:55:32 +0200 Subject: [PATCH 2/2] Updates the Export Modal --- crates/barsql-io/src/export.rs | 4 +- crates/barsql-io/src/lib.rs | 3 +- crates/barsql-ui/locales/bg.json | 12 +- crates/barsql-ui/locales/de.json | 12 +- crates/barsql-ui/locales/en.json | 12 +- crates/barsql-ui/locales/es.json | 12 +- crates/barsql-ui/src/export_dialog.rs | 289 ++++++++++++++---- crates/barsql-ui/src/file_dialogs.rs | 19 +- crates/barsql-ui/src/form.rs | 17 +- crates/barsql-ui/src/grid/toolbar.rs | 7 +- crates/barsql-ui/src/grid/view.rs | 6 + crates/barsql-ui/src/query_tab.rs | 2 + crates/barsql-ui/src/results.rs | 25 +- .../barsql-ui/src/scenarios/result_edits.rs | 19 ++ crates/barsql-ui/src/scenarios/table_view.rs | 22 ++ crates/barsql-ui/src/structure_tab.rs | 6 +- crates/barsql-ui/src/table_tab.rs | 7 +- crates/barsql-ui/src/toast.rs | 140 ++++++++- 18 files changed, 520 insertions(+), 94 deletions(-) diff --git a/crates/barsql-io/src/export.rs b/crates/barsql-io/src/export.rs index 42cf43b..ae2b7b6 100644 --- a/crates/barsql-io/src/export.rs +++ b/crates/barsql-io/src/export.rs @@ -5,6 +5,8 @@ use barsql_sql::{Dialect, quote_ident_in, quote_literal_in}; use serde_json::Value as Json; pub const EXPORT_CHUNK_ROWS: usize = 5000; +// SQL INSERTs go into this table when none is named. +pub const DEFAULT_TABLE: &str = "results"; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ExportFormat { @@ -99,7 +101,7 @@ impl Exporter { Some(dialect) => quote_ident_in(Dialect::of(dialect), id), None => format!("\"{}\"", id.replace('"', "\"\"")), }; - let table = table_name.filter(|t| !t.is_empty()).unwrap_or("results"); + let table = table_name.filter(|t| !t.is_empty()).unwrap_or(DEFAULT_TABLE); let sql_prefix = format!( "INSERT INTO {} ({}) VALUES (", quote(table), diff --git a/crates/barsql-io/src/lib.rs b/crates/barsql-io/src/lib.rs index 6e6d998..ad82bfe 100644 --- a/crates/barsql-io/src/lib.rs +++ b/crates/barsql-io/src/lib.rs @@ -14,7 +14,8 @@ pub use csv::{CsvField, CsvReader, csv_values}; pub use csv_import::{CsvOptions, ImportPreview, count_rows, infer_column_type, new_reader, preview_file}; pub use detect::{FileFormat, detect_format}; pub use export::{ - EXPORT_FORMATS, ExportChunk, ExportFormat, Exporter, export_to_string, is_space, restringify_json, sql_literal, + DEFAULT_TABLE, EXPORT_FORMATS, ExportChunk, ExportFormat, Exporter, export_to_string, is_space, restringify_json, + sql_literal, }; pub use format::{format_query, format_sql}; pub use json_import::{JsonCell, JsonError, JsonReader, JsonShape, count_json_rows, json_cell, preview_json}; diff --git a/crates/barsql-ui/locales/bg.json b/crates/barsql-ui/locales/bg.json index c13160c..b64479a 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -45,7 +45,17 @@ "rowCount_one": "{{count}} ред", "rowCount_other": "{{count}} реда", "columnCount_one": "{{count}} колона", - "columnCount_other": "{{count}} колони" + "columnCount_other": "{{count}} колони", + "rowsLoaded": "Заредени ({{count}})", + "loadedRowCount_one": "{{count}} зареден ред", + "loadedRowCount_other": "{{count}} заредени реда", + "table": "Таблица", + "hintText": "Стойности, разделени с табулация, без заглавен ред", + "hintCsv": "Стойности, разделени със запетая, със заглавен ред", + "hintJson": "Масив с по един обект за всеки ред", + "hintMarkdown": "Таблица със заглавен ред", + "hintSql": "По един израз INSERT за всеки ред", + "showInFolder": "Покажи в папката" }, "editor": { "moveToDatabase": "Смяна на базата данни", diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index 81eee49..ca4e8c5 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -45,7 +45,17 @@ "rowCount_one": "{{count}} Zeile", "rowCount_other": "{{count}} Zeilen", "columnCount_one": "{{count}} Spalte", - "columnCount_other": "{{count}} Spalten" + "columnCount_other": "{{count}} Spalten", + "rowsLoaded": "Geladen ({{count}})", + "loadedRowCount_one": "{{count}} geladenen Zeile", + "loadedRowCount_other": "{{count}} geladenen Zeilen", + "table": "Tabelle", + "hintText": "Tabulatorgetrennte Werte ohne Kopfzeile", + "hintCsv": "Kommagetrennte Werte mit Kopfzeile", + "hintJson": "Ein Array mit einem Objekt pro Zeile", + "hintMarkdown": "Eine Tabelle mit Kopfzeile", + "hintSql": "Eine INSERT-Anweisung pro Zeile", + "showInFolder": "Im Ordner anzeigen" }, "editor": { "moveToDatabase": "Datenbank wechseln", diff --git a/crates/barsql-ui/locales/en.json b/crates/barsql-ui/locales/en.json index 898492a..d613461 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -45,7 +45,17 @@ "rowCount_one": "{{count}} row", "rowCount_other": "{{count}} rows", "columnCount_one": "{{count}} column", - "columnCount_other": "{{count}} columns" + "columnCount_other": "{{count}} columns", + "rowsLoaded": "Loaded ({{count}})", + "loadedRowCount_one": "{{count}} loaded row", + "loadedRowCount_other": "{{count}} loaded rows", + "table": "Table", + "hintText": "Tab-separated values with no header row", + "hintCsv": "Comma-separated values with a header row", + "hintJson": "An array with one object per row", + "hintMarkdown": "A table with a header row", + "hintSql": "One INSERT statement per row", + "showInFolder": "Show in folder" }, "editor": { "runAll": "Run all", diff --git a/crates/barsql-ui/locales/es.json b/crates/barsql-ui/locales/es.json index b6d0ac7..8effd52 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -45,7 +45,17 @@ "rowCount_one": "{{count}} fila", "rowCount_other": "{{count}} filas", "columnCount_one": "{{count}} columna", - "columnCount_other": "{{count}} columnas" + "columnCount_other": "{{count}} columnas", + "rowsLoaded": "Cargadas ({{count}})", + "loadedRowCount_one": "{{count}} fila cargada", + "loadedRowCount_other": "{{count}} filas cargadas", + "table": "Tabla", + "hintText": "Valores separados por tabuladores, sin fila de encabezado", + "hintCsv": "Valores separados por comas, con fila de encabezado", + "hintJson": "Un array con un objeto por fila", + "hintMarkdown": "Una tabla con fila de encabezado", + "hintSql": "Una sentencia INSERT por fila", + "showInFolder": "Mostrar en la carpeta" }, "editor": { "moveToDatabase": "Cambiar de base de datos", diff --git a/crates/barsql-ui/src/export_dialog.rs b/crates/barsql-ui/src/export_dialog.rs index 1f6d8ad..4802753 100644 --- a/crates/barsql-ui/src/export_dialog.rs +++ b/crates/barsql-ui/src/export_dialog.rs @@ -1,23 +1,26 @@ use std::path::PathBuf; +use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use barsql_io::{EXPORT_FORMATS, ExportFormat, WriteOutcome, write_chunks}; +use barsql_io::{DEFAULT_TABLE, EXPORT_FORMATS, ExportFormat, WriteOutcome, write_chunks}; use gpui_kit::component::button::{Button, ButtonVariants}; +use gpui_kit::component::input::InputState; use gpui_kit::component::menu::{PopupMenu, PopupMenuItem}; -use gpui_kit::component::{ActiveTheme, Disableable, Sizable, WindowExt, v_flex}; +use gpui_kit::component::{ActiveTheme, Disableable, Sizable, WindowExt, h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; -use crate::file_dialogs::pick_export_path; +use crate::file_dialogs::{pick_save_path, reveal_path}; use crate::form::{self, SelectMenu}; use crate::grid::copy::{self, CopyTarget}; use crate::grid::format_label; use crate::grid::{ExportSource, copy_format, set_copy_format}; use crate::i18n::{count, t, t_count, t_with}; use crate::modal::{self, Modal}; -use crate::toast; -use crate::tokens::TEXT_SM; +use crate::spinner::Spinner; +use crate::toast::{self, ToastAction, ToastKind}; +use crate::tokens::{ICON_XS, TEXT_SM}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum RowScope { @@ -36,14 +39,17 @@ pub struct ExportDialog { source: ExportSource, rows: RowScope, columns: ColumnScope, + // The table SQL INSERTs go into. + table: Entity, busy: bool, + copying: bool, progress: Option, stop: Arc, task: Option>, } impl ExportDialog { - fn new(source: ExportSource) -> Self { + fn new(source: ExportSource, window: &mut Window, cx: &mut Context) -> Self { let rows = if source.selected_rows.is_empty() { RowScope::All } else { RowScope::Selected }; let columns = if !source.selected_columns.is_empty() { ColumnScope::Selected @@ -52,7 +58,19 @@ impl ExportDialog { } else { ColumnScope::All }; - Self { source, rows, columns, busy: false, progress: None, stop: Arc::default(), task: None } + let named = source.table.clone().unwrap_or_default(); + let table = cx.new(|cx| InputState::new(window, cx).placeholder(DEFAULT_TABLE).default_value(named)); + Self { + source, + rows, + columns, + table, + busy: false, + copying: false, + progress: None, + stop: Arc::default(), + task: None, + } } fn target(&self) -> CopyTarget { @@ -69,27 +87,56 @@ impl ExportDialog { CopyTarget { columns, rows } } + // Only the loaded part of the table goes out. + fn loaded_only(&self) -> bool { + self.source.more_rows && (self.rows == RowScope::All || self.source.selected_rows.is_empty()) + } + + fn all_rows_label(&self, cx: &App) -> SharedString { + let key = if self.source.more_rows { "export.rowsLoaded" } else { "export.rowsAll" }; + t_with(cx, key, &[("count", &self.source.order.len().to_string())]) + } + + fn table_name(&self, cx: &App) -> Option { + let name = self.table.read(cx).value().trim().to_string(); + (!name.is_empty()).then_some(name) + } + + fn file_name(&self, format: ExportFormat) -> String { + // Characters Windows refuses in file names. + let unsafe_char = |c: char| c.is_control() || r#"\/:*?"<>|"#.contains(c); + let name = self.source.name.as_deref().unwrap_or_default(); + let name: String = name.chars().map(|c| if unsafe_char(c) { '_' } else { c }).collect(); + let stem = name.trim().trim_end_matches('.').trim_end(); + format!("{}.{}", if stem.is_empty() { "export" } else { stem }, format.ext()) + } + fn copy(&mut self, window: &mut Window, cx: &mut Context) { if self.busy { return; } - self.busy = true; + (self.busy, self.copying) = (true, true); cx.notify(); - let (set, staged, table) = (self.source.set.clone(), self.source.staged.clone(), self.source.table.clone()); + let (set, staged, table) = (self.source.set.clone(), self.source.staged.clone(), self.table_name(cx)); let (target, format, dialect) = (self.target(), copy_format(cx), self.source.dialect); let text = cx.background_spawn(async move { copy::export(&set, staged.as_ref(), format, table.as_deref(), dialect, &target) }); - self.task = Some(cx.spawn_in(window, async move |this, cx| { + // Detached, so the copy still lands if the dialog is closed first. + cx.spawn_in(window, async move |this, cx| { let text = text.await; - this.update_in(cx, |dialog, window, cx| { - dialog.busy = false; + cx.update(|_, cx| { cx.write_to_clipboard(ClipboardItem::new_string(text)); toast::success(t(cx, "toast.exportCopied"), cx); + }) + .ok(); + this.update_in(cx, |dialog, window, cx| { + (dialog.busy, dialog.copying) = (false, false); window.close_dialog(cx); }) .ok(); - })); + }) + .detach(); } fn save(&mut self, window: &mut Window, cx: &mut Context) { @@ -99,7 +146,7 @@ impl ExportDialog { let format = copy_format(cx); self.busy = true; cx.notify(); - let picked = pick_export_path(format.ext(), cx); + let picked = pick_save_path(&self.file_name(format), cx); self.task = Some(cx.spawn_in(window, async move |this, cx| { let Some(path) = picked.await else { this.update(cx, |dialog, cx| { @@ -117,9 +164,7 @@ impl ExportDialog { let write = self.write(path.clone(), format, cx); self.task = Some(cx.spawn_in(window, async move |this, cx| { let outcome = write.await; - let file_name = - path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()); - this.update_in(cx, |dialog, window, cx| dialog.finish(outcome, &file_name, window, cx)).ok(); + this.update_in(cx, |dialog, window, cx| dialog.finish(outcome, path, window, cx)).ok(); })); } @@ -133,7 +178,7 @@ impl ExportDialog { self.stop.store(false, Ordering::Relaxed); self.progress = Some(0); cx.notify(); - let (set, staged, table) = (self.source.set.clone(), self.source.staged.clone(), self.source.table.clone()); + let (set, staged, table) = (self.source.set.clone(), self.source.staged.clone(), self.table_name(cx)); let (target, stop, dialect) = (self.target(), self.stop.clone(), self.source.dialect); let (sender, receiver) = async_channel::unbounded(); let write = cx.background_spawn(async move { @@ -156,22 +201,28 @@ impl ExportDialog { fn finish( &mut self, outcome: std::io::Result, - file_name: &str, + path: PathBuf, window: &mut Window, cx: &mut Context, ) { self.busy = false; self.progress = None; cx.notify(); + let file_name = + path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()); match outcome { Ok(WriteOutcome { cancelled: false, .. }) => { - let message = t_with(cx, "toast.savedFile", &[("fileName", file_name)]); - toast::success(message, cx); + let message = t_with(cx, "toast.savedFile", &[("fileName", &file_name)]); + let reveal = ToastAction { + label: t(cx, "export.showInFolder"), + on_click: Rc::new(move |_, cx| reveal_path(&path, cx)), + }; + toast::push(message, ToastKind::Success, None, Some(reveal), cx); window.close_dialog(cx); } // A partial file stays on disk, so don't report it as a finished export. Ok(WriteOutcome { rows, cancelled: true }) => { - let message = t_count(cx, "toast.exportStopped", rows as i64, &[("fileName", file_name)]); + let message = t_count(cx, "toast.exportStopped", rows as i64, &[("fileName", &file_name)]); toast::error(message, cx); } Err(error) => { @@ -226,21 +277,32 @@ impl ExportDialog { impl ExportDialog { fn set_rows(&mut self, rows: RowScope, cx: &mut Context) { - self.rows = rows; - cx.notify(); + if !self.writing() { + self.rows = rows; + cx.notify(); + } + } + + fn set_columns(&mut self, columns: ColumnScope, cx: &mut Context) { + if !self.writing() { + self.columns = columns; + cx.notify(); + } } } impl Render for ExportDialog { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let format = copy_format(cx); + let writing = self.writing(); let target = self.target(); - let (total, selected_rows) = (self.source.order.len(), self.source.selected_rows.len()); + let selected_rows = self.source.selected_rows.len(); let (all_columns, visible, selected_columns) = (self.source.set.columns.len(), self.source.visible.len(), self.source.selected_columns.len()); let this = cx.entity().downgrade(); let format_menu = form::select("export-format", format_label(format, cx), cx) .debug_selector(|| "export-format".into()) + .disabled(writing) .select_menu(window, cx, move |mut menu: PopupMenu, _, cx| { for option in EXPORT_FORMATS { let this = this.clone(); @@ -253,14 +315,20 @@ impl Render for ExportDialog { } menu }); + let format_group = + form::group(t(cx, "export.format"), format_menu, cx).child(form::hint(t(cx, format_hint(format)), cx)); + let format_row = match format { + ExportFormat::Sql => { + let table = form::input(&self.table, window, cx).disabled(writing); + form::row(format_group, form::group(t(cx, "export.table"), table, cx)).into_any_element() + } + _ => format_group.into_any_element(), + }; let rows = form::toggle_group() .child( - form::toggle( - "export-rows-all", - t_with(cx, "export.rowsAll", &[("count", &total.to_string())]), - self.rows == RowScope::All, - ) - .on_click(cx.listener(|dialog, _, _, cx| dialog.set_rows(RowScope::All, cx))), + form::toggle("export-rows-all", self.all_rows_label(cx), self.rows == RowScope::All) + .disabled(writing) + .on_click(cx.listener(|dialog, _, _, cx| dialog.set_rows(RowScope::All, cx))), ) .child( form::toggle( @@ -269,7 +337,7 @@ impl Render for ExportDialog { self.rows == RowScope::Selected, ) .debug_selector(|| "export-rows-selected".into()) - .disabled(selected_rows == 0) + .disabled(writing || selected_rows == 0) .when(selected_rows == 0, |button| button.tooltip(t(cx, "tooltip.exportSelectRows"))) .on_click(cx.listener(|dialog, _, _, cx| dialog.set_rows(RowScope::Selected, cx))), ); @@ -287,19 +355,18 @@ impl Render for ExportDialog { form::toggle_group().children(column_scopes.into_iter().enumerate().map(|(ix, (scope, label))| { let empty = scope == ColumnScope::Selected && selected_columns == 0; form::toggle(("export-columns", ix), label, self.columns == scope) - .disabled(empty) + .disabled(writing || empty) .when(empty, |button| button.tooltip(t(cx, "tooltip.exportSelectCols"))) - .on_click(cx.listener(move |dialog, _, _, cx| { - dialog.columns = scope; - cx.notify(); - })) + .on_click(cx.listener(move |dialog, _, _, cx| dialog.set_columns(scope, cx))) })); let status = match self.progress { - None => div() + None => h_flex() .mt(rems(0.308)) + .gap(rems(0.462)) .text_size(TEXT_SM) .text_color(cx.theme().muted_foreground) - .child(summary(target.rows.len(), target.columns.len(), format, cx)) + .when(self.copying, |el| el.child(Spinner::new(ICON_XS))) + .child(summary(target.rows.len(), target.columns.len(), self.loaded_only(), format, cx)) .into_any_element(), Some(done) => { let total = target.rows.len(); @@ -311,7 +378,7 @@ impl Render for ExportDialog { v_flex() .child( modal::body() - .child(form::group(t(cx, "export.format"), format_menu, cx)) + .child(format_row) .child(form::group(t(cx, "export.rows"), rows, cx)) .child(form::group(t(cx, "export.columns"), columns, cx)) .child(status), @@ -320,9 +387,19 @@ impl Render for ExportDialog { } } +fn format_hint(format: ExportFormat) -> &'static str { + match format { + ExportFormat::Text => "export.hintText", + ExportFormat::Csv => "export.hintCsv", + ExportFormat::Json => "export.hintJson", + ExportFormat::Markdown => "export.hintMarkdown", + ExportFormat::Sql => "export.hintSql", + } +} + // "Exporting 14 rows × 3 columns as CSV". Each count picks its own plural. -fn summary(rows: usize, cols: usize, format: ExportFormat, cx: &App) -> SharedString { - let rows = t_count(cx, "export.rowCount", rows as i64, &[]); +fn summary(rows: usize, cols: usize, loaded_only: bool, format: ExportFormat, cx: &App) -> SharedString { + let rows = t_count(cx, if loaded_only { "export.loadedRowCount" } else { "export.rowCount" }, rows as i64, &[]); let cols = t_count(cx, "export.columnCount", cols as i64, &[]); t_with(cx, "export.summary", &[("rows", &rows), ("cols", &cols), ("format", &format_label(format, cx))]) } @@ -338,7 +415,7 @@ impl Global for Opened {} impl ExportDialog { pub(crate) fn summary(&self, cx: &App) -> String { let target = self.target(); - summary(target.rows.len(), target.columns.len(), copy_format(cx), cx).to_string() + summary(target.rows.len(), target.columns.len(), self.loaded_only(), copy_format(cx), cx).to_string() } // Whether Selected can be picked, and whether it is. @@ -360,10 +437,22 @@ impl ExportDialog { scopes.push("selected"); (scopes, name(self.columns)) } + + pub(crate) fn rows_label(&self, cx: &App) -> String { + self.all_rows_label(cx).to_string() + } + + pub(crate) fn insert_table(&self, cx: &App) -> String { + self.table.read(cx).value().to_string() + } + + pub(crate) fn suggested_file(&self, cx: &App) -> String { + self.file_name(copy_format(cx)) + } } pub fn open(source: ExportSource, window: &mut Window, cx: &mut App) { - let dialog = cx.new(|_| ExportDialog::new(source)); + let dialog = cx.new(|cx| ExportDialog::new(source, window, cx)); #[cfg(test)] cx.set_global(Opened(dialog.downgrade())); // Enter saves to a file, the main button. @@ -371,7 +460,7 @@ pub fn open(source: ExportSource, window: &mut Window, cx: &mut App) { let writing = dialog.read(cx).writing(); let entry = dialog.clone(); Modal::new("export", t(cx, "export.title")) - .size(modal::Size::Sm) + .size(modal::Size::Md) .closable(!writing) .build(frame, dialog.clone(), window, cx) .keyboard(!writing) @@ -389,13 +478,15 @@ mod tests { use barsql_db::{ChunkBuilder, ColumnMeta, ResultSet}; use barsql_io::ExportFormat; - use gpui_kit::component::Root; + use gpui_kit::component::{Root, WindowExt as _}; use gpui_kit::{AppContext as _, Context, IntoElement, Render, TestAppContext, VisualTestContext, Window, div}; - use super::{ColumnScope, ExportDialog, RowScope}; - use crate::grid::ExportSource; + use super::{ColumnScope, ExportDialog, Opened, RowScope, open}; + use crate::file_dialogs::Revealed; use crate::grid::copy::CopyTarget; + use crate::grid::{ExportSource, set_copy_format}; use crate::test_support::Env; + use crate::toast; struct Blank; @@ -428,22 +519,36 @@ mod tests { selected_rows: vec![1], visible: vec![1, 0], selected_columns: vec![], + more_rows: false, + name: None, } } + fn window(cx: &mut TestAppContext) -> &mut VisualTestContext { + let window = cx.add_window(|window, cx| Root::new(cx.new(|_| Blank), window, cx)); + VisualTestContext::from_window(window.into(), cx).into_mut() + } + + fn dialog(source: ExportSource, cx: &mut VisualTestContext) -> gpui_kit::Entity { + cx.update(|window, cx| cx.new(|cx| ExportDialog::new(source, window, cx))) + } + + fn clipboard(cx: &mut VisualTestContext) -> Option { + cx.read_from_clipboard().and_then(|item| item.text()) + } + #[gpui_kit::test] fn exports_default_to_the_selection_and_copy_or_write_it(cx: &mut TestAppContext) { let _env = Env::new(cx); - let window = cx.add_window(|window, cx| Root::new(cx.new(|_| Blank), window, cx)); - let cx = VisualTestContext::from_window(window.into(), cx).into_mut(); - let dialog = cx.new(|_| ExportDialog::new(source())); + let cx = window(cx); + let dialog = dialog(source(), cx); let (rows, columns, target) = dialog.read_with(cx, |d, _| (d.rows, d.columns, d.target())); assert_eq!((rows, columns), (RowScope::Selected, ColumnScope::Visible)); assert_eq!(target, CopyTarget { columns: vec![1, 0], rows: vec![1] }); dialog.update_in(cx, |dialog, window, cx| dialog.copy(window, cx)); cx.run_until_parked(); - assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("name,id\nbob,2")); + assert_eq!(clipboard(cx).as_deref(), Some("name,id\nbob,2")); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("export.json"); @@ -457,5 +562,85 @@ mod tests { assert!(written.starts_with("[\n {\n \"id\": 3,"), "{written}"); assert_eq!(written.matches("\"note\": null").count(), 3); assert_eq!(dialog.read_with(cx, |d, _| (d.busy, d.progress)), (false, None)); + let last = cx.update(|_, cx| toast::messages(cx).len()) - 1; + let reveal = cx.update(|_, cx| toast::action(last, cx)).expect("the saved toast offers its folder"); + cx.update(|window, cx| (reveal.on_click)(window, cx)); + assert_eq!(cx.update(|_, cx| cx.default_global::().0.clone()), [path]); + } + + #[gpui_kit::test] + fn a_copy_still_lands_when_the_dialog_closes_first(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let cx = window(cx); + cx.update(|window, cx| open(source(), window, cx)); + let dialog = cx.update(|_, cx| cx.global::().0.upgrade()).expect("the dialog"); + dialog.update_in(cx, |dialog, window, cx| dialog.copy(window, cx)); + assert!(dialog.read_with(cx, |d, _| d.copying), "the button spins while the text is made"); + cx.update(|window, cx| window.close_dialog(cx)); + drop(dialog); + cx.run_until_parked(); + assert!(cx.update(|_, cx| cx.global::().0.upgrade()).is_none(), "the dialog is gone"); + assert_eq!(clipboard(cx).as_deref(), Some("name,id\nbob,2")); + } + + #[gpui_kit::test] + fn the_form_holds_still_while_a_file_is_written(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let cx = window(cx); + let dialog = dialog(source(), cx); + dialog.update(cx, |dialog, cx| { + dialog.progress = Some(0); + dialog.set_rows(RowScope::All, cx); + dialog.set_columns(ColumnScope::All, cx); + }); + assert_eq!(dialog.read_with(cx, |d, _| (d.rows, d.columns)), (RowScope::Selected, ColumnScope::Visible)); + } + + #[gpui_kit::test] + fn a_partly_loaded_table_says_its_rows_are_only_the_loaded_ones(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let cx = window(cx); + let dialog = dialog(ExportSource { more_rows: true, ..source() }, cx); + let read = |cx: &mut VisualTestContext| dialog.read_with(cx, |d, cx| (d.rows_label(cx), d.summary(cx))); + let (label, summary) = read(cx); + assert_eq!(label, "Loaded (3)"); + assert!(summary.contains("1 row ×"), "the selection is loaded by definition: {summary}"); + dialog.update(cx, |dialog, cx| dialog.set_rows(RowScope::All, cx)); + let (_, summary) = read(cx); + assert!(summary.contains("3 loaded rows"), "{summary}"); + } + + #[gpui_kit::test] + fn sql_inserts_go_into_the_table_named_in_the_dialog(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let cx = window(cx); + cx.update(|_, cx| set_copy_format(ExportFormat::Sql, cx)); + let dialog = dialog(ExportSource { table: Some("people".into()), ..source() }, cx); + assert_eq!(dialog.read_with(cx, |d, cx| d.insert_table(cx)), "people"); + let copied = |name: &str, cx: &mut VisualTestContext| { + dialog.update_in(cx, |dialog, window, cx| { + dialog.table.update(cx, |input, cx| input.set_value(name.to_string(), window, cx)); + dialog.copy(window, cx); + }); + cx.run_until_parked(); + clipboard(cx).unwrap_or_default() + }; + assert_eq!(copied("people", cx), r#"INSERT INTO "people" ("name", "id") VALUES ('bob', 2);"#); + assert!(copied(" staff ", cx).starts_with(r#"INSERT INTO "staff" "#)); + assert!(copied("", cx).starts_with(r#"INSERT INTO "results" "#), "an empty name falls back"); + } + + #[gpui_kit::test] + fn the_file_is_named_after_the_tab(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let cx = window(cx); + let named = |name: Option<&str>, format, cx: &mut VisualTestContext| { + let dialog = dialog(ExportSource { name: name.map(str::to_string), ..source() }, cx); + dialog.read_with(cx, |d, _| d.file_name(format)) + }; + assert_eq!(named(Some("users"), ExportFormat::Csv, cx), "users.csv"); + assert_eq!(named(Some("Posts: a/b?"), ExportFormat::Json, cx), "Posts_ a_b_.json"); + assert_eq!(named(Some("notes. "), ExportFormat::Markdown, cx), "notes.md"); + assert_eq!(named(None, ExportFormat::Sql, cx), "export.sql"); } } diff --git a/crates/barsql-ui/src/file_dialogs.rs b/crates/barsql-ui/src/file_dialogs.rs index b7431db..a2233ac 100644 --- a/crates/barsql-ui/src/file_dialogs.rs +++ b/crates/barsql-ui/src/file_dialogs.rs @@ -18,6 +18,21 @@ pub fn open_path(path: &Path, cx: &mut App) { cx.open_with_system(path); } +#[cfg(test)] +#[derive(Default)] +pub struct Revealed(pub Vec); + +#[cfg(test)] +impl gpui_kit::Global for Revealed {} + +// Opens the file's folder with the file picked. +pub fn reveal_path(path: &Path, cx: &mut App) { + #[cfg(test)] + return cx.default_global::().0.push(path.to_path_buf()); + #[cfg(not(test))] + cx.reveal_path(path); +} + use crate::i18n::t_with; use crate::toast; @@ -96,10 +111,6 @@ pub fn pick_folder(title: &str, cx: &App) -> Task> { run(rfd::AsyncFileDialog::new().set_title(title).pick_folder(), cx) } -pub fn pick_export_path(ext: &str, cx: &App) -> Task> { - pick_save_path(&format!("export.{ext}"), cx) -} - pub fn pick_save_path(file_name: &str, cx: &App) -> Task> { if let Some(stub) = stubbed(cx) { return stub; diff --git a/crates/barsql-ui/src/form.rs b/crates/barsql-ui/src/form.rs index e4e44c5..3cb2f65 100644 --- a/crates/barsql-ui/src/form.rs +++ b/crates/barsql-ui/src/form.rs @@ -276,26 +276,33 @@ pub fn section(cx: &App) -> Div { } pub fn select(id: impl Into, label: impl Into, cx: &App) -> Button { - labeled_select(id, None, label.into(), cx.theme().foreground, cx) + labeled_select(id, None, label.into(), None, cx) } pub fn select_with_icon(id: impl Into, icon: Icon, label: impl Into, cx: &App) -> Button { - labeled_select(id, Some(icon), label.into(), cx.theme().foreground, cx) + labeled_select(id, Some(icon), label.into(), None, cx) } // A select with nothing chosen yet, dimmed like an input's placeholder. pub fn select_placeholder(id: impl Into, placeholder: impl Into, cx: &App) -> Button { - labeled_select(id, None, placeholder.into(), cx.theme().muted_foreground, cx) + labeled_select(id, None, placeholder.into(), Some(cx.theme().muted_foreground), cx) } -fn labeled_select(id: impl Into, icon: Option, label: SharedString, color: Hsla, cx: &App) -> Button { +// Without a color the label takes the button's, which dims when it's disabled. +fn labeled_select( + id: impl Into, + icon: Option, + label: SharedString, + color: Option, + cx: &App, +) -> Button { let theme = cx.theme(); Button::new(id).outline().w_full().h(rems(FIELD_REM)).pl(rems(0.769)).pr(rems(0.615)).bg(theme.background).child( h_flex() .w_full() .gap(rems(0.462)) .text_size(TEXT_BASE) - .text_color(color) + .when_some(color, |el, color| el.text_color(color)) .children(icon.map(|icon| icon.size(ICON_SM))) .child(div().flex_1().min_w_0().truncate().child(label)) .child(Icon::new(IconName::ChevronDown).size(ICON_MD).text_color(theme.muted_foreground)), diff --git a/crates/barsql-ui/src/grid/toolbar.rs b/crates/barsql-ui/src/grid/toolbar.rs index c566f86..9a04d47 100644 --- a/crates/barsql-ui/src/grid/toolbar.rs +++ b/crates/barsql-ui/src/grid/toolbar.rs @@ -9,7 +9,7 @@ use gpui_kit::component::{ActiveTheme, Disableable, Icon, IconName, Selectable, use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; -use super::view::Grid; +use super::view::{Grid, GridEvent}; use super::{copy_format, set_copy_format}; use crate::form::{self, ToolButton}; use crate::i18n::{t, t_with}; @@ -122,10 +122,7 @@ pub fn toolbar( .debug_selector(|| "export-results".into()) .tool(Icon::new(Lucide::Download), ICON_XS, t(cx, "results.export")) .tooltip(t(cx, "tooltip.exportOptions")) - .on_click(move |_, window, cx| { - let source = export.read(cx).export_source(); - crate::export_dialog::open(source, window, cx); - }), + .on_click(move |_, _, cx| export.update(cx, |_, cx| cx.emit(GridEvent::Export))), ), ) } diff --git a/crates/barsql-ui/src/grid/view.rs b/crates/barsql-ui/src/grid/view.rs index 05498d1..f8a5739 100644 --- a/crates/barsql-ui/src/grid/view.rs +++ b/crates/barsql-ui/src/grid/view.rs @@ -183,6 +183,10 @@ pub struct ExportSource { pub selected_rows: Vec, pub visible: Vec, pub selected_columns: Vec, + // The server has rows the grid hasn't loaded yet. + pub more_rows: bool, + // The tab's title, which names the file. + pub name: Option, } // For the JSON row panel, with only the visible columns. `number` is the gutter's, from 1. @@ -804,6 +808,8 @@ impl Grid { selected_rows, visible: self.columns.clone(), selected_columns: self.columns.iter().copied().filter(|c| self.selection.columns.contains(c)).collect(), + more_rows: false, + name: None, } } diff --git a/crates/barsql-ui/src/query_tab.rs b/crates/barsql-ui/src/query_tab.rs index 16178fd..a5c6bd6 100644 --- a/crates/barsql-ui/src/query_tab.rs +++ b/crates/barsql-ui/src/query_tab.rs @@ -322,6 +322,7 @@ impl QueryTab { ]; schema::ensure_loaded(&connection.id, connection.driver.clone(), cx); let title = dotted_title(&tab.title, &connection.name).unwrap_or(tab.title); + results.update(cx, |results, _| results.set_title(title.clone().into())); let mut this = Self { id: tab.id, title: title.into(), @@ -553,6 +554,7 @@ impl QueryTab { } pub fn set_title(&mut self, title: SharedString, cx: &mut Context) { + self.results.update(cx, |results, _| results.set_title(title.clone())); self.title = title; cx.emit(QueryTabEvent::Edited); cx.notify(); diff --git a/crates/barsql-ui/src/results.rs b/crates/barsql-ui/src/results.rs index 97fb509..85b7cb5 100644 --- a/crates/barsql-ui/src/results.rs +++ b/crates/barsql-ui/src/results.rs @@ -337,6 +337,7 @@ pub struct ResultsPanel { // The tab's connection, where a name an error calls unknown may have a near one, and where edits go. connection: Option, tab_id: String, + title: SharedString, // The Messages tab is showing, in place of the active result. messages_open: bool, // A tab was picked during this run, so its end leaves the choice alone. @@ -381,6 +382,16 @@ impl ResultsPanel { self.tab_id = tab_id; } + pub fn set_title(&mut self, title: SharedString) { + self.title = title; + } + + fn export(&self, grid: &Entity, window: &mut Window, cx: &mut App) { + let mut source = grid.read(cx).export_source(); + source.name = Some(self.title.to_string()); + crate::export_dialog::open(source, window, cx); + } + pub fn pending_edits(&self) -> usize { self.sets.iter().filter_map(|set| set.editor.as_ref()).map(|editor| editor.counts()).map(|(e, d)| e + d).sum() } @@ -953,9 +964,10 @@ impl ResultsPanel { })) }) }) - .item(PopupMenuItem::new(t(cx, "results.contextExportAs")).on_click(move |_, window, cx| { - crate::export_dialog::open(export.read(cx).export_source(), window, cx); - })); + .item( + PopupMenuItem::new(t(cx, "results.contextExportAs")) + .on_click(move |_, _, cx| export.update(cx, |_, cx| cx.emit(GridEvent::Export))), + ); } if let Some(plan) = plan { menu = menu.item( @@ -1253,7 +1265,7 @@ impl ResultsPanel { let value = grid.set().display(*row, *column).map(str::to_string); cell_viewer::open(name, type_name, value, window, cx); } - GridEvent::Export => crate::export_dialog::open(grid.read(cx).export_source(), window, cx), + GridEvent::Export => self.export(grid, window, cx), GridEvent::FocusedRowChanged if self.is_active(grid) => cx.emit(ResultsEvent::FocusedRowChanged), GridEvent::EditCell { row, column, value } => { let cell = [(*row, *column, value.clone())]; @@ -1349,6 +1361,11 @@ impl ResultsPanel { let writable = self.editable(); let Some(set) = self.sets.get_mut(index).filter(|set| set.grid.as_ref() == Some(grid)) else { return }; set.editor = writable.then(|| ResultEditor::new(table.clone(), grid.read(cx).set())).flatten(); + // SQL INSERTs name the table only when every column is its own, under the same name. + let names = grid.read(cx).set().columns.iter().map(|meta| Some(meta.name.as_str())); + if table.columns.iter().map(Option::as_deref).eq(names) { + grid.update(cx, |grid, _| grid.set_table_name(Some(table.table.clone()))); + } set.table = Some(table); self.sync_overlay(index, cx); } diff --git a/crates/barsql-ui/src/scenarios/result_edits.rs b/crates/barsql-ui/src/scenarios/result_edits.rs index 92759d2..5191603 100644 --- a/crates/barsql-ui/src/scenarios/result_edits.rs +++ b/crates/barsql-ui/src/scenarios/result_edits.rs @@ -5,6 +5,7 @@ use gpui_kit::{Entity, Modifiers, TestAppContext}; use super::driver::{Driver, open}; use crate::actions::{CloseTab, ToggleJsonPanel}; +use crate::export_dialog::Opened as ExportOpened; use crate::grid::Grid; use crate::query_tab::TxnState; @@ -69,6 +70,24 @@ fn an_edited_query_result_saves_to_its_table(cx: &mut TestAppContext) { assert_eq!(app.query("SELECT name FROM e2e_qe WHERE id = 1")[0][0], Value::Text("Alicia".into())); } +fn export_table(app: &mut Driver) -> String { + app.click("export-results"); + let dialog = app.cx.update(|_, cx| cx.try_global::().and_then(|opened| opened.0.upgrade())); + let table = app.cx.update(|_, cx| dialog.expect("the export dialog").read(cx).insert_table(cx)); + app.click("export-dismiss"); + table +} + +#[gpui_kit::test] +fn sql_inserts_from_a_result_go_into_its_table_when_every_column_is_its_own(cx: &mut TestAppContext) { + let mut app = editable(cx, "SELECT id, name FROM e2e_qe ORDER BY id"); + assert_eq!(export_table(&mut app), "e2e_qe"); + app.run("SELECT id, name AS n FROM e2e_qe ORDER BY id"); + let results = app.results(); + app.settle(|cx| cx.update(|_, cx| results.read(cx).editing_table().is_some())); + assert_eq!(export_table(&mut app), "", "a renamed column isn't the table's, so the name is left to the user"); +} + // Apply swaps in the saved rows without moving the focus. #[gpui_kit::test] fn the_json_viewer_shows_an_applied_result_edit(cx: &mut TestAppContext) { diff --git a/crates/barsql-ui/src/scenarios/table_view.rs b/crates/barsql-ui/src/scenarios/table_view.rs index b50ea9b..af2b2fb 100644 --- a/crates/barsql-ui/src/scenarios/table_view.rs +++ b/crates/barsql-ui/src/scenarios/table_view.rs @@ -162,6 +162,28 @@ fn hiding_a_column_scopes_the_export_to_the_visible_ones(cx: &mut TestAppContext assert_eq!(visible(&mut app), ["id", "name"]); } +#[gpui_kit::test] +fn a_table_with_more_pages_exports_its_loaded_rows_under_its_own_name(cx: &mut TestAppContext) { + let mut app = prepared( + cx, + &format!( + "CREATE TABLE e2e_tvpages {PEOPLE}; WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 150) + INSERT INTO e2e_tvpages SELECT i, 'p' || i FROM n" + ), + ); + browse(&mut app, "e2e_tvpages"); + app.click("export-results"); + let dialog = app.cx.update(|_, cx| cx.try_global::().and_then(|opened| opened.0.upgrade())).unwrap(); + let (label, summary, file) = app.cx.update(|_, cx| { + let dialog = dialog.read(cx); + (dialog.rows_label(cx), dialog.summary(cx), dialog.suggested_file(cx)) + }); + assert_eq!(label, "Loaded (100)", "only the first page is in the grid"); + assert!(summary.contains("100 loaded rows"), "{summary}"); + assert_eq!(file, "e2e_tvpages.csv"); + app.click("export-dismiss"); +} + #[gpui_kit::test] fn a_reopened_table_view_keeps_its_sort_and_hidden_columns(cx: &mut TestAppContext) { let mut app = prepared( diff --git a/crates/barsql-ui/src/structure_tab.rs b/crates/barsql-ui/src/structure_tab.rs index 13be556..276f51f 100644 --- a/crates/barsql-ui/src/structure_tab.rs +++ b/crates/barsql-ui/src/structure_tab.rs @@ -432,7 +432,11 @@ impl StructureTab { }); cell_viewer::open_editor(name, String::new(), value, on_save, window, cx); } - GridEvent::Export => crate::export_dialog::open(grid.read(cx).export_source(), window, cx), + GridEvent::Export => { + let mut source = grid.read(cx).export_source(); + source.name = Some(self.title(cx).to_string()); + crate::export_dialog::open(source, window, cx); + } _ => {} } } diff --git a/crates/barsql-ui/src/table_tab.rs b/crates/barsql-ui/src/table_tab.rs index 1641f14..0d93072 100644 --- a/crates/barsql-ui/src/table_tab.rs +++ b/crates/barsql-ui/src/table_tab.rs @@ -607,7 +607,12 @@ impl TableTab { }); cell_viewer::open_editor(name, type_name, value, on_save, window, cx); } - GridEvent::Export => crate::export_dialog::open(grid.read(cx).export_source(), window, cx), + GridEvent::Export => { + let mut source = grid.read(cx).export_source(); + source.more_rows = self.has_more; + source.name = Some(self.title.to_string()); + crate::export_dialog::open(source, window, cx); + } GridEvent::FocusedRowChanged => cx.emit(TableTabEvent::FocusedRowChanged), GridEvent::HiddenChanged => cx.emit(TableTabEvent::Edited), _ => {} diff --git a/crates/barsql-ui/src/toast.rs b/crates/barsql-ui/src/toast.rs index c367e75..650af9a 100644 --- a/crates/barsql-ui/src/toast.rs +++ b/crates/barsql-ui/src/toast.rs @@ -1,5 +1,6 @@ +use std::collections::HashSet; use std::rc::Rc; -use std::time::Duration; +use std::time::{Duration, Instant}; use crate::form; use crate::tokens::{ICON_SM, ICON_XS, RADIUS, TEXT_SM}; @@ -33,6 +34,10 @@ struct Toast { message: SharedString, kind: ToastKind, action: Option, + // Time left to show, None for one that stays. + left: Option, + // When its countdown started, None while held. + since: Option, _expiry: Task<()>, } @@ -40,6 +45,7 @@ struct Toast { pub struct Toasts { items: Vec, next_id: u64, + hovered: HashSet, } impl Global for Toasts {} @@ -73,30 +79,60 @@ pub fn push( return; } let duration = duration.unwrap_or(if kind == ToastKind::Error { ERROR_DURATION } else { DEFAULT_DURATION }); + let left = (!duration.is_zero()).then_some(duration); let toasts = cx.default_global::(); toasts.next_id += 1; let id = toasts.next_id; - let expiry = if duration.is_zero() { - Task::ready(()) - } else { - cx.spawn(async move |cx| { - cx.background_executor().timer(duration).await; - cx.update(|cx| dismiss(id, cx)); - }) - }; - cx.update_global::(|toasts, _| { - toasts.items.push(Toast { id, message, kind, action, _expiry: expiry }); - let overflow = toasts.items.len().saturating_sub(MAX_TOASTS); - toasts.items.drain(..overflow); - }); + toasts.items.push(Toast { id, message, kind, action, left, since: None, _expiry: Task::ready(()) }); + let overflow = toasts.items.len().saturating_sub(MAX_TOASTS); + toasts.items.drain(..overflow); + sync(cx); } pub fn dismiss(id: u64, cx: &mut App) { if cx.has_global::() { cx.update_global::(|toasts, _| toasts.items.retain(|toast| toast.id != id)); + sync(cx); } } +fn hover(id: u64, hovered: bool, cx: &mut App) { + let toasts = cx.default_global::(); + match hovered { + true => toasts.hovered.insert(id), + false => toasts.hovered.remove(&id), + }; + sync(cx); +} + +// While any toast is under the pointer every countdown holds, so none slides out from under it. +fn sync(cx: &mut App) { + let now = cx.background_executor().now(); + cx.update_global::(|toasts, cx| { + let items = &mut toasts.items; + toasts.hovered.retain(|id| items.iter().any(|toast| toast.id == *id)); + let held = !toasts.hovered.is_empty(); + for toast in items.iter_mut() { + let Some(left) = toast.left else { continue }; + match (held, toast.since) { + (true, Some(since)) => { + toast.left = Some(left.saturating_sub(now - since)); + (toast.since, toast._expiry) = (None, Task::ready(())); + } + (false, None) => { + let id = toast.id; + toast.since = Some(now); + toast._expiry = cx.spawn(async move |cx| { + cx.background_executor().timer(left).await; + cx.update(|cx| dismiss(id, cx)); + }); + } + _ => {} + } + } + }); +} + #[cfg(test)] pub fn action(index: usize, cx: &App) -> Option { cx.try_global::()?.items.get(index)?.action.clone() @@ -125,6 +161,8 @@ pub fn render(window: &Window, cx: &App) -> Option { }; h_row() .id(("toast", id as usize)) + .debug_selector(move || format!("toast-{id}")) + .on_hover(move |hovered, _, cx| hover(id, *hovered, cx)) .gap(rems(0.769)) .pl(rem * 0.923 + px(2.)) .pr(rems(0.923)) @@ -195,9 +233,79 @@ fn h_row() -> Div { mod tests { use std::time::Duration; - use gpui_kit::TestAppContext; + use gpui_kit::{ + App, Context, IntoElement, Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, Window, div, + point, px, + }; + + use super::{ToastKind, error, hover, messages, push, success}; + use crate::test_support::Env; + + fn shown(cx: &mut App) -> Vec { + messages(cx).into_iter().map(|(_, message)| message).collect() + } + + fn wait(cx: &mut TestAppContext, ms: u64) { + cx.executor().advance_clock(Duration::from_millis(ms)); + cx.run_until_parked(); + } - use super::{ToastKind, error, messages, push, success}; + #[gpui_kit::test] + fn a_hovered_toast_holds_every_countdown_until_the_pointer_leaves(cx: &mut TestAppContext) { + cx.update(|cx| success("first", cx)); + wait(cx, 1000); + cx.update(|cx| { + success("second", cx); + hover(1, true, cx); + }); + wait(cx, 10_000); + cx.update(|cx| success("third", cx)); + wait(cx, 10_000); + assert_eq!(cx.update(shown), ["first", "second", "third"], "nothing expires under the pointer"); + + cx.update(|cx| hover(1, false, cx)); + wait(cx, 2400); + assert_eq!(cx.update(shown), ["first", "second", "third"], "the first had 2.5 s left"); + wait(cx, 200); + assert_eq!(cx.update(shown), ["second", "third"]); + wait(cx, 1000); + assert!(cx.update(shown).is_empty(), "the others had a whole 3.5 s"); + } + + #[gpui_kit::test] + fn dismissing_the_hovered_toast_lets_the_rest_go(cx: &mut TestAppContext) { + cx.update(|cx| { + success("first", cx); + success("second", cx); + hover(2, true, cx); + super::dismiss(2, cx); + }); + wait(cx, 3500); + assert!(cx.update(shown).is_empty(), "no pointer is left over a toast"); + } + + struct Stack; + + impl Render for Stack { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + div().size_full().children(super::render(window, cx)) + } + } + + #[gpui_kit::test] + fn the_pointer_on_a_drawn_toast_holds_it(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let (_, cx) = cx.add_window_view(|_, _| Stack); + cx.update(|_, cx| success("saved", cx)); + cx.update(|window, cx| window.draw(cx).clear(cx)); + let toast = cx.debug_bounds("toast-1").expect("the toast is drawn"); + cx.simulate_mouse_move(toast.center(), None, Modifiers::none()); + wait(cx, 10_000); + assert_eq!(cx.update(|_, cx| shown(cx)), ["saved"], "held under the pointer"); + cx.simulate_mouse_move(point(px(1.), px(1.)), None, Modifiers::none()); + wait(cx, 3500); + assert!(cx.update(|_, cx| shown(cx)).is_empty(), "gone once the pointer moved off"); + } #[gpui_kit::test] fn five_at_most_and_errors_linger_longer(cx: &mut TestAppContext) {