diff --git a/src-tauri/src/db/migrations.rs b/src-tauri/src/db/migrations.rs index 3db78839..54334e7e 100644 --- a/src-tauri/src/db/migrations.rs +++ b/src-tauri/src/db/migrations.rs @@ -34,6 +34,47 @@ pub struct MigrationProject { /// The folder the migrations were read from. pub dir: String, pub files: Vec, + /// Every `.sql` file in the folder by file name, journal or not: what + /// `wrangler d1 migrations apply` runs and records in `d1_migrations`. + pub sql_files: Vec, + /// The D1 database a `wrangler.toml` / `wrangler.json(c)` next to the + /// migrations names, for the apply command. + pub wrangler_db: Option, +} + +/// The first `database_name = "x"` (TOML) or `"database_name": "x"` (JSON). +fn database_name(text: &str) -> Option { + for (i, _) in text.match_indices("database_name") { + let rest = text[i + "database_name".len()..].trim_start_matches('"').trim_start(); + let Some(rest) = rest.strip_prefix([':', '=']) else { continue }; + let rest = rest.trim_start(); + let q = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?; + let v: String = rest[1..].chars().take_while(|c| *c != q).collect(); + if !v.is_empty() { + return Some(v); + } + } + None +} + +/// `database_name` from the first wrangler config in `from` or a folder above +/// it, up to `root`. +fn wrangler_db(root: &Path, from: &Path) -> Option { + let mut dir = Some(from); + while let Some(d) = dir { + for f in ["wrangler.toml", "wrangler.jsonc", "wrangler.json"] { + if let Ok(text) = std::fs::read_to_string(d.join(f)) { + if let Some(name) = database_name(&text) { + return Some(name); + } + } + } + if d == root { + break; + } + dir = d.parent(); + } + None } const MAX_SQL: usize = 2 * 1024 * 1024; @@ -73,6 +114,33 @@ fn is_drizzle_dir(dir: &Path) -> bool { dir.join("meta").join("_journal.json").is_file() } +/// A plain `migrations/` folder of `.sql` files, as Wrangler (D1) keeps them. +fn is_sql_dir(dir: &Path) -> bool { + dir.file_name().is_some_and(|n| n == "migrations") + && std::fs::read_dir(dir) + .map(|rd| rd.flatten().any(|e| e.path().extension().is_some_and(|x| x == "sql"))) + .unwrap_or(false) +} + +/// Every `.sql` file directly in `dir`, by name; `name` keeps the `.sql` +/// (that's what `d1_migrations.name` holds). +pub fn read_sql_dir(dir: &Path) -> Vec { + let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut names: Vec = rd + .flatten() + .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|x| x == "sql")) + .filter_map(|e| e.file_name().to_str().map(String::from)) + .collect(); + names.sort(); + names + .into_iter() + .filter_map(|name| { + let (sql, checksum) = read_sql(&dir.join(&name))?; + Some(MigrationFile { name, sql, checksum, when: None }) + }) + .collect() +} + /// Folders worth looking into for a project root, a few levels down, skipping /// the ones that are never migrations. fn walk(root: &Path, depth: usize, out: &mut Vec) { @@ -113,6 +181,13 @@ pub fn find(root: &Path, tool: Option<&str>) -> Option<(String, PathBuf)> { return Some(("prisma".into(), d.clone())); } } + // No journal anywhere: a Wrangler migrations folder reads like Drizzle's + // SQL files, applied by name. + if want_drizzle { + if let Some(d) = dirs.iter().find(|d| is_sql_dir(d) && !is_prisma_dir(d)) { + return Some(("drizzle".into(), d.clone())); + } + } None } @@ -135,6 +210,10 @@ pub fn read_prisma(dir: &Path) -> Vec { } pub fn read_drizzle(dir: &Path) -> Result, String> { + if !is_drizzle_dir(dir) { + // A Wrangler folder: its files are the migrations, in name order. + return Ok(read_sql_dir(dir).into_iter().map(|f| MigrationFile { name: f.name.trim_end_matches(".sql").to_string(), ..f }).collect()); + } let journal = std::fs::read_to_string(dir.join("meta").join("_journal.json")) .map_err(|e| format!("Could not read meta/_journal.json: {e}"))?; let v: serde_json::Value = serde_json::from_str(&journal).map_err(|e| format!("meta/_journal.json isn't valid JSON: {e}"))?; @@ -174,7 +253,9 @@ pub async fn migrations_project(dir: String, tool: Option) -> Result>(), ["0000_init.sql", "0001_posts.sql", "0001b_hand_written.sql"]); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_wrangler_migrations_folder_reads_as_drizzle() { + let root = tmp("wrangler"); + let m = root.join("migrations"); + std::fs::create_dir_all(&m).unwrap(); + std::fs::write(m.join("0002_b.sql"), "SELECT 2;").unwrap(); + std::fs::write(m.join("0001_a.sql"), "SELECT 1;").unwrap(); + let (tool, dir) = find(&root, None).unwrap(); + assert_eq!((tool.as_str(), dir.clone()), ("drizzle", m.clone())); + let files = read_drizzle(&dir).unwrap(); + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["0001_a", "0002_b"]); let _ = std::fs::remove_dir_all(&root); } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 401c4bdd..af62ba02 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -498,6 +498,8 @@ pub fn run() { .manage(launch::LaunchState::default()) .setup(move |app| { display_backend::watch(app.handle().clone()); + // Local servers marked "Start with Stroke". + local_servers::autostart(app.handle().clone()); // Linux packages renamed the binary from `app` to `stroke` (2.5.6), and // a launch-at-login entry stores the binary's path. Re-enabling an // enabled entry rewrites it with the current path, so it doesn't @@ -952,6 +954,10 @@ pub fn run() { local_servers::local_server_free_port, local_servers::brew_services_list, local_servers::brew_service_action, + local_servers::local_servers_discover, + local_servers::local_server_reveal, + local_servers::open_local_servers_window, + local_servers::local_server_connect_in, cloud_backup::backup_job_save, cloud_backup::backup_job_patch, cloud_backup::backup_job_delete, diff --git a/src-tauri/src/local_servers.rs b/src-tauri/src/local_servers.rs index f2c2a599..aa0a6119 100644 --- a/src-tauri/src/local_servers.rs +++ b/src-tauri/src/local_servers.rs @@ -35,6 +35,9 @@ pub struct LocalServer { pub runtime: String, #[serde(default)] pub created_at: i64, + /// Start it when Stroke opens. + #[serde(default)] + pub autostart: bool, } #[derive(Debug, Clone, Serialize)] @@ -45,6 +48,26 @@ pub struct ServerState { pub running: bool, /// Why it can't run right now (Docker not running, binary gone). pub problem: Option, + /// When the running server started, ms since the epoch. + pub started_at: Option, + /// Size of a native server's data folder. + pub disk_bytes: Option, + /// Where a native server keeps its data. + pub data_dir: Option, +} + +/// A database server listening on this computer that Stroke didn't make: +/// Postgres.app, a Homebrew service, a docker compose container. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoundServer { + pub engine: String, + pub port: u16, + /// docker | process + pub source: String, + /// The container's name, or the engine for a plain process. + pub name: String, + pub image: Option, } #[derive(Debug, Clone, Serialize)] @@ -436,6 +459,40 @@ async fn docker_running(id: &str) -> Result { } } +/// When a running server started: Docker's StartedAt, Postgres's +/// postmaster.pid (its third line), or the pid file's time for the rest. +async fn started_at(app: &AppHandle, s: &LocalServer) -> Option { + if s.runtime == "docker" { + let out = run(&docker().ok()?, &["inspect", "-f", "{{.State.StartedAt}}", &container(&s.id)]).await.ok()?; + return chrono::DateTime::parse_from_rfc3339(out.trim()).ok().map(|t| t.timestamp_millis()); + } + let dir = server_dir(app, &s.id).ok()?; + if s.engine == "postgres" { + let text = std::fs::read_to_string(dir.join("data").join("postmaster.pid")).ok()?; + return text.lines().nth(2)?.trim().parse::().ok().map(|t| t * 1000); + } + let modified = std::fs::metadata(pid_file(app, &s.id).ok()?).ok()?.modified().ok()?; + Some(chrono::DateTime::::from(modified).timestamp_millis()) +} + +/// Bytes under `dir`, files only, not following links. +fn dir_size(dir: &Path) -> u64 { + let mut total = 0; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { continue }; + for e in rd.flatten() { + let Ok(meta) = e.metadata() else { continue }; + if meta.is_dir() { + stack.push(e.path()); + } else if meta.is_file() { + total += meta.len(); + } + } + } + total +} + async fn state_of(app: &AppHandle, s: LocalServer, docker_ok: bool) -> ServerState { let (running, problem) = if s.runtime == "docker" { if !docker_ok { @@ -460,7 +517,203 @@ async fn state_of(app: &AppHandle, s: LocalServer, docker_ok: bool) -> ServerSta let problem = if up || native_binary(&s.engine).is_some() { None } else { Some(format!("{} isn't installed anymore", s.engine)) }; (up, problem) }; - ServerState { server: s, running, problem } + let started_at = if running { started_at(app, &s).await } else { None }; + let (disk_bytes, data_dir) = if s.runtime == "native" { + match server_dir(app, &s.id) { + Ok(dir) => { + let data = dir.join("data"); + let shown = data.to_string_lossy().into_owned(); + let size = tokio::task::spawn_blocking(move || dir_size(&data)).await.ok(); + (size, Some(shown)) + } + Err(_) => (None, None), + } + } else { + (None, None) + }; + ServerState { server: s, running, problem, started_at, disk_bytes, data_dir } +} + +// ── Finding servers Stroke didn't make ────────────────────────────────────── + +/// Ports each engine is usually found on. +const PROBE_PORTS: &[(&str, std::ops::RangeInclusive)] = &[ + ("postgres", 5432..=5440), + ("mysql", 3306..=3310), + ("redis", 6379..=6382), + ("mongodb", 27017..=27020), +]; + +/// What answers on a port, checked by speaking a few bytes of the engine's +/// protocol: Postgres answers an SSLRequest with S or N, MySQL and MariaDB +/// greet first with protocol version 10, Redis answers PING. MongoDB has no +/// cheap greeting, so an open port in its range counts. +async fn identify(engine: &str, port: u16) -> Option { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let t = Duration::from_millis(500); + let mut stream = tokio::time::timeout(t, tokio::net::TcpStream::connect(("127.0.0.1", port))).await.ok()?.ok()?; + let mut buf = [0u8; 128]; + match engine { + "postgres" => { + stream.write_all(&[0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]).await.ok()?; + let n = tokio::time::timeout(t, stream.read(&mut buf)).await.ok()?.ok()?; + (n == 1 && (buf[0] == b'S' || buf[0] == b'N')).then(|| "postgres".to_string()) + } + "mysql" => { + let n = tokio::time::timeout(t, stream.read(&mut buf)).await.ok()?.ok()?; + if n > 5 && buf[4] == 10 { + let greeting = String::from_utf8_lossy(&buf[5..n]).to_ascii_lowercase(); + Some(if greeting.contains("mariadb") { "mariadb" } else { "mysql" }.to_string()) + } else { + None + } + } + "redis" => { + stream.write_all(b"PING\r\n").await.ok()?; + let n = tokio::time::timeout(t, stream.read(&mut buf)).await.ok()?.ok()?; + let reply = String::from_utf8_lossy(&buf[..n]); + (reply.starts_with("+PONG") || reply.starts_with("-NOAUTH") || reply.starts_with("-ERR")).then(|| "redis".to_string()) + } + "mongodb" => Some("mongodb".to_string()), + _ => None, + } +} + +/// Engine of a container image, when it's a database. +fn image_engine(image: &str) -> Option<&'static str> { + let base = image.rsplit('/').next().unwrap_or(image).split([':', '@']).next().unwrap_or(""); + Some(match base { + b if b.starts_with("postgres") || b.starts_with("postgis") || b == "timescaledb" || b.starts_with("pgvector") => "postgres", + b if b.starts_with("mariadb") => "mariadb", + b if b.starts_with("mysql") || b.starts_with("percona") => "mysql", + b if b.starts_with("redis") || b.starts_with("valkey") => "redis", + b if b.starts_with("mongo") => "mongodb", + _ => return None, + }) +} + +/// Host ports a `docker ps` Ports column publishes ("0.0.0.0:5432->5432/tcp, [::]:5432->5432/tcp"). +fn published_ports(ports: &str) -> Vec { + let mut out: Vec = ports + .split(',') + .filter_map(|p| p.split("->").next()?.rsplit(':').next()?.trim().parse().ok()) + .collect(); + out.dedup(); + out +} + +#[tauri::command] +pub async fn local_servers_discover(app: AppHandle) -> Result, String> { + let ours: Vec = load(&app)?.iter().map(|s| s.port).collect(); + let mut found: Vec = Vec::new(); + // Containers first: they carry a name worth showing. + if let Some(d) = which("docker") { + if let Ok(out) = run(&d, &["ps", "--format", "{{.Names}}\t{{.Image}}\t{{.Ports}}\t{{.Labels}}"]).await { + for line in out.lines() { + let cols: Vec<&str> = line.split('\t').collect(); + if cols.len() < 3 || cols.get(3).is_some_and(|l| l.contains("app=stroke")) { + continue; + } + let Some(engine) = image_engine(cols[1]) else { continue }; + for port in published_ports(cols[2]) { + if ours.contains(&port) || found.iter().any(|f| f.port == port) { + continue; + } + found.push(FoundServer { engine: engine.into(), port, source: "docker".into(), name: cols[0].to_string(), image: Some(cols[1].to_string()) }); + } + } + } + } + let probes = PROBE_PORTS.iter().flat_map(|(engine, range)| range.clone().map(move |p| (*engine, p))) + .filter(|(_, p)| !ours.contains(p) && !found.iter().any(|f| f.port == *p)) + .map(|(engine, port)| async move { identify(engine, port).await.map(|e| (e, port)) }); + for (engine, port) in futures::future::join_all(probes).await.into_iter().flatten() { + let label = match engine.as_str() { "postgres" => "PostgreSQL", "mysql" => "MySQL", "mariadb" => "MariaDB", "redis" => "Redis", _ => "MongoDB" }; + found.push(FoundServer { engine, port, source: "process".into(), name: label.into(), image: None }); + } + found.sort_by_key(|f| f.port); + Ok(found) +} + +/// Start the servers marked to start with Stroke. Runs once at launch. +pub fn autostart(app: AppHandle) { + tauri::async_runtime::spawn(async move { + let Ok(servers) = load(&app) else { return }; + for s in servers.into_iter().filter(|s| s.autostart) { + if let Err(e) = local_server_start(app.clone(), s.id.clone()).await { + log::warn!("local server {} didn't start at launch: {e}", s.name); + } + } + }); +} + +/// Show a native server's data folder in the file manager. +#[tauri::command] +pub async fn local_server_reveal(app: AppHandle, id: String) -> Result<(), String> { + let s = find(&app, &id)?; + if s.runtime != "native" { + return Err("A Docker server keeps its data in a Docker volume".into()); + } + let data = server_dir(&app, &id)?.join("data"); + tauri_plugin_opener::reveal_item_in_dir(&data).map_err(|e| e.to_string()) +} + +/// The Local servers window: one per app, focused when it's already open. +#[tauri::command] +pub async fn open_local_servers_window(app: AppHandle, from: String) -> Result<(), String> { + let label = "main-local-servers"; + if let Some(w) = app.webview_windows().get(label) { + let _ = w.unminimize(); + let _ = w.set_focus(); + return Ok(()); + } + let from: String = from.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(64).collect(); + let url = format!("/?view=local-servers&from={from}"); + let mut builder = tauri::WebviewWindowBuilder::new(&app, label, tauri::WebviewUrl::App(url.into())) + .title("Local Servers") + .inner_size(980.0, 640.0) + .min_inner_size(720.0, 460.0) + .resizable(true) + .visible(false) + .background_color(tauri::window::Color(8, 8, 8, 255)) + .devtools(cfg!(debug_assertions)) + .zoom_hotkeys_enabled(false) + .on_navigation(crate::navigation_allowed); + #[cfg(target_os = "macos")] + { + builder = builder + .title_bar_style(tauri::TitleBarStyle::Overlay) + .hidden_title(true) + .traffic_light_position(crate::mac_chrome::traffic_light_position()); + } + #[cfg(not(target_os = "macos"))] + { + builder = builder.decorations(false); + } + let window = builder.build().map_err(|e| e.to_string())?; + let surface = crate::surface_for_theme(window.theme().unwrap_or(tauri::Theme::Dark)); + let _ = window.set_background_color(Some(surface)); + crate::set_webview_backdrop(&window, surface); + crate::guard_webview(&window); + crate::arm_reveal_failsafe(&window); + Ok(()) +} + +/// Connect to a server in an app window: the Local servers window hands the +/// connection to the window it was opened from (or the first main window) +/// and brings that one forward. +#[tauri::command] +pub async fn local_server_connect_in(app: AppHandle, target: String, connection: serde_json::Value) -> Result<(), String> { + let windows = app.webview_windows(); + let w = windows + .get(target.as_str()) + .filter(|_| target.starts_with("main") && target != "main-local-servers" && !target.starts_with("main-dashboard-")) + .or_else(|| windows.get("main")) + .or_else(|| windows.iter().find(|(l, _)| l.starts_with("main") && *l != "main-local-servers" && !l.starts_with("main-dashboard-")).map(|(_, w)| w)) + .ok_or("Open a Stroke window first")?; + let _ = w.unminimize(); + let _ = w.set_focus(); + w.emit("local-server-connect", connection).map_err(|e| e.to_string()) } // ── Commands ──────────────────────────────────────────────────────────────── @@ -548,6 +801,7 @@ pub async fn local_server_create(app: AppHandle, spec: NewServer) -> Result Result<(), Strin /// Rename a server or move it to another port (it has to be stopped for a port change). #[tauri::command] -pub async fn local_server_update(app: AppHandle, id: String, name: Option, port: Option) -> Result { +pub async fn local_server_update(app: AppHandle, id: String, name: Option, port: Option, autostart: Option) -> Result { let mut servers = load(&app)?; let idx = servers.iter().position(|s| s.id == id).ok_or("That server no longer exists")?; + if let Some(a) = autostart { + servers[idx].autostart = a; + } if let Some(n) = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) { servers[idx].name = n; } @@ -841,10 +1098,21 @@ mod tests { assert!(validate(&spec("oracle", "23", 1521, "docker"), &[]).is_err()); assert!(validate(&spec("redis", "7; rm -rf /", 6380, "docker"), &[]).is_err()); assert!(validate(&spec("redis", "7", 80, "docker"), &[]).unwrap_err().contains("1024")); - let taken = LocalServer { id: "a".into(), name: "Air".into(), engine: "postgres".into(), version: "16".into(), port: 5432, runtime: "docker".into(), created_at: 0 }; + let taken = LocalServer { id: "a".into(), name: "Air".into(), engine: "postgres".into(), version: "16".into(), port: 5432, runtime: "docker".into(), created_at: 0, autostart: false }; assert!(validate(&spec("mysql", "8.4", 5432, "docker"), &[taken]).unwrap_err().contains("Air")); } + #[test] + fn other_servers_are_recognised_by_image_and_port() { + assert_eq!(image_engine("postgres:16-alpine"), Some("postgres")); + assert_eq!(image_engine("docker.io/bitnami/mariadb:11"), Some("mariadb")); + assert_eq!(image_engine("ghcr.io/x/pgvector/pgvector:pg17"), Some("postgres")); + assert_eq!(image_engine("valkey/valkey:8"), Some("redis")); + assert_eq!(image_engine("nginx:latest"), None); + assert_eq!(published_ports("0.0.0.0:5433->5432/tcp, [::]:5433->5432/tcp"), vec![5433]); + assert_eq!(published_ports("6379/tcp"), Vec::::new()); + } + #[test] fn docker_images_and_ports() { assert_eq!(docker_image("mongodb", "8.0").unwrap().0, "mongo:8.0"); diff --git a/src/App.svelte b/src/App.svelte index b2fe8fc0..f9178eef 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -8,6 +8,8 @@ // A window opened for one dashboard (open_dashboard_window) shows only that. const params = typeof location !== 'undefined' ? new URLSearchParams(location.search) : new URLSearchParams() const dashboardView = params.get('view') === 'dashboard' ? { dash: params.get('dash') ?? '', conn: params.get('conn') ?? '' } : null + // The Local servers window (open_local_servers_window). + const localServersFrom = params.get('view') === 'local-servers' ? params.get('from') || 'main' : null import LicenseGate from './lib/components/LicenseGate.svelte' import AppLockGate from './lib/components/AppLockGate.svelte' import AppErrorBoundary from './lib/components/AppErrorBoundary.svelte' @@ -103,6 +105,10 @@ {#if dashboardView} + {:else if localServersFrom} + {#await import('./lib/components/LocalServersWindow.svelte') then { default: LocalServersWindow }} + + {/await} {:else} {/if} diff --git a/src/lib/components/DashboardPage.svelte b/src/lib/components/DashboardPage.svelte index 605d657c..619ab84b 100644 --- a/src/lib/components/DashboardPage.svelte +++ b/src/lib/components/DashboardPage.svelte @@ -19,6 +19,8 @@ reorderItems, addQueryToDashboard, updateItem, + dashboardsConnectionId, + flushDashboards, } from "$lib/stores/dashboards.js"; import { listSavedQueries, queryTitle } from "$lib/stores/query-history.js"; import { executeSql } from "$lib/api.js"; @@ -264,8 +266,12 @@ async function openWindow() { if (!activeDash || !connection?.id) return; try { + // The window reads the dashboard from storage: write pending edits now, + // and pass the key the dashboards are stored under (the saved + // connection's id), not the live connection's. + flushDashboards(); const { invoke } = await import("@tauri-apps/api/core"); - await invoke("open_dashboard_window", { dashboardId: activeDash.id, connectionId: connection.id, title: activeDash.name }); + await invoke("open_dashboard_window", { dashboardId: activeDash.id, connectionId: dashboardsConnectionId() || connection.id, title: activeDash.name }); } catch (e) { toast.error("Could not open the window", { description: String(e) }); } diff --git a/src/lib/components/DashboardWindow.svelte b/src/lib/components/DashboardWindow.svelte index bd78b9de..e2692804 100644 --- a/src/lib/components/DashboardWindow.svelte +++ b/src/lib/components/DashboardWindow.svelte @@ -1,16 +1,16 @@ -
- -
-
- + + +
+ + {#if !fullscreen} +
+
+ + {#if dashOptions.length > 1} + { currentId = v; live = {} }} + /> + {:else} +

{dash?.name ?? 'Dashboard'}

+ {/if} + {#if connName} + + {/if} +
+
{#if dash} + + ({ value: String(v), label: v ? `Every ${l}` : 'Auto refresh off' }))} onchange={(v) => dash && updateDashboard(dash.id, { refreshSec: Number(v) })} /> + {/if} -
-

- {dash?.name ?? 'Dashboard'} -

-
- {#if connName} - - - {connName} - - {/if} - {#if !isMac}{/if} -
+ {#if !isMac}{/if} + + {:else} + + {/if} -
- {#if !dash} -
- -

This dashboard was deleted

+
+ {#if ready && !dash} +
+ +
+

This dashboard isn't here anymore

+

It was deleted, or it belongs to another connection.

+
+ {#if dashOptions.length} +
+ {#each dashOptions as o (o.value)} + + {/each} +
+ {/if}
- {:else if dash.items.length === 0} -
- -

Nothing on {dash.name} yet

-

Add charts or saved queries from the Dashboard tab; they show up here.

+ {:else if dash && dash.items.length === 0} +
+ +
+

Nothing on {dash.name} yet

+

Add charts or saved queries in the Dashboard tab. They show up here as you add them.

+
- {:else} -
+ {:else if dash} +
{#each dash.items as item, i (item.id)} {@const chart = getChart(item.chartId)} {@const l = live[keyOf(item)]} @@ -186,34 +277,63 @@ {@const color = REPORT_COLORS[i % REPORT_COLORS.length]} {@const status = l?.loading && !l?.result ? 'loading' : l?.error ? 'error' : l?.at ? 'ok' : sqlOf(item) ? 'loading' : 'idle'}
+
+ +

{title}

+ + {status === 'error' ? 'Failed' : l?.loading ? 'Running' : l?.at ? agoText(l.at, now) : ''} + + {#if sqlOf(item)} + + {/if} +
{#if l?.error} -
-

Query failed

-

{l.error}

+
+

Query failed

+

{l.error}

+
{:else if view?.kpi} -
+
{formatKpi(view.kpi.value)} - {view.kpi.label} + {view.kpi.label}
{:else if view?.table} -
+
- + {#each view.table.columns as c, ci (ci)} - + {/each} {#each view.table.rows as row, ri (ri)} - + {#each row as cell, ci (ci)} {/each} @@ -223,44 +343,15 @@
{c}{c}
{cell === null ? 'NULL' : typeof cell === 'number' ? reportNumber(cell) : typeof cell === 'object' ? JSON.stringify(cell) : String(cell)}
{:else if view?.option} - + + {:else if status === 'loading'} + {:else if status === 'idle'} -
+
{chart ? 'This chart writes, so it only runs from the editor' : 'This chart was deleted'}
{/if}
- -
-
- - {#if sqlOf(item)} - - {/if} -
-

{title}

-

- {status === 'ok' ? 'OK' : status === 'error' ? 'Failed' : status === 'loading' ? 'Running' : '·'} -

-
{/each}
diff --git a/src/lib/components/DataTable.svelte b/src/lib/components/DataTable.svelte index f48b100b..94ae58e4 100644 --- a/src/lib/components/DataTable.svelte +++ b/src/lib/components/DataTable.svelte @@ -4582,8 +4582,12 @@ import FilterX from "@lucide/svelte/icons/filter-x"; const auto = new Set() for (const col of cols) { const dt = col.dataType ?? col.data_type ?? "" - if (stored[col.name] == null) auto.add(col.name) - next[col.name] = clampColumnWidth(stored[col.name] ?? defaultColumnWidth(dt)) + // Builds before 2.21 saved every column's width when one was dragged, + // the untouched ones at their fixed type default (420 for text). A + // stored width equal to that default was never chosen: fit it instead. + const own = stored[col.name] != null && stored[col.name] !== clampColumnWidth(defaultColumnWidth(dt)) ? stored[col.name] : null + if (own == null) auto.add(col.name) + next[col.name] = clampColumnWidth(own ?? defaultColumnWidth(dt)) } columnWidths = next // Columns nobody has sized are fitted to their content once rows arrive. @@ -4704,7 +4708,24 @@ import FilterX from "@lucide/svelte/icons/filter-x"; const w = fittedWidth(columns[i], i) if (w == null) return columnWidths = { ...columnWidths, [colName]: w } - if (columnWidthsKey) saveColumnWidths(columnWidthsKey, columnWidths) + keepWidth(colName, w) + } + + /** + * Store one column's width, chosen by hand. Only columns someone sized are + * stored; the rest stay automatic and are fitted to what they hold. + * @param {string} colName @param {number} w + */ + function keepWidth(colName, w) { + if (!columnWidthsKey) return + const stored = loadColumnWidths(columnWidthsKey) + // Drop the type defaults older builds stored for untouched columns. + for (const col of columns) { + const dt = col.dataType ?? col.data_type ?? '' + if (stored[col.name] === clampColumnWidth(defaultColumnWidth(dt))) delete stored[col.name] + } + stored[colName] = w + saveColumnWidths(columnWidthsKey, stored) } // Virtual (relationship / expression) column widths persist alongside real @@ -4775,7 +4796,7 @@ import FilterX from "@lucide/svelte/icons/filter-x"; if (columnWidthsKey && resizingColName) { if (resizingColName.startsWith('__vrel__')) saveColumnWidths(`${columnWidthsKey}\x00__vrel`, _vrelWidths); else if (resizingColName.startsWith('__vcol__')) saveColumnWidths(`${columnWidthsKey}\x00__vcol`, _vexprWidths); - else saveColumnWidths(columnWidthsKey, columnWidths); + else keepWidth(resizingColName, columnWidths[resizingColName]); } resizingColName = null; } @@ -4855,6 +4876,18 @@ import FilterX from "@lucide/svelte/icons/filter-x"; } } + /** Every column back to automatic: fitted to its content, nothing stored. */ + function fitAllColumns() { + /** @type {Record} */ + const fitted = {} + columns.forEach((col, i) => { + const w = rows.length ? fittedWidth(col, i) : null + if (w != null) fitted[col.name] = w + }) + columnWidths = { ...columnWidths, ...fitted } + if (columnWidthsKey) saveColumnWidths(columnWidthsKey, {}) + } + // ── Per-tab expand/sub-view state preservation ─────────────────────────────── // Expand rows and FK sub-view are saved per columnWidthsKey so switching tabs // restores exactly what the user had open in each table. @@ -9698,6 +9731,10 @@ import FilterX from "@lucide/svelte/icons/filter-x"; {$t('menu.resetWidth')} + runMenuAction(fitAllColumns)}> + + {$t('menu.fitAllColumns')} + diff --git a/src/lib/components/LocalServersDialog.svelte b/src/lib/components/LocalServersDialog.svelte deleted file mode 100644 index 2e8d6e29..00000000 --- a/src/lib/components/LocalServersDialog.svelte +++ /dev/null @@ -1,481 +0,0 @@ - - - - - {#if view === 'list'} - - Local servers - Database servers running on this computer. - - - - -
- {#if env && !env.docker} -

- - {env.dockerInstalled ? "Docker isn't running. Start Docker Desktop for Docker servers; native Postgres works without it." : "Docker isn't installed. Native Postgres works without it."} -

- {/if} - - {#if servers.length === 0 && !loading} -
- -
-

No local servers yet

-

Postgres, MySQL, MariaDB, Redis or MongoDB, any version, ready in a minute.

-
- -
- {:else} -
    - {#each servers as s (s.id)} - {@const e = engineOf(s.engine)} -
  • - - - - -
    -

    {s.name}

    -

    - {#if s.problem}{s.problem} - {:else}{e.label} {s.version} · {s.running ? `127.0.0.1:${s.port}` : `port ${s.port}`} · {runtimeLabel(s.runtime)}{/if} -

    -
    - - - - - - - - void showLogs(s)}>Logs - void editPort(s)}>Change port… - - void remove(s)}>Delete with its data - - -
  • - {/each} -
- {/if} - - {#if env?.brew && brew.length} -
- - {#if brewOpen} -
    - {#each brew as b (b.name)} -
  • - {b.name} - -
  • - {/each} -
- {/if} -
- {/if} -
- {:else if view === 'port' && portFor} - - Change the port of {portFor.name} - Pick a new port for this server. - -
{ e.preventDefault(); void savePort() }}> - - {#if portError}{/if} -
- - -
-
- {:else if view === 'logs'} - - {logsFor} logs - The last lines the server wrote. - - -
{logs}
- {:else} - - New local server - Pick an engine, a version and where it runs. - -
{ e.preventDefault(); void create() }}> -
- Engine -
- {#each ENGINES as e (e.id)} - {@const on = fEngine === e.id} - - {/each} -
-
-
- Version -
- {#each engine.versions as v (v)} - {@const on = fVersion === v} - - {/each} -
-
-
- Runs on -
- {#each [ - { id: /** @type {const} */ ('docker'), Icon: Container, title: 'Docker', ok: dockerOk, - body: dockerOk ? 'A container on 127.0.0.1, its data in a Docker volume.' : env?.dockerInstalled ? 'Start Docker Desktop to use this.' : 'Install Docker Desktop to use this.' }, - { id: /** @type {const} */ ('native'), Icon: Cpu, title: 'Native', ok: nativeOk, - body: fEngine === 'postgres' ? `Downloads Postgres ${fVersion} once, about 30 MB.` : nativeOk ? `Uses the ${engine.label} installed here.` : `${engine.label} isn't installed on this computer.` }, - ] as r (r.id)} - {@const on = fRuntime === r.id} - - {/each} -
-
-
- - -
- {#if portTaken}

{portTaken.name} already uses port {portNum}.

{/if} - {#if progress} -
-

{progress.message}

-
-
-
-
- {/if} - {#if formError}{/if} -
- - -
-
- {/if} -
-
diff --git a/src/lib/components/LocalServersWindow.svelte b/src/lib/components/LocalServersWindow.svelte new file mode 100644 index 00000000..ada88ae7 --- /dev/null +++ b/src/lib/components/LocalServersWindow.svelte @@ -0,0 +1,773 @@ + + +{#snippet engineTile(/** @type {string} */ id, /** @type {string} */ size, /** @type {string | null} */ dot)} + + + {#if dot}{/if} + +{/snippet} + +{#snippet copyButton(/** @type {string} */ text, /** @type {string} */ what, /** @type {string} */ label)} + +{/snippet} + +{#snippet connectionCard(/** @type {{ engine: string, port: number }} */ s, /** @type {string} */ key)} + {@const url = connectionUrl(s)} +
+
+

Connection

+
+
+ {#each fields(s) as [k, v] (k)} +
{k}
+
{v}
+ {#if k !== 'Password'}{@render copyButton(v, `${key}:${k}`, `Copy ${k.toLowerCase()}`)}{:else}{/if} + {/each} +
+
+
+ {url} + {@render copyButton(url, `${key}:url`, 'Copy URL')} +
+
+ {envName(s.engine)}="{url}" + {@render copyButton(`${envName(s.engine)}="${url}"`, `${key}:env`, 'Copy as .env line')} +
+
+
+{/snippet} + +
+
+
+ +

Local Servers

+
+
+ + + {#if !isMac}{/if} +
+ +
+ + + + +
+ {#if selected === 'new'} +
{ e.preventDefault(); void create() }}> +
+

New server

+

Listens on 127.0.0.1 only, with no password. For development on this computer.

+
+
+

Engine

+
+ {#each ENGINES as e (e.id)} + {@const on = fEngine === e.id} + + {/each} +
+
+
+

Version

+
+ {#each engine.versions as v (v)} + {@const on = fVersion === v} + + {/each} +
+
+
+

Runs on

+
+ {#each [ + { id: /** @type {const} */ ('native'), Icon: Cpu, title: 'Native', ok: nativeOk, + body: fEngine === 'postgres' ? `Downloads Postgres ${fVersion} once, about 30 MB. No Docker needed.` : nativeOk ? `Uses the ${engine.label} installed on this computer.` : `${engine.label} isn't installed on this computer.` }, + { id: /** @type {const} */ ('docker'), Icon: Container, title: 'Docker', ok: dockerOk, + body: dockerOk ? 'A container, its data in a Docker volume.' : env?.dockerInstalled ? 'Start Docker Desktop to use this.' : 'Install Docker Desktop to use this.' }, + ] as r (r.id)} + {@const on = fRuntime === r.id} + + {/each} +
+
+
+ + +
+ {#if portTaken}

{portTaken.name} already uses port {portNum}.

+ {:else if portFound}

{portFound.source === 'docker' ? portFound.name : engineOf(portFound.engine).label} is already listening on port {portNum}.

{/if} + + {#if progress} +
+

{progress.message}

+
+
+
+
+ {/if} + {#if formError}{/if} +
+ {#if servers.length}{/if} + +
+
+ {:else if current} + {@const s = current} + {@const e = engineOf(s.engine)} + {@const isBusy = busy === s.id} +
+
+ {@render engineTile(s.engine, 'size-12', null)} +
+ {#if renaming} +
{ ev.preventDefault(); void saveName() }}> + + void saveName()} onkeydown={(ev) => { if (ev.key === 'Escape') renaming = false }} aria-label="Server name" /> +
+ {:else} + + {/if} +

{e.label} {s.version} · {runtimeLabel(s.runtime)}

+
+
+ + + + + + + + void editPort()}>Change port… + {#if s.runtime === 'native'} + void revealServer(s.id).catch((err) => toast.error('Could not open the folder', { description: String(err) }))}>Show data folder + {/if} + + void remove(s)}>Delete with its data + + +
+
+ + {#if failures[s.id] || s.problem} + + {/if} + + {#if editingPort} +
{ ev.preventDefault(); void savePort() }}> + + + + {#if portError}{/if} +
+ {/if} + + +
+
+
Status
+
+ + {isBusy ? (s.running ? 'Stopping' : 'Starting') : s.running ? 'Running' : 'Stopped'} +
+
+
+
{s.running ? 'Up for' : 'Port'}
+
{s.running ? uptime(s.startedAt, now) || 'Just started' : s.port}
+
+
+
Data
+
{s.runtime === 'docker' ? 'Docker volume' : formatBytes(s.diskBytes) || '0 B'}
+
+
+ + {@render connectionCard(s, s.id)} + + + +
+
+

Log

+ +
+
{logsFor === s.id ? logs || 'Nothing logged yet.' : ''}
+
+
+ {:else if currentFound} + {@const f = currentFound} + {@const e = engineOf(f.engine)} +
+
+ {@render engineTile(f.engine, 'size-12', null)} +
+

{f.source === 'docker' ? f.name : `${e.label} on ${f.port}`}

+

+ {e.label} · {f.source === 'docker' ? `Docker container${f.image ? `, ${f.image}` : ''}` : 'Running on this computer'} +

+
+ +
+

+ Stroke didn't start this server, so it can't stop it or read its log. It opens with the usual defaults below; if it asks for a password, set it in the connection. +

+ {@render connectionCard(f, `found:${f.port}`)} +
+ {:else if loaded} +
+ +
+

Pick a server

+

Or make one: Postgres, MySQL, MariaDB, Redis or MongoDB, any version, ready in a minute.

+
+ +
+ {/if} +
+
+
diff --git a/src/lib/components/MigrationsPage.svelte b/src/lib/components/MigrationsPage.svelte index 95905437..407a2a99 100644 --- a/src/lib/components/MigrationsPage.svelte +++ b/src/lib/components/MigrationsPage.svelte @@ -1,11 +1,12 @@
- +
setTool(v)} /> - {#if list.length} -

- {c.applied} applied - {#if files}{c.pending} pending{/if} - {#if c.failed}{c.failed} failed{/if} - {#if c.rolledBack}{c.rolledBack} rolled back{/if} -

- {/if}
-
- {#if projectError} - - {:else if !projectDir && list.length} -

- Showing what ran. to see pending migrations too. -

- {/if} - +
{#if error} - {:else if !loading && !list.length} + {:else if list.length} + +
+
+
+ Applied + {c.applied}{known ? ` / ${list.length}` : ''} +
+ {#if known} +
+ Pending + {c.pending} +
+ {/if} + {#if c.failed || c.rolledBack} +
+ Failed + {c.failed + c.rolledBack} +
+ {/if} +
+ Last applied + + {lastApplied ? `${splitName(lastApplied.name)[1]} · ${ago(lastApplied.appliedAt)}` : 'Nothing yet'} + +
+
+ {#if known} +
+
+
+ {/if} +
+ Read from {TABLE_NAME[source]}{source === 'd1' ? ' (Wrangler)' : ''} + {#if !known} + · + + to see what's pending + {/if} +
+ {#if known && c.pending} +
+ Apply {c.pending === 1 ? 'it' : `all ${c.pending}`}: + {applyCommand} + +
+ {/if} +
+ + {#if projectError} + + {/if} + + {#if known} + 3 ? 'w-[26rem] max-w-full' : 'w-80 max-w-full'} onchange={(v) => { filter = v; open = null }} /> + {/if} + + {#if !shown.length} +

Nothing {filter === 'failed' ? 'needs a look' : filter}.

+ {:else} +
    + {#each shown as m (m.name)} + {@const st = STATUS[m.status]} + {@const expanded = open === m.name} + {@const [seq, label] = splitName(m.name)} +
  1. + + {#if expanded} +
    +

    + {m.name} + {#if m.appliedAt}Applied {when(m.appliedAt)}{/if} + {#if m.durationMs != null}Took {took(m.durationMs)}{/if} + {#if m.steps != null}{m.steps} step{m.steps === 1 ? '' : 's'}{/if} +

    + {#if m.logs} +
    {m.logs}
    + {/if} + {#if m.sql} +
    + {#await import('./CodeEditor.svelte') then { default: CodeEditor }} + + {/await} +
    +
    + {#if onopensql} + + {/if} + +
    + {:else if !known} +

    Pick the project folder to see this migration's SQL.

    + {:else} +

    This migration's file isn't in the project folder.

    + {/if} +
    + {/if} +
  2. + {/each} +
+ {/if} + {:else if !loading}

{tool === 'prisma' ? 'No Prisma migrations' : 'No Drizzle migrations'} {rows === null ? 'in this database' : 'yet'}.

- {:else} -
    - {#each list as m (m.name)} - {@const st = STATUS[m.status]} - {@const expanded = open === m.name} -
  1. - - {#if expanded} -
    - {#if m.durationMs != null || m.steps != null} -

    - {[m.durationMs != null ? `Took ${took(m.durationMs)}` : '', m.steps != null ? `${m.steps} step${m.steps === 1 ? '' : 's'} applied` : ''].filter(Boolean).join(' · ')} -

    - {/if} - {#if m.logs} -
    {m.logs}
    - {/if} - {#if m.sql} -
    - {#await import('./CodeEditor.svelte') then { default: CodeEditor }} - - {/await} -
    -
    - {#if onopensql} - - {/if} - -
    - {:else if !files} -

    Pick the project folder to see this migration's SQL.

    - {/if} -
    - {/if} -
  2. - {/each} -
{/if}
diff --git a/src/lib/components/QuitHint.svelte b/src/lib/components/QuitHint.svelte index d1b89ec1..c100416e 100644 --- a/src/lib/components/QuitHint.svelte +++ b/src/lib/components/QuitHint.svelte @@ -10,6 +10,10 @@ let ready = $state(false) /** @type {ReturnType | null} */ let timer = null + /** How long the second press counts, for the draining bar. */ + let windowMs = $state(1600) + /** Bumped per hint so the bar restarts from full. */ + let run = $state(0) $effect(() => { let off = () => {} @@ -17,9 +21,11 @@ void import('@tauri-apps/api/event') .then(({ listen }) => listen('app-quit-hint', (e) => { ready = true + windowMs = Number(e.payload) || 1600 + run++ requestAnimationFrame(() => { shown = true }) if (timer) clearTimeout(timer) - timer = setTimeout(() => { shown = false }, Number(e.payload) || 1600) + timer = setTimeout(() => { shown = false }, windowMs) })) .then((un) => { if (gone) un(); else off = un }) .catch(() => {}) @@ -34,12 +40,35 @@ class="pointer-events-none fixed inset-x-0 top-[22vh] z-[100] flex justify-center" >
- Hold - - or press twice to quit +

+ Press again to quit +

+

or keep holding it

+ {#key run} + + {/key}
{/if} + + diff --git a/src/lib/components/StudioShell.svelte b/src/lib/components/StudioShell.svelte index b03354a2..5fbc083d 100644 --- a/src/lib/components/StudioShell.svelte +++ b/src/lib/components/StudioShell.svelte @@ -578,7 +578,31 @@ } } let showDockerModal = $state(false) - let showLocalServers = $state(false) + /** Local servers live in their own window; its Open button connects here. */ + async function openLocalServers() { + try { + const { getCurrentWindow } = await import('@tauri-apps/api/window') + const { openLocalServersWindow } = await import('$lib/local-servers.js') + await openLocalServersWindow(getCurrentWindow().label) + } catch (e) { + toast.error('Could not open Local servers', { description: String(e) }) + } + } + $effect(() => { + let off = () => {} + let gone = false + void import('@tauri-apps/api/event') + .then(({ listen }) => listen('local-server-connect', (e) => { + // Ids are stable per server: one opened before keeps what was set on + // it since (a password for a server Stroke didn't make). + const info = /** @type {any} */ (e.payload) + const saved = loadSavedConnections().find((c) => c.id === info.id) + void handleDockerConnect(saved ? { ...saved } : info) + })) + .then((un) => { if (gone) un(); else off = un }) + .catch(() => {}) + return () => { gone = true; off() } + }) let dockerInitialDb = $state(/** @type {string | null} */ (null)) /** Bottom query-log console visibility. */ let queryLogOpen = $state(false) @@ -3478,7 +3502,7 @@ let rowSearch = $state('') erd: () => openErdTab(), dataDiff: () => openDataDiffTab(), migrations: () => openMigrationsTab(), - localServers: () => { commandOpen = false; showLocalServers = true }, + localServers: () => { commandOpen = false; void openLocalServers() }, dashboard: () => openDashboardTab(), logs: () => openLogsTab(), extensions: () => openExtensionsTab(), @@ -8541,6 +8565,9 @@ let rowSearch = $state('') await connectByType(conn) await onConnected(conn, conn.id) showDockerModal = false + // Connected from another window (Local servers) while the connection + // screen was up: show the database, not the screen. + showConnectionModal = false } catch (e) { error = String(e) showDockerModal = false @@ -9932,11 +9959,7 @@ let rowSearch = $state('') dialect={dbType} onopeninsql={(sql) => { if (aiMode) exitAiMode(); void openQueryInEditor(sql) }} /> -{#if showLocalServers} - {#await import('./LocalServersDialog.svelte') then { default: LocalServersDialog }} - void handleDockerConnect(c)} /> - {/await} -{/if} + {#if dialogMounted.docker} {#await lazyDialogs.docker() then { default: DockerLaunchModal }} { commandOpen = false; openSchemaTimelineTab() }} opendatadiff={() => { commandOpen = false; openDataDiffTab() }} openmigrations={() => { commandOpen = false; openMigrationsTab() }} - openlocalservers={() => { commandOpen = false; showLocalServers = true }} + openlocalservers={() => { commandOpen = false; void openLocalServers() }} schemaContext={aiSchemaContext} onaskcontinue={handleAskContinue} /> diff --git a/src/lib/i18n.js b/src/lib/i18n.js index 60ac0d0c..d4fec1ce 100644 --- a/src/lib/i18n.js +++ b/src/lib/i18n.js @@ -189,6 +189,7 @@ const DICT = { 'menu.moveLast': 'Move to last', 'menu.resetOrder': 'Reset column order', 'menu.resetWidth': 'Reset column width', + 'menu.fitAllColumns': 'Fit all columns to content', 'menu.columnStats': 'Column stats', 'menu.highlight': 'Highlight', 'menu.noColor': 'No color', @@ -346,6 +347,7 @@ const DICT = { 'menu.moveLast': 'Mover al final', 'menu.resetOrder': 'Restablecer orden de columnas', 'menu.resetWidth': 'Restablecer ancho de columna', + 'menu.fitAllColumns': 'Ajustar todas las columnas al contenido', 'menu.columnStats': 'Estadísticas de columna', 'menu.highlight': 'Resaltar', 'menu.noColor': 'Sin color', @@ -502,6 +504,7 @@ const DICT = { 'menu.moveLast': 'Déplacer à la fin', 'menu.resetOrder': 'Réinitialiser l’ordre des colonnes', 'menu.resetWidth': 'Réinitialiser la largeur', + 'menu.fitAllColumns': 'Ajuster toutes les colonnes au contenu', 'menu.columnStats': 'Statistiques de colonne', 'menu.highlight': 'Surligner', 'menu.noColor': 'Aucune couleur', @@ -657,6 +660,7 @@ const DICT = { 'menu.moveLast': 'Ans Ende', 'menu.resetOrder': 'Spaltenreihenfolge zurücksetzen', 'menu.resetWidth': 'Spaltenbreite zurücksetzen', + 'menu.fitAllColumns': 'Alle Spalten an Inhalt anpassen', 'menu.columnStats': 'Spaltenstatistik', 'menu.highlight': 'Hervorheben', 'menu.noColor': 'Keine Farbe', diff --git a/src/lib/local-servers.js b/src/lib/local-servers.js index d7203471..22b918d0 100644 --- a/src/lib/local-servers.js +++ b/src/lib/local-servers.js @@ -4,7 +4,8 @@ import { invoke } from '@tauri-apps/api/core' /** - * @typedef {{ id: string, name: string, engine: string, version: string, port: number, runtime: 'docker' | 'native', createdAt: number, running: boolean, problem: string | null }} LocalServer + * @typedef {{ id: string, name: string, engine: string, version: string, port: number, runtime: 'docker' | 'native', createdAt: number, autostart: boolean, running: boolean, problem: string | null, startedAt: number | null, diskBytes: number | null, dataDir: string | null }} LocalServer + * @typedef {{ engine: string, port: number, source: 'docker' | 'process', name: string, image: string | null }} FoundServer * @typedef {{ docker: boolean, dockerInstalled: boolean, brew: boolean, native: string[] }} LocalEnv * @typedef {{ name: string, status: string, running: boolean }} BrewService */ @@ -60,8 +61,56 @@ export const startServer = (id) => invoke('local_server_start', { id }) export const stopServer = (id) => invoke('local_server_stop', { id }) /** @param {string} id */ export const deleteServer = (id) => invoke('local_server_delete', { id }) -/** @param {string} id @param {{ name?: string, port?: number }} patch */ -export const updateServer = (id, patch) => invoke('local_server_update', { id, name: patch.name ?? null, port: patch.port ?? null }) +/** @param {string} id @param {{ name?: string, port?: number, autostart?: boolean }} patch */ +export const updateServer = (id, patch) => invoke('local_server_update', { id, name: patch.name ?? null, port: patch.port ?? null, autostart: patch.autostart ?? null }) +/** Database servers on this computer that Stroke didn't make. @returns {Promise} */ +export const discoverServers = () => invoke('local_servers_discover') +/** @param {string} id */ +export const revealServer = (id) => invoke('local_server_reveal', { id }) +/** Open the Local servers window; `from` is the window that connects. @param {string} from */ +export const openLocalServersWindow = (from) => invoke('open_local_servers_window', { from }) +/** Hand a connection to an app window. @param {string} target @param {any} connection */ +export const connectIn = (target, connection) => invoke('local_server_connect_in', { target, connection }) + +/** + * The URL a server is reached at, as an app's DATABASE_URL would hold it. + * @param {{ engine: string, port: number }} s + */ +export function connectionUrl(s) { + switch (s.engine) { + case 'postgres': return `postgresql://postgres@127.0.0.1:${s.port}/postgres` + case 'mysql': + case 'mariadb': return `mysql://root@127.0.0.1:${s.port}/` + case 'redis': return `redis://127.0.0.1:${s.port}` + default: return `mongodb://127.0.0.1:${s.port}/?directConnection=true` + } +} + +/** The env var name apps usually read for an engine. @param {string} engine */ +export const envName = (engine) => (engine === 'redis' ? 'REDIS_URL' : engine === 'mongodb' ? 'MONGODB_URI' : 'DATABASE_URL') + +/** 1536 → "1.5 KB". @param {number | null | undefined} n */ +export function formatBytes(n) { + if (n == null) return '' + const u = ['B', 'KB', 'MB', 'GB', 'TB'] + let i = 0 + let v = n + while (v >= 1024 && i < u.length - 1) { v /= 1024; i++ } + return `${v < 10 && i ? v.toFixed(1) : Math.round(v)} ${u[i]}` +} + +/** How long since `ms`, short: "3 min", "2 h 5 min", "4 days". @param {number | null | undefined} ms @param {number} [now] */ +export function uptime(ms, now = Date.now()) { + if (!ms) return '' + const s = Math.max(0, Math.round((now - ms) / 1000)) + if (s < 60) return 'under a minute' + const m = Math.floor(s / 60) + if (m < 60) return `${m} min` + const h = Math.floor(m / 60) + if (h < 24) return m % 60 ? `${h} h ${m % 60} min` : `${h} h` + const d = Math.floor(h / 24) + return `${d} day${d === 1 ? '' : 's'}` +} /** @param {string} id @returns {Promise} */ export const serverLogs = (id) => invoke('local_server_logs', { id }) /** @param {number} from @returns {Promise} */ diff --git a/src/lib/migrations.js b/src/lib/migrations.js index 0ae779ce..8347e913 100644 --- a/src/lib/migrations.js +++ b/src/lib/migrations.js @@ -10,6 +10,9 @@ // counts as applied when its journal `when` is at or before the newest // created_at, which is how Drizzle's migrator decides; `hash` is the SHA-256 // of the .sql file. Drizzle records no failures (a failed run rolls back). +// Cloudflare D1 projects apply the same files with `wrangler d1 migrations +// apply`, which keeps its own `d1_migrations` (id, name, applied_at), `name` +// being the file name: every .sql file in the folder, in the journal or not. /** * @typedef {'applied' | 'pending' | 'failed' | 'rolled-back'} MigrationStatus @@ -143,6 +146,36 @@ export function mergeDrizzle(rows, files) { return out } +/** + * @param {Record[]} rows `d1_migrations` + * @param {MigrationFile[] | null} files every .sql file in the folder (name with `.sql`); null when no folder is set + * @returns {Migration[]} + */ +export function mergeD1(rows, files) { + const strip = (/** @type {string} */ n) => n.replace(/\.sql$/i, '') + /** @type {Map>} */ + const ran = new Map(rows.map((r) => [strip(String(r.name ?? '')), r])) + const fileByName = new Map((files ?? []).map((f) => [strip(f.name), f])) + const names = [...new Set([...fileByName.keys(), ...ran.keys()])].filter(Boolean).sort() + return names.map((name) => { + const row = ran.get(name) + const file = fileByName.get(name) + return { + name, + status: /** @type {MigrationStatus} */ (row ? 'applied' : 'pending'), + appliedAt: row ? toMs(row.applied_at) : null, + startedAt: null, + durationMs: null, + steps: null, + logs: null, + sql: file?.sql ?? null, + changed: false, + missingFile: !!files && !file, + attempts: row ? 1 : 0, + } + }) +} + /** @param {Migration[]} list */ export function counts(list) { const c = { applied: 0, pending: 0, failed: 0, rolledBack: 0, changed: 0 } @@ -159,10 +192,11 @@ export function counts(list) { /** * The SELECTs that read each tool's table, per engine family. Prisma's table * lives in the connection's schema; Drizzle's in `drizzle` on Postgres. - * @param {'prisma' | 'drizzle'} tool @param {string} family @param {string | null} schema + * @param {'prisma' | 'drizzle' | 'd1'} tool @param {string} family @param {string | null} schema * @returns {string[]} tried in order until one works */ export function migrationQueries(tool, family, schema) { + if (tool === 'd1') return family === 'd1' || family === 'sqlite' ? ['SELECT id, name, applied_at FROM "d1_migrations" ORDER BY id'] : [] const q = family === 'mysql' ? (/** @type {string} */ s) => `\`${s.replace(/`/g, '``')}\`` : (/** @type {string} */ s) => `"${s.replace(/"/g, '""')}"` if (tool === 'prisma') { const cols = 'id, checksum, finished_at, migration_name, logs, rolled_back_at, started_at, applied_steps_count' diff --git a/src/lib/migrations.test.js b/src/lib/migrations.test.js index a66e829d..9dd5eff0 100644 --- a/src/lib/migrations.test.js +++ b/src/lib/migrations.test.js @@ -74,3 +74,15 @@ describe('helpers', () => { expect(rowsOf({ columns: [{ name: 'a' }, { name: 'b' }], rows: [[1, 2]] })).toEqual([{ a: 1, b: 2 }]) }) }) + +describe('mergeD1', () => { + it('matches d1_migrations names to the folder files', async () => { + const { mergeD1 } = await import('./migrations.js') + const rows = [{ id: 1, name: '0000_init.sql', applied_at: '2026-01-02 10:00:00' }, { id: 2, name: 'old.sql', applied_at: '2026-01-03 10:00:00' }] + const files = [{ name: '0000_init.sql', sql: 'a', checksum: 'x', when: null }, { name: '0001_more.sql', sql: 'b', checksum: 'y', when: null }] + const list = mergeD1(rows, files) + expect(list.map((m) => [m.name, m.status, m.missingFile])).toEqual([['0000_init', 'applied', false], ['0001_more', 'pending', false], ['old', 'applied', true]]) + expect(list[0].appliedAt).toBe(Date.parse('2026-01-02T10:00:00Z')) + expect(mergeD1(rows, null).every((m) => m.status === 'applied')).toBe(true) + }) +}) diff --git a/src/lib/stores/dashboards.js b/src/lib/stores/dashboards.js index e32b6c2f..15a3f34c 100644 --- a/src/lib/stores/dashboards.js +++ b/src/lib/stores/dashboards.js @@ -91,6 +91,40 @@ export function switchDashboardsConnection(connectionId) { activeDashboardId.set(loadActiveId(_connId)) } +/** Write pending edits now (another window is about to read them). */ +export function flushDashboards() { + persistDashboards.flush() +} + +/** The connection key the dashboards are stored under right now. */ +export function dashboardsConnectionId() { + return _connId +} + +/** + * The connection key whose dashboards hold `dashId`, `preferred` first. A + * dashboard window opened with a key the tab didn't store under (an older + * build, a connection matched another way) still finds its dashboard. + * @param {string} dashId @param {string} preferred @returns {string | null} + */ +export function findDashboardScope(dashId, preferred) { + /** @param {string | null} raw */ + const has = (raw) => { + try { + const list = JSON.parse(raw ?? 'null') + return Array.isArray(list) && list.some((d) => d?.id === dashId) + } catch { return false } + } + try { + if (preferred && has(localStorage.getItem(KEY(preferred)))) return preferred + for (let i = 0; i < localStorage.length; i++) { + const k = localStorage.key(i) + if (k?.startsWith('stroke:dashboards:') && has(localStorage.getItem(k))) return k.slice('stroke:dashboards:'.length) + } + } catch { /* storage unavailable */ } + return null +} + /** @param {string} name @returns {Dashboard} */ export function createDashboard(name) { const id = `dash-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`