From 42d2255226be52e8a1adb0f40017146d84a08978 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Mon, 30 Nov 2026 09:36:41 -0300 Subject: [PATCH 1/8] =?UTF-8?q?docs:=20dise=C3=B1o=20y=20plan=20de=20ejecu?= =?UTF-8?q?tar=20todo,=20pesta=C3=B1as=20de=20resultado=20y=20men=C3=BA=20?= =?UTF-8?q?de=20Estructura?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- ...6-11-30-openpl-ejecutar-todo-y-pestanas.md | 63 +++++++++++++++++++ ...-openpl-ejecutar-todo-y-pestanas-design.md | 41 ++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-30-openpl-ejecutar-todo-y-pestanas.md create mode 100644 docs/superpowers/specs/2026-11-30-openpl-ejecutar-todo-y-pestanas-design.md diff --git a/docs/superpowers/plans/2026-11-30-openpl-ejecutar-todo-y-pestanas.md b/docs/superpowers/plans/2026-11-30-openpl-ejecutar-todo-y-pestanas.md new file mode 100644 index 0000000..6becb6f --- /dev/null +++ b/docs/superpowers/plans/2026-11-30-openpl-ejecutar-todo-y-pestanas.md @@ -0,0 +1,63 @@ +# Ejecutar todo, pestañas de resultado y menú de Estructura. Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:executing-plans. Steps use `- [ ]`. + +**Goal:** F8 ejecuta todo sin selección, un resultado por pestaña con su propio cursor, y Copiar código / Comentar en Estructura. + +**Architecture:** Rust guarda varios cursores por sesión (`CursorStore`, tope 20). `SqlWindow` pasa de un `grid` a `results: ResultTab[]`, con la pestaña activa derivada de `tab` (`result:N`). `programSymbols` expone el rango de cada declaración; un helper puro alterna comentarios de línea. + +**Tech Stack:** Rust (`openpl-core`), React 19, CodeMirror 6, Vitest. + +**Spec:** `docs/superpowers/specs/2026-11-30-openpl-ejecutar-todo-y-pestanas-design.md` + +## Global Constraints + +- Textos: "Ejecutar sentencia", "Copiar código", "Comentar", "Descomentar", "Select ", "Consulta N". +- Atajos solo en `keymap.ts`: `execute` F8 (sin alt), `executeStatement` Ctrl+Enter. +- Tope de cursores abiertos por sesión: 20. +- TDD; `cargo test -p openpl-core`, `cargo clippy -D warnings`, `npx.cmd tsc --noEmit`, `npm.cmd test` en verde antes de cada commit. + +## Review Focus + +- Una ejecución nueva mientras otra pestaña trae filas (Traer todas) no debe mezclar filas entre pestañas. +- Cambiar de pestaña con ediciones pendientes no pierde datos sin preguntar. +- Un script con 25 SELECT: las primeras pestañas quedan sin "más filas" en vez de fallar. +- Rollback con varias pestañas abiertas deja todas sin "más filas". +- Ctrl+Enter en la ventana de programa sigue compilando. + +--- + +### Task 1: Varios cursores por sesión (Rust) + +**Files:** `crates/openpl-core/src/sql.rs` + +- Produces: `struct CursorStore { cap, items: VecDeque<(u64, T)> }` con `insert(id, T)` (expulsa el más viejo si pasa `cap`), `get_mut(id)`, `remove(id)`, `clear()`. `execute` ya no vacía los cursores; `fetch(cursor, 0)` libera solo ese; `rollback` vacía todos. +- [ ] Tests unitarios de `CursorStore`: inserta y obtiene por id; el 21.º expulsa el primero; `remove` y `clear`. +- [ ] Ver fallar, implementar, `cargo test -p openpl-core`, clippy. Commit. + +### Task 2: F8 ejecuta todo; Ctrl+Enter ejecuta la sentencia + +**Files:** `app/src/keymap.ts`, `components/SqlWindow.tsx`, `components/ProgramWindow.tsx`, `App.tsx`, tests de los tres. + +- [ ] Tests: SqlWindow con dos INSERT y cursor en el primero: `execute` llama `sqlExecute` dos veces; `executeStatement` una. ProgramWindow: `executeStatement` compila igual que `execute`. Keymap: Ctrl+Enter → `executeStatement`. +- [ ] Implementar (`execute: run(targets(true).list)`; `executeStatement: run(targets().list)`; App enruta `executeStatement` en SQL y programa). Commit. + +### Task 3: Una pestaña por resultado + +**Files:** `components/SqlWindow.tsx`, `components/SqlWindow.test.tsx`, `app/src/sqlScript.ts` (título). + +- Produces: `resultTitle(sql: string, index: number): string` en `sqlScript.ts`. +- [ ] Tests: `resultTitle("select * from PER_MARCACION_REG t", 0)` → "Select PER_MARCACION_REG"; sin FROM → "Consulta 1". SqlWindow: dos SELECT → dos pestañas con esos nombres, activa la última, cada una muestra sus filas; Traer todas en la primera pide el cursor de la primera; ejecutar de nuevo libera cursores anteriores (`sqlFetch(..., 0)`); cambiar de pestaña con edición pendiente pide confirmar. +- [ ] Implementar. Commit. + +### Task 4: Copiar código y Comentar en Estructura + +**Files:** `app/src/programSymbols.ts` (`range`), `app/src/lineComments.ts` (nuevo), `components/ProgramWindow.tsx`, tests. + +- Produces: `ProgramSymbol.range: { from: number; to: number }`; `toggleLineComments(text: string, from: number, to: number): { changes: { from: number; to?: number; insert: string }[]; commented: boolean }` (`commented` = el rango ya estaba comentado). +- [ ] Tests: rango de una rutina definida va de PROCEDURE a `END;`; de una variable, hasta su `;`. `toggleLineComments` comenta y descomenta conservando sangría y saltando líneas vacías. ProgramWindow: menú de una entrada privada ofrece Copiar código y Comentar; Comentar se deshace con un undo; en solo lectura no hay Comentar. +- [ ] Implementar. Commit. + +### Task 5: Documentación y cierre + +- [ ] `docs/behavior/sql.md` (F8, Ctrl+Enter, pestañas), `docs/behavior/programa.md` (menú Estructura), `docs/ESTADO.md` (teclas que cambian), antislop corto. Suite completa. Commit. diff --git a/docs/superpowers/specs/2026-11-30-openpl-ejecutar-todo-y-pestanas-design.md b/docs/superpowers/specs/2026-11-30-openpl-ejecutar-todo-y-pestanas-design.md new file mode 100644 index 0000000..cfa4b24 --- /dev/null +++ b/docs/superpowers/specs/2026-11-30-openpl-ejecutar-todo-y-pestanas-design.md @@ -0,0 +1,41 @@ +# Ejecutar todo, una pestaña por resultado y menú de Estructura + +Fecha: 2026-11-30. Estado: aprobado por el usuario. Issues de GitHub #17 y #16. + +## Intención + +- **#17:** en una ventana SQL con varios INSERT o SELECT, F8 sin selección debe ejecutarlos todos, + no solo el del cursor. Si hay varios SELECT, cada resultado va en su propia pestaña (el usuario + mostró una captura con "Select per_marcacion_reg" y "Select per_marcacion_aux"). +- **#16:** desde el panel Estructura, copiar el código completo de un procedimiento, función o + cualquier declaración, y comentarlo o descomentarlo entero. + +## Comportamiento + +1. **F8 / Ejecutar:** con selección, lo seleccionado. Sin selección, todas las sentencias en orden; + se detiene en el primer error (lo que hoy hace Shift+F8, que sigue igual). +2. **Ctrl+Enter / Ejecutar sentencia:** comando propio, solo la sentencia del cursor. En la ventana + de programa, Ctrl+Enter sigue compilando como F8. +3. **Pestañas de resultado:** cada SELECT de la ejecución abre una pestaña "Select tabla" (primera + tabla del FROM, tal como está escrita) o "Consulta N". Los DML informan en Salida. Al terminar + queda activa la del último SELECT. Una ejecución nueva reemplaza las pestañas. Sin resultados + queda la pestaña "Resultados" vacía, como hoy. +4. **Cada pestaña es independiente:** trae más filas, Traer todas, exporta, copia y edita su + propio resultado. Cambiar de pestaña con ediciones pendientes pide confirmación. +5. **Cursores (Rust):** la sesión guarda hasta 20 cursores abiertos; el más viejo se cierra al + pasar el tope. Una ejecución nueva libera los cursores de la anterior (`sql_fetch` con tamaño + 0). Rollback cierra todos. +6. **Estructura:** clic derecho en cualquier entrada ofrece **Copiar código** (la declaración + entera; una rutina desde PROCEDURE o FUNCTION hasta su `END;`) y **Comentar** / **Descomentar** + (`-- ` al inicio de cada línea, un solo Ctrl+Z). Comentar no aparece en solo lectura. **Probar** + sigue donde estaba. + +## Enfoques + +- **Elegido: un cursor por pestaña** en la sesión de Rust. Cada pestaña sigue viva. +- Descartado: un solo cursor y pestañas anteriores con la primera tanda "parcial". Más simple, + pero las pestañas viejas no traen más filas ni se editan. + +## Fuera de alcance + +La consola de comandos y la ventana de prueba no cambian. From 8629d75d160783552461c63cc6393ca42585e78d Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Mon, 30 Nov 2026 09:38:01 -0300 Subject: [PATCH 2/8] =?UTF-8?q?feat(core):=20WAL-128=20varios=20cursores?= =?UTF-8?q?=20abiertos=20por=20sesi=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hasta 20; el más viejo se cierra al pasar el tope. Ejecutar ya no cierra los anteriores; fetch con tamaño 0 libera uno y rollback los cierra todos. Co-Authored-By: Claude Opus 5.5 --- crates/openpl-core/src/sql.rs | 103 ++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 22 deletions(-) diff --git a/crates/openpl-core/src/sql.rs b/crates/openpl-core/src/sql.rs index 1d80262..4b15622 100644 --- a/crates/openpl-core/src/sql.rs +++ b/crates/openpl-core/src/sql.rs @@ -6,6 +6,7 @@ use oracle::sql_type::{Clob, Nclob, OracleType, RefCursor, Timestamp, ToSql}; use oracle::{ColumnInfo, ResultSet, Row, Statement, StatementType}; use serde::{Deserialize, Serialize}; use std::cell::RefCell; +use std::collections::VecDeque; use std::io::Read; use std::iter::Peekable; use std::time::Instant; @@ -225,14 +226,51 @@ fn read_test_output( } } -struct OpenCursor { - id: u64, - rows: Peekable>, +/// Cursores abiertos de una sesión, del más viejo al más nuevo. Pasado el tope se cierra el más viejo. +struct CursorStore { + cap: usize, + items: VecDeque<(u64, T)>, } +impl CursorStore { + const fn new(cap: usize) -> Self { + Self { + cap, + items: VecDeque::new(), + } + } + + fn insert(&mut self, id: u64, item: T) { + while self.items.len() >= self.cap { + self.items.pop_front(); + } + self.items.push_back((id, item)); + } + + fn get_mut(&mut self, id: u64) -> Option<&mut T> { + self.items + .iter_mut() + .find(|(open, _)| *open == id) + .map(|(_, item)| item) + } + + fn remove(&mut self, id: u64) { + self.items.retain(|(open, _)| *open != id); + } + + fn clear(&mut self) { + self.items.clear(); + } +} + +/// Cursores abiertos a la vez por sesión: uno por pestaña de resultado. +const MAX_OPEN_CURSORS: usize = 20; + +type OpenRows = Peekable>; + thread_local! { - // Cada sesión vive en su propio hilo: este cursor es el de esa sesión. - static CURSOR: RefCell> = const { RefCell::new(None) }; + // Cada sesión vive en su propio hilo: estos cursores son los de esa sesión. + static CURSORS: RefCell> = const { RefCell::new(CursorStore::new(MAX_OPEN_CURSORS)) }; static NEXT_CURSOR: RefCell = const { RefCell::new(1) }; } @@ -452,7 +490,6 @@ pub fn execute_with_outputs( page_size: usize, outputs: &[TestOutputBind], ) -> Result { - CURSOR.with(|c| c.borrow_mut().take()); let params = binds .iter() .map(bind_param) @@ -485,7 +522,7 @@ pub fn execute_with_outputs( *n }); if page.more { - CURSOR.with(|c| *c.borrow_mut() = Some(OpenCursor { id, rows })); + CURSORS.with(|c| c.borrow_mut().insert(id, rows)); } ExecResult::Query { cursor: id, @@ -549,24 +586,22 @@ fn failed_outcome( /// Siguiente página del cursor abierto. Un tamaño de cero libera ese cursor. pub fn fetch(cursor: u64, size: usize) -> Result { - CURSOR.with(|c| { - let mut slot = c.borrow_mut(); - let Some(open) = slot.as_mut().filter(|o| o.id == cursor) else { - return Ok(QueryPage { - rows: Vec::new(), - more: false, - }); + CURSORS.with(|c| { + let mut store = c.borrow_mut(); + let empty = || QueryPage { + rows: Vec::new(), + more: false, }; if size == 0 { - *slot = None; - return Ok(QueryPage { - rows: Vec::new(), - more: false, - }); + store.remove(cursor); + return Ok(empty()); } - let page = read_page(&mut open.rows, size, |row| row_cells(&row)); + let Some(rows) = store.get_mut(cursor) else { + return Ok(empty()); + }; + let page = read_page(rows, size, |row| row_cells(&row)); if !matches!(&page, Ok(page) if page.more) { - *slot = None; + store.remove(cursor); } page }) @@ -578,7 +613,7 @@ pub fn commit(conn: &DbConn) -> Result { } pub fn rollback(conn: &DbConn) -> Result { - CURSOR.with(|c| c.borrow_mut().take()); + CURSORS.with(|c| c.borrow_mut().clear()); conn.raw().rollback()?; in_transaction(conn) } @@ -587,6 +622,30 @@ pub fn rollback(conn: &DbConn) -> Result { mod tests { use super::*; + #[test] + fn cursor_store_guarda_varios_y_expulsa_el_mas_viejo() { + let mut store = CursorStore::new(2); + store.insert(1, "a"); + store.insert(2, "b"); + assert_eq!(store.get_mut(1), Some(&mut "a")); + store.insert(3, "c"); + assert_eq!(store.get_mut(1), None); + assert_eq!(store.get_mut(2), Some(&mut "b")); + assert_eq!(store.get_mut(3), Some(&mut "c")); + } + + #[test] + fn cursor_store_libera_uno_o_todos() { + let mut store = CursorStore::new(20); + store.insert(1, "a"); + store.insert(2, "b"); + store.remove(1); + assert_eq!(store.get_mut(1), None); + assert_eq!(store.get_mut(2), Some(&mut "b")); + store.clear(); + assert_eq!(store.get_mut(2), None); + } + #[test] fn tope_lob_cuenta_caracteres_y_respeta_utf8() { assert_eq!(cap_text("A😀ñB", 3), ("A😀ñ".into(), true)); From abff3c9870076b6cb4afaa1b14bbb1c5033c69da Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Mon, 30 Nov 2026 09:40:36 -0300 Subject: [PATCH 3/8] =?UTF-8?q?feat(app):=20WAL-128=20F8=20sin=20selecci?= =?UTF-8?q?=C3=B3n=20ejecuta=20todo;=20Ctrl+Enter=20ejecuta=20la=20sentenc?= =?UTF-8?q?ia?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/App.test.tsx | 2 +- app/src/App.tsx | 7 +++++-- app/src/components/ProgramWindow.test.tsx | 9 +++++++++ app/src/components/ProgramWindow.tsx | 1 + app/src/components/SqlWindow.test.tsx | 22 ++++++++++++++++++++++ app/src/components/SqlWindow.tsx | 4 +++- app/src/keymap.test.ts | 11 +++++++---- app/src/keymap.ts | 4 +++- 8 files changed, 51 insertions(+), 9 deletions(-) diff --git a/app/src/App.test.tsx b/app/src/App.test.tsx index 2d47684..55a550e 100644 --- a/app/src/App.test.tsx +++ b/app/src/App.test.tsx @@ -439,7 +439,7 @@ test("compara el programa en su sesión aunque el explorador cambie de conexión expect( session.queryByRole("menuitem", { name: /Preparar compilación/ }), ).not.toBeInTheDocument(); - expect(session.getByRole("menuitem", { name: /^Ejecutar(?! script)/ })).toBeEnabled(); + expect(session.getByRole("menuitem", { name: /^Ejecutar(?! script| sentencia)/ })).toBeEnabled(); fireEvent.keyDown(document, { key: "Escape" }); fireEvent.keyDown(window, { key: "d", altKey: true, shiftKey: true }); expect(await screen.findByText("Sin diferencias de texto")).toBeInTheDocument(); diff --git a/app/src/App.tsx b/app/src/App.tsx index 9aeb3e7..0788ad3 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -86,6 +86,7 @@ const SqlWindow = lazy(() => const quoteName = (name: string) => `"${name.replace(/"/g, '""')}"`; const TAB_DRAG_TYPE = "application/x-openpl-tab"; const sqlTabActions = [ + "executeStatement", "execute", "showSymbolCard", "goToDefinition", @@ -271,7 +272,7 @@ export default function App() { (program.sql!.transaction && !program.sql!.busy), ) .map((id) => [id, () => { - if (id === "execute" && states[program.sql!.sessionId] === "Disconnected") { + if ((id === "execute" || id === "executeStatement") && states[program.sql!.sessionId] === "Disconnected") { reconnectSqlButton.current?.focus(); showNotice(reconnectErrors[program.sql!.sessionId] ?? "Sesión desconectada"); return; @@ -298,6 +299,7 @@ export default function App() { "compareProgram", "test", "execute", + "executeStatement", "cancel", "goToLine", "find", @@ -321,7 +323,7 @@ export default function App() { if (id === "test") return !!program.object && !!editorConnection; if (id === "compareProgram") return !!program.object && !!editorConnection; - if (id === "execute" || id === "cancel") + if (id === "execute" || id === "executeStatement" || id === "cancel") return !!program.object && !!editorConnection && !program.readOnly; if (id === "spec" || id === "body" || id === "sideBySide") return program.parts.length === 2; @@ -1168,6 +1170,7 @@ export default function App() { run("reconnect"), "sep", run("execute"), + run("executeStatement"), run("executeScript"), run("cancel"), "sep", diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index 5ac540b..1946720 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -980,3 +980,12 @@ test("Ctrl+clic sin contexto de símbolos igual ubica el cursor", async () => { fireEvent.mouseDown(view.contentDOM, { ctrlKey: true, button: 0, clientX: 5, clientY: 5 }); await waitFor(() => expect(view.state.selection.main.head).toBe(position)); }); + +test("Ctrl+Enter compila igual que F8", async () => { + const ref = createRef(); + const compile = compiler(); + render(); + await act(async () => ref.current?.executeStatement?.()); + expect(compile.run).toHaveBeenCalledWith(compiledStatement); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index cf6c7c2..e5595a6 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -524,6 +524,7 @@ export function ProgramWindow({ unfoldBlock: runInEditor(unfoldCode), compareProgram: readCurrentProgram ? () => void compare() : undefined, execute: canCompile ? () => void compileActive() : undefined, + executeStatement: canCompile ? () => void compileActive() : undefined, cancel: canCompile ? stopCompilation : undefined, test: onTestRoutine ? runInEditor((view) => { const position = view.state.selection.main.head; diff --git a/app/src/components/SqlWindow.test.tsx b/app/src/components/SqlWindow.test.tsx index 71c6ca0..4ea58c8 100644 --- a/app/src/components/SqlWindow.test.tsx +++ b/app/src/components/SqlWindow.test.tsx @@ -893,3 +893,25 @@ test("F12 no salta si el cursor se movió mientras se resolvía", async () => { await new Promise((resolve) => setTimeout(resolve, 20)); expect(openObject).not.toHaveBeenCalled(); }); + +describe("F8 y Ctrl+Enter", () => { + const done = { result: { kind: "Done" as const, message: "1 fila insertada" }, elapsed_ms: 1, output: [], transaction: true }; + const source = "INSERT INTO t VALUES (1);\nINSERT INTO t VALUES (2);"; + + test("F8 sin selección ejecuta todas las sentencias", async () => { + const execute = vi.spyOn(api, "sqlExecute").mockResolvedValue(done); + const { ref, view } = setup(source); + act(() => view.dispatch({ selection: { anchor: 3 } })); + await act(async () => ref.current!.execute!()); + expect(execute).toHaveBeenCalledTimes(2); + }); + + test("Ctrl+Enter ejecuta solo la sentencia del cursor", async () => { + const execute = vi.spyOn(api, "sqlExecute").mockResolvedValue(done); + const { ref, view } = setup(source); + act(() => view.dispatch({ selection: { anchor: 3 } })); + await act(async () => ref.current!.executeStatement!()); + expect(execute).toHaveBeenCalledTimes(1); + expect(execute.mock.calls[0][1]).toBe("INSERT INTO t VALUES (1)"); + }); +}); diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index 539762f..966abd4 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -870,7 +870,9 @@ export function SqlWindow({ const actions: ProgramActions = { hasPending: () => count > 0, explainPlan: command ? undefined : () => void explain(), - execute: command ? undefined : () => void run(targets().list), + // Sin selección, F8 ejecuta todas las sentencias; Ctrl+Enter, solo la del cursor. + execute: command ? undefined : () => void run(targets(true).list), + executeStatement: command ? undefined : () => void run(targets().list), executeScript: command ? undefined : () => void run(targets(true).list), exportData: !command && grid && !editSession && !busy ? () => void exportRows(grid) : undefined, fetchAllRows: !command && grid?.more && !busy ? () => void fetchAll() : undefined, diff --git a/app/src/keymap.test.ts b/app/src/keymap.test.ts index 81918c2..f03bb81 100644 --- a/app/src/keymap.test.ts +++ b/app/src/keymap.test.ts @@ -265,15 +265,18 @@ describe("keymap", () => { expect(replace).not.toHaveBeenCalled(); }); - test("Ctrl Y rehace y Ctrl Enter ejecuta como alias", () => { + test("Ctrl Y rehace y Ctrl Enter ejecuta la sentencia del cursor", () => { expect(commands.redo.alt).toEqual(["Ctrl+Y"]); - expect(commands.execute.alt).toEqual(["Ctrl+Enter"]); + expect(commands.execute.alt).toBeUndefined(); + expect(commands.executeStatement.keys).toBe("Ctrl+Enter"); const redo = vi.fn(); expect(handleShortcut(key("Ctrl+Y"), { redo })).toBe(true); expect(redo).toHaveBeenCalled(); const execute = vi.fn(); - expect(handleShortcut(key("Ctrl+Enter"), { execute })).toBe(true); - expect(execute).toHaveBeenCalled(); + const executeStatement = vi.fn(); + expect(handleShortcut(key("Ctrl+Enter"), { execute, executeStatement })).toBe(true); + expect(executeStatement).toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); }); test("comandos nuevos con sus teclas", () => { diff --git a/app/src/keymap.ts b/app/src/keymap.ts index d3e3ae4..be34d5d 100644 --- a/app/src/keymap.ts +++ b/app/src/keymap.ts @@ -6,6 +6,7 @@ export type CommandId = | "selectGridRows" | "copyGrid" | "execute" + | "executeStatement" | "executeScript" | "cancel" | "commit" @@ -77,7 +78,8 @@ export interface Command { } const list: Command[] = [ - { id: "execute", label: "Ejecutar", keys: "F8", alt: ["Ctrl+Enter"] }, + { id: "execute", label: "Ejecutar", keys: "F8" }, + { id: "executeStatement", label: "Ejecutar sentencia", keys: "Ctrl+Enter" }, { id: "fetchAllRows", label: "Traer todas", keys: "Ctrl+Shift+End" }, { id: "exportData", label: "Exportar CSV", keys: "Ctrl+Shift+X" }, { id: "selectGridRows", label: "Seleccionar filas cargadas", keys: "Ctrl+A" }, From f7c1614b8fb0bd5bb40275b8eaf5699924f6959d Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Mon, 30 Nov 2026 09:45:33 -0300 Subject: [PATCH 4/8] =?UTF-8?q?feat(app):=20WAL-128=20un=20resultado=20por?= =?UTF-8?q?=20pesta=C3=B1a=20en=20la=20ventana=20SQL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cada SELECT abre su pestaña (Select tabla o Consulta N) con su propio cursor: trae más filas, exporta y edita por su cuenta. Una ejecución nueva libera los cursores anteriores. Cambiar de pestaña con ediciones pendientes pide confirmar, y el aviso de traer filas queda en su pestaña. Co-Authored-By: Claude Opus 5.5 --- app/src/components/SqlWindow.test.tsx | 118 +++++++++++++++++++++++ app/src/components/SqlWindow.tsx | 134 +++++++++++++++++++------- app/src/sqlScript.test.ts | 13 ++- app/src/sqlScript.ts | 10 ++ 4 files changed, 238 insertions(+), 37 deletions(-) diff --git a/app/src/components/SqlWindow.test.tsx b/app/src/components/SqlWindow.test.tsx index 4ea58c8..c71a23f 100644 --- a/app/src/components/SqlWindow.test.tsx +++ b/app/src/components/SqlWindow.test.tsx @@ -915,3 +915,121 @@ describe("F8 y Ctrl+Enter", () => { expect(execute.mock.calls[0][1]).toBe("INSERT INTO t VALUES (1)"); }); }); + +describe("una pestaña por resultado", () => { + const two = "select * from PER_MARCACION_REG t;\n\nselect * from PER_MARCACION_AUX t;"; + + test("cada SELECT abre su pestaña y queda activa la última", async () => { + vi.spyOn(api, "sqlExecute") + .mockResolvedValueOnce(query([["1", "REG"]], false, 1)) + .mockResolvedValueOnce(query([["2", "AUX"]], false, 2)); + const { ref } = setup(two); + await act(async () => ref.current!.execute!()); + const first = screen.getByRole("tab", { name: "Select PER_MARCACION_REG" }); + const second = screen.getByRole("tab", { name: "Select PER_MARCACION_AUX" }); + expect(second).toHaveAttribute("aria-selected", "true"); + expect(screen.getByText("AUX")).toBeInTheDocument(); + fireEvent.click(first); + expect(first).toHaveAttribute("aria-selected", "true"); + expect(screen.getByText("REG")).toBeInTheDocument(); + expect(screen.queryByText("AUX")).not.toBeInTheDocument(); + }); + + test("Traer todas en una pestaña anterior usa su propio cursor", async () => { + vi.spyOn(api, "sqlExecute") + .mockResolvedValueOnce(query([["1", "REG"]], true, 1)) + .mockResolvedValueOnce(query([["2", "AUX"]], false, 2)); + const fetch = vi.spyOn(api, "sqlFetch").mockResolvedValue({ rows: [["3", "MAS"]], more: false }); + const { ref } = setup(two); + await act(async () => ref.current!.execute!()); + fireEvent.click(screen.getByRole("tab", { name: "Select PER_MARCACION_REG" })); + await act(async () => ref.current!.fetchAllRows!()); + expect(fetch).toHaveBeenCalledWith("w1", 1, expect.any(Number)); + expect(screen.getByText("MAS")).toBeInTheDocument(); + }); + + test("ejecutar de nuevo libera los cursores de la ejecución anterior", async () => { + vi.spyOn(api, "sqlExecute") + .mockResolvedValueOnce(query([["1", "REG"]], true, 1)) + .mockResolvedValueOnce(query([["2", "AUX"]], false, 2)) + .mockResolvedValueOnce(query([["9", "NUEVO"]], false, 3)); + const fetch = vi.spyOn(api, "sqlFetch").mockResolvedValue({ rows: [], more: false }); + const { ref, view } = setup(two); + await act(async () => ref.current!.execute!()); + act(() => view.dispatch({ selection: { anchor: 3 } })); + await act(async () => ref.current!.executeStatement!()); + expect(fetch).toHaveBeenCalledWith("w1", 1, 0); + expect(screen.queryByRole("tab", { name: "Select PER_MARCACION_AUX" })).not.toBeInTheDocument(); + expect(screen.getByRole("tab", { name: "Select PER_MARCACION_REG" })).toHaveAttribute("aria-selected", "true"); + }); + + test("rollback deja todas las pestañas sin más filas", async () => { + vi.spyOn(api, "sqlExecute") + .mockResolvedValueOnce({ ...query([["1", "REG"]], true, 1), transaction: true }) + .mockResolvedValueOnce({ ...query([["2", "AUX"]], true, 2), transaction: true }); + vi.spyOn(api, "sqlRollback").mockResolvedValue(false); + const { ref } = setup(two); + await act(async () => ref.current!.execute!()); + await act(async () => ref.current!.rollback!()); + expect(ref.current!.fetchAllRows).toBeUndefined(); + fireEvent.click(screen.getByRole("tab", { name: "Select PER_MARCACION_REG" })); + expect(ref.current!.fetchAllRows).toBeUndefined(); + }); +}); + +test("cambiar de pestaña con ediciones pendientes pide confirmar", async () => { + const target = { + owner: "HR", name: "CLIENTES", + columns: [ + { name: "ID", data_type: "NUMBER", nullable: false, editable: true }, + { name: "NOMBRE", data_type: "VARCHAR2", nullable: true, editable: true }, + ], + }; + vi.spyOn(api, "sqlExecute") + .mockResolvedValueOnce(query([["1", "Ana"]], false, 1)) + .mockResolvedValueOnce(query([["7", "Otra"]], false, 2)) + .mockResolvedValueOnce({ + result: { + kind: "Query", cursor: 3, + columns: [ + { name: ROWID_COLUMN, type_name: "ROWID", numeric: false, lob: false }, + { name: "ID", type_name: "NUMBER", numeric: true, lob: false }, + { name: "NOMBRE", type_name: "VARCHAR2(40)", numeric: false, lob: false }, + ], + page: { rows: [["AAA1", "1", "Ana"]], more: false }, + }, + elapsed_ms: 1, output: [], transaction: false, + }); + vi.spyOn(api, "sqlEditTarget").mockResolvedValue(target); + const { ref } = setup("select id, nombre from clientes;\nselect * from otra;"); + await act(async () => ref.current!.execute!()); + fireEvent.click(screen.getByRole("tab", { name: "Select clientes" })); + await act(async () => ref.current!.editData!()); + const grid = screen.getByRole("grid", { name: "Resultados" }); + fireEvent.doubleClick(within(grid).getAllByRole("gridcell", { name: /^NOMBRE / })[0]); + const input = within(grid).getByRole("textbox", { name: "Editar NOMBRE" }); + fireEvent.change(input, { target: { value: "Ana María" } }); + fireEvent.keyDown(input, { key: "Enter" }); + const confirm = vi.spyOn(window, "confirm").mockReturnValue(false); + fireEvent.click(screen.getByRole("tab", { name: "Select otra" })); + expect(confirm).toHaveBeenCalled(); + expect(screen.getByRole("tab", { name: "Select clientes" })).toHaveAttribute("aria-selected", "true"); + confirm.mockReturnValue(true); + fireEvent.click(screen.getByRole("tab", { name: "Select otra" })); + expect(screen.getByRole("tab", { name: "Select otra" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getByText("Otra")).toBeInTheDocument(); +}); + +test("traer filas en una pestaña no muestra el aviso en otra", async () => { + vi.spyOn(api, "sqlExecute") + .mockResolvedValueOnce(query([["1", "REG"]], true, 1)) + .mockResolvedValueOnce(query([["2", "AUX"]], false, 2)); + vi.spyOn(api, "sqlFetch").mockReturnValue(new Promise(() => {})); + const { ref } = setup("select * from PER_MARCACION_REG t;\nselect * from PER_MARCACION_AUX t;"); + await act(async () => ref.current!.execute!()); + fireEvent.click(screen.getByRole("tab", { name: "Select PER_MARCACION_REG" })); + act(() => ref.current!.fetchAllRows!()); + expect(screen.getByRole("button", { name: /Traer todas/ })).toBeInTheDocument(); + fireEvent.click(screen.getByRole("tab", { name: "Select PER_MARCACION_AUX" })); + expect(screen.queryByRole("button", { name: /Traer todas/ })).not.toBeInTheDocument(); +}); diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index 966abd4..f3b4823 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -25,7 +25,7 @@ import { editableQuery, ROWID_COLUMN } from "../sqlEdit"; import { appliedRows, buildChanges, emptyPending, pendingCount, pendingDiscardMessage, type Cell, type Pending } from "../gridEdits"; import { copyGridCells, withBom } from "../gridSelection"; import { ResultGrid, type CellPosition, type RowStatus } from "./ResultGrid"; -import { splitScript, statementAt, type ScriptStatement } from "../sqlScript"; +import { resultTitle, splitScript, statementAt, type ScriptStatement } from "../sqlScript"; import { applySubstitutions, assignedBinds, findVariables } from "../sqlBinds"; import type { CompletionCatalog } from "../programCompletion"; import { ProgramEditor, type EditorMarker } from "./ProgramEditor"; @@ -94,7 +94,21 @@ interface HistoryEntry { } type Tab = "variables" | "results" | "output" | "history" | "plan"; -const RESULT_TABS = [["results", "Resultados"], ["output", "Salida"], ["history", "Historial"]] as const; + +/** Pestaña de la barra de resultados; `result` es el índice de la pestaña de resultado que muestra. */ +interface TabEntry { + key: string; + tab: Tab; + label: string; + result?: number; +} + +/** Resultado de un SELECT de la última ejecución, con su propio cursor. */ +interface ResultTab { + title: string; + grid: Grid; + query: { sql: string; binds: BindValue[] }; +} const EDITOR_SHARE = { initial: 70, min: 20, max: 85, step: 4 }; const clampEditorShare = (share: number) => Math.max(EDITOR_SHARE.min, Math.min(EDITOR_SHARE.max, Math.round(share))); const FETCH_ALL = 1000; @@ -163,11 +177,45 @@ export function SqlWindow({ const [plan, setPlan] = useState(null); const [planSelection, setPlanSelection] = useState(null); const [planning, setPlanning] = useState(false); - const tabs: readonly (readonly [Tab, string])[] = [ - ...(hasTestVariables ? [["variables", "Variables"] as const] : []), - ...RESULT_TABS, ...(plan ? [["plan", "Plan"] as const] : []), + const [results, setResults] = useState([]); + const [activeResult, setActiveResult] = useState(0); + const resultsRef = useRef(results); + resultsRef.current = results; + const activeResultRef = useRef(activeResult); + activeResultRef.current = activeResult; + const grid = results[activeResult]?.grid ?? null; + const fetchingHere = (cursor: number | undefined) => fetching && fetchingCursor === cursor; + const activeQuery = results[activeResult]?.query ?? null; + /** Aplica `update` a la grilla de cada pestaña; las que no corresponden la devuelven igual. */ + const updateGrids = (update: (current: Grid) => Grid) => + setResults((current) => current.map((result) => ({ ...result, grid: update(result.grid) }))); + const replaceActiveGrid = (next: Grid) => + setResults((current) => current.map((result, index) => index === activeResultRef.current ? { ...result, grid: next } : result)); + const tabs: TabEntry[] = [ + ...(hasTestVariables ? [{ key: "variables", tab: "variables" as const, label: "Variables" }] : []), + ...(results.length + ? results.map((result, index) => ({ key: `result-${index}`, tab: "results" as const, label: result.title, result: index })) + : [{ key: "results", tab: "results" as const, label: "Resultados" }]), + { key: "output", tab: "output", label: "Salida" }, + { key: "history", tab: "history", label: "Historial" }, + ...(plan ? [{ key: "plan", tab: "plan" as const, label: "Plan" }] : []), ]; - const [grid, setGrid] = useState(null); + const isSelectedTab = (entry: TabEntry) => + tab === entry.tab && (entry.result === undefined || entry.result === activeResult); + /** Activa la pestaña; pasar a otro resultado con ediciones pendientes pide confirmar. */ + function selectTab(entry: TabEntry): boolean { + if (entry.result !== undefined && entry.result !== activeResult) { + if (pendingCount(pending) && !window.confirm(pendingDiscardMessage(pendingCount(pending)))) return false; + setEditSession(null); + setPending(emptyPending()); + setConflicts(null); + setSelected(null); + setFetchError(null); + setActiveResult(entry.result); + } + setTab(entry.tab); + return true; + } const [summary, setSummary] = useState(null); const { lines, omitted: omittedLines, append, flush: flushOutput, clear: clearOutput } = useLineBuffer(command ? 2000 : 10000); @@ -195,6 +243,8 @@ export function SqlWindow({ const draft = useMemo(() => routine && routineDraft(routine.path, routine.signature, routine.overloaded, omitted), [routine, omitted]); const declaredOutputs = draft?.outputs ?? testSettings?.outputs; const [fetching, setFetching] = useState(false); + // Cursor de la pestaña que está trayendo filas; las demás no muestran el aviso. + const [fetchingCursor, setFetchingCursor] = useState(null); const [fetchError, setFetchError] = useState(null); const [notice, setNotice] = useState(""); const [editorShare, setEditorShare] = useState(EDITOR_SHARE.initial); @@ -205,7 +255,6 @@ export function SqlWindow({ const saved = useRef(initialSql); const fileName = useRef(testSettings?.fileName ?? null); const started = useRef(false); - const lastQueryRef = useRef<{ sql: string; binds: BindValue[] } | null>(null); const [editSession, setEditSession] = useState(null); const [pending, setPending] = useState(emptyPending); const count = pendingCount(pending); @@ -360,6 +409,7 @@ export function SqlWindow({ setRunning(true); let startedSql = false; let lastQuery = false; + let produced = 0; let productionApproved = environment !== "prod"; const promptedBinds = new Map(); const ask: SqlplusCtx["ask"] = io?.ask ?? (async (name) => { @@ -383,10 +433,7 @@ export function SqlWindow({ const context: SqlplusCtx = { print: (line, kind) => appendLine(kind ?? "info", line), ask, - query: (sql, binds = []) => { - setGrid((current) => current?.more ? { ...current, more: false } : current); - return api.sqlExecute(sessionId, sql, binds); - }, + query: (sql, binds = []) => api.sqlExecute(sessionId, sql, binds), readFile: api.readScriptFile, writeFile: api.writeSpoolFile, runScript: async (source, child) => { @@ -441,6 +488,13 @@ export function SqlWindow({ } if (!startedSql) { startedSql = true; + // Una ejecución nueva reemplaza las pestañas: sus cursores abiertos se liberan. + for (const previous of resultsRef.current) { + if (previous.grid.more) void api.sqlFetch(sessionId, previous.grid.cursor, 0).catch(() => {}); + } + resultsRef.current = []; + setResults([]); + setActiveResult(0); setEditSession(null); setPending(emptyPending()); setConflicts(null); @@ -449,11 +503,9 @@ export function SqlWindow({ let outcome: ExecOutcome; try { setFetchError(null); - setGrid((current) => current?.more ? { ...current, more: false } : current); outcome = await (outputs.length ? api.sqlExecute(sessionId, sql, binds, undefined, outputs) : api.sqlExecute(sessionId, sql, binds)); - if (outcome.result.kind === "Query") lastQueryRef.current = { sql, binds }; if (outcome.result.kind === "Failed") { if (sqlplus.settings.serveroutput) outcome.output.forEach((line) => log("output", line)); onTransaction(outcome.transaction); @@ -508,7 +560,13 @@ export function SqlWindow({ } if (stopFetchRef.current) return false; } else { - setGrid(result); + const index = produced++; + const entry: ResultTab = { title: resultTitle(sql, index), grid: result, query: { sql, binds } }; + // Las refs al día: Editar datos lee el resultado justo después de ejecutar. + resultsRef.current = [...resultsRef.current, entry]; + activeResultRef.current = index; + setResults((current) => [...current, entry]); + setActiveResult(index); if (exportQuery) await exportRows(result); } lastQuery = true; @@ -539,10 +597,11 @@ export function SqlWindow({ setSelected(null); setNotice(""); const cursor = result.cursor; + setFetchingCursor(cursor); let received = result.rows.length; const exported = forExport ? [...result.rows] : []; const stopped = () => { - setGrid((current) => current?.cursor === cursor ? { ...current, more: false } : current); + updateGrids((current) => current.cursor === cursor ? { ...current, more: false } : current); setNotice(`Traer todas detenido. ${received === 1 ? "Se conserva 1 fila" : `Se conservan ${received} filas`}.`); }; try { @@ -551,7 +610,7 @@ export function SqlWindow({ const page = await api.sqlFetch(sessionId, cursor, FETCH_ALL); received += page.rows.length; if (forExport) exported.push(...page.rows); - setGrid((current) => current?.cursor === cursor + updateGrids((current) => current.cursor === cursor ? { ...current, rows: [...current.rows, ...page.rows], more: page.more } : current); more = page.more; @@ -566,12 +625,13 @@ export function SqlWindow({ } const message = detail.code && !detail.message.startsWith(detail.code) ? `${detail.code} ${detail.message}` : detail.message; - setGrid((current) => current?.cursor === cursor ? { ...current, more: false } : current); + updateGrids((current) => current.cursor === cursor ? { ...current, more: false } : current); setFetchError(`${message} · Reejecuta con F8`); log("error", message); } finally { fetchingRef.current = false; setFetching(false); + setFetchingCursor(null); } } @@ -593,7 +653,7 @@ export function SqlWindow({ if (running || applying || fetchingRef.current) return; try { const open = action === "commit" ? await api.sqlCommit(sessionId) : await api.sqlRollback(sessionId); - if (action === "rollback") setGrid((current) => current?.more ? { ...current, more: false } : current); + if (action === "rollback") updateGrids((current) => current.more ? { ...current, more: false } : current); onTransaction(open); log("info", action === "commit" ? "Commit hecho" : "Rollback hecho"); } catch (error) { @@ -614,7 +674,8 @@ export function SqlWindow({ setConflicts(null); return; } - const query = lastQueryRef.current; + const active = resultsRef.current[activeResultRef.current]; + const query = active?.query ?? null; if (!query) { setAlert("Ejecuta una consulta para editar sus filas"); return; @@ -636,7 +697,8 @@ export function SqlWindow({ if (outcome.result.kind !== "Query") return; const { cursor: id, columns, page } = outcome.result; const visible = columns.slice(1); - setGrid({ cursor: id, columns, rows: page.rows, more: page.more, elapsed: outcome.elapsed_ms, hiddenRowid: columns[0]?.name === ROWID_COLUMN }); + if (active?.grid.more) void api.sqlFetch(sessionId, active.grid.cursor, 0).catch(() => {}); + replaceActiveGrid({ cursor: id, columns, rows: page.rows, more: page.more, elapsed: outcome.elapsed_ms, hiddenRowid: columns[0]?.name === ROWID_COLUMN }); setFetchError(null); setEditSession({ target, @@ -737,11 +799,11 @@ export function SqlWindow({ try { const result = await api.sqlApply(sessionId, editSession.target, changes); if (result.kind === "Conflicts") { - setGrid({ ...grid, rows }); + replaceActiveGrid({ ...grid, rows }); setConflicts({ list: result.conflicts, rowsOf }); return; } - setGrid({ ...grid, rows: appliedRows(rows, pending, result.inserted) }); + replaceActiveGrid({ ...grid, rows: appliedRows(rows, pending, result.inserted) }); setPending(emptyPending()); setConflicts(null); setSelected(null); @@ -922,7 +984,7 @@ export function SqlWindow({ }, []); const offset = grid?.hiddenRowid ? 1 : 0; - const insertSource = lastQueryRef.current?.sql; + const insertSource = activeQuery?.sql; const insertTarget = useMemo(() => insertSource ? editableQuery(insertSource)?.table : undefined, [insertSource]); const insertTable = editSession?.target ?? insertTarget; const visibleColumns: SqlColumn[] = grid ? grid.columns.slice(offset) : []; @@ -1062,25 +1124,25 @@ export function SqlWindow({
{ - const order = tabs.map(([id]) => id); const step = { ArrowRight: 1, ArrowLeft: -1 }[event.key]; if (!step) return; - const next = order[(order.indexOf(tab) + step + order.length) % order.length]; - setTab(next); - const nextIndex = order.indexOf(next); + const current = Math.max(0, tabs.findIndex(isSelectedTab)); + const nextIndex = (current + step + tabs.length) % tabs.length; + if (!selectTab(tabs[nextIndex])) return; event.currentTarget.querySelectorAll('[role="tab"]')[nextIndex]?.focus(); }}> - {tabs.map(([id, label]) => ( - ))}
- {tab === "results" && (grid?.more || fetching) && ( + {tab === "results" && (grid?.more || fetchingHere(grid?.cursor)) && (