Skip to content

Commit 56607bd

Browse files
feat(frontend): apply / discard staging bar with IPC
Add GridStagingToolbar (revert + save), db_apply_staging command that rebuilds the Rust buffer from a TS snapshot, and table-target wiring so Save refreshes Data after a successful transaction. Closes #1891
1 parent 3e73aef commit 56607bd

14 files changed

Lines changed: 606 additions & 24 deletions

File tree

‎apps/tauri/src-tauri/src/commands.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::connection::{
55
};
66
use crate::profiles::{ConnectionProfile, ProfileStore, ProfileStoreError};
77
use crate::secrets::SharedSecretStore;
8+
use crate::staging::{apply_staging_request, ApplyResult, StagingApplyRequest};
89
use serde::Deserialize;
910
use tauri::ipc::Channel;
1011
use tauri::State;
@@ -505,3 +506,12 @@ pub fn db_execute_query(
505506
.map_err(|e| ConnectionError::io(format!("query channel closed: {e}")))
506507
})
507508
}
509+
510+
/// Apply frontend staging edits in a single transaction (#1891).
511+
#[tauri::command]
512+
pub fn db_apply_staging(
513+
request: StagingApplyRequest,
514+
registry: State<'_, ConnectionRegistry>,
515+
) -> Result<ApplyResult, ConnectionError> {
516+
apply_staging_request(&registry, request)
517+
}

‎apps/tauri/src-tauri/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ pub use staging::{
2020
};
2121

2222
use commands::{
23-
db_connect_mysql, db_connect_postgres, db_connect_sqlite, db_describe_object, db_disconnect,
24-
db_erd_schema, db_execute_query, db_is_connected, db_list_children, db_list_columns,
25-
db_list_schemas, db_list_tables, db_postgres_object_detail, db_sqlite_overview,
23+
db_apply_staging, db_connect_mysql, db_connect_postgres, db_connect_sqlite, db_describe_object,
24+
db_disconnect, db_erd_schema, db_execute_query, db_is_connected, db_list_children,
25+
db_list_columns, db_list_schemas, db_list_tables, db_postgres_object_detail, db_sqlite_overview,
2626
profiles_connect_mysql, profiles_connect_postgres, profiles_connect_sqlite, profiles_delete,
2727
profiles_list, profiles_upsert,
2828
};
@@ -106,6 +106,7 @@ pub fn run() {
106106
db_sqlite_overview,
107107
db_erd_schema,
108108
db_execute_query,
109+
db_apply_staging,
109110
profiles_list,
110111
profiles_upsert,
111112
profiles_delete,
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
//! IPC payload: rebuild a [`StagingBuffer`] from the frontend snapshot and apply.
2+
3+
use super::apply::{
4+
apply_staging_mysql, apply_staging_postgres, apply_staging_sqlite, ApplyError, ApplyResult,
5+
};
6+
use super::StagingBuffer;
7+
use crate::connection::{
8+
ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, DriverKind,
9+
};
10+
use serde::Deserialize;
11+
use std::collections::BTreeSet;
12+
13+
/// One staged cell edit (JSON-friendly; Maps don't round-trip cleanly).
14+
#[derive(Debug, Clone, Deserialize)]
15+
#[serde(rename_all = "camelCase")]
16+
pub struct StagedCellEdit {
17+
pub row: usize,
18+
pub col: usize,
19+
pub value: String,
20+
}
21+
22+
/// Frontend staging snapshot for apply (#1891).
23+
#[derive(Debug, Clone, Deserialize)]
24+
#[serde(rename_all = "camelCase")]
25+
pub struct StagingApplyRequest {
26+
pub connection_id: ConnectionId,
27+
pub table_name: String,
28+
pub schema: Option<String>,
29+
pub columns: Vec<String>,
30+
pub primary_keys: Vec<String>,
31+
pub original_rows: Vec<Vec<String>>,
32+
pub modified_cells: Vec<StagedCellEdit>,
33+
pub inserted_rows: Vec<Vec<String>>,
34+
pub deleted_row_indices: Vec<usize>,
35+
}
36+
37+
impl StagingApplyRequest {
38+
pub fn into_buffer(self) -> StagingBuffer {
39+
let mut buf = StagingBuffer::new(
40+
self.columns,
41+
self.original_rows,
42+
self.primary_keys,
43+
);
44+
for edit in self.modified_cells {
45+
buf.set_cell(edit.row, edit.col, edit.value);
46+
}
47+
for row in self.inserted_rows {
48+
buf.add_row(Some(row));
49+
}
50+
let deleted: BTreeSet<usize> = self.deleted_row_indices.into_iter().collect();
51+
for idx in deleted {
52+
buf.toggle_delete_row(idx);
53+
}
54+
buf
55+
}
56+
}
57+
58+
/// Apply staged edits on the live connection; clears buffer only on success (Rust side).
59+
pub fn apply_staging_request(
60+
registry: &ConnectionRegistry,
61+
req: StagingApplyRequest,
62+
) -> Result<ApplyResult, ConnectionError> {
63+
let id = req.connection_id.clone();
64+
let table = req.table_name.clone();
65+
let schema = req.schema.clone();
66+
let mut buffer = req.into_buffer();
67+
68+
let driver = registry
69+
.driver_of(&id)
70+
.ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?;
71+
72+
let result = match driver {
73+
DriverKind::Sqlite => registry.with_sqlite(&id, |s| {
74+
s.with_connection(|conn| {
75+
apply_staging_sqlite(conn, &mut buffer, &table, schema.as_deref())
76+
.map_err(map_apply_error)
77+
})
78+
}),
79+
DriverKind::Postgres => registry.with_postgres(&id, |s| {
80+
s.with_pool(|pool| {
81+
apply_staging_postgres(pool, &mut buffer, &table, schema.as_deref())
82+
.map_err(map_apply_error)
83+
})
84+
}),
85+
DriverKind::Mysql => registry.with_mysql(&id, |s| {
86+
s.with_pool(|pool| {
87+
apply_staging_mysql(pool, &mut buffer, &table, schema.as_deref())
88+
.map_err(map_apply_error)
89+
})
90+
}),
91+
}?;
92+
93+
Ok(result)
94+
}
95+
96+
fn map_apply_error(err: ApplyError) -> ConnectionError {
97+
ConnectionError::io(err.to_string())
98+
}

‎apps/tauri/src-tauri/src/staging/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ mod apply;
88
mod apply_live;
99
mod buffer;
1010
mod dml;
11+
mod ipc;
1112

1213
pub use apply::{
1314
apply_plan_mysql, apply_plan_postgres, apply_plan_sqlite, apply_staging_mysql,
@@ -20,3 +21,4 @@ pub use dml::{
2021
generate_plan, MutationType, SqlDialect, StagingColumnMeta, TableMutationPlan,
2122
TableMutationStatement,
2223
};
24+
pub use ipc::{apply_staging_request, StagingApplyRequest};

‎apps/tauri/src/api/staging.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { invoke } from "@tauri-apps/api/core";
2+
3+
export type StagingApplyRequest = {
4+
connectionId: string;
5+
tableName: string;
6+
schema?: string | null;
7+
columns: string[];
8+
primaryKeys: string[];
9+
originalRows: string[][];
10+
modifiedCells: { row: number; col: number; value: string }[];
11+
insertedRows: string[][];
12+
deletedRowIndices: number[];
13+
};
14+
15+
export type ApplyResult = {
16+
statements_applied: number;
17+
};
18+
19+
/** Apply staged grid edits in one DB transaction. */
20+
export async function dbApplyStaging(
21+
request: StagingApplyRequest,
22+
): Promise<ApplyResult> {
23+
return invoke<ApplyResult>("db_apply_staging", { request });
24+
}

‎apps/tauri/src/staging/buffer.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,16 @@ describe("StagingBuffer (frontend)", () => {
4141
expect(buf.effectiveRows()[0]?.[2]).toBe("NULL");
4242
expect(NULL_SENTINEL).toContain("QUERYA_NULL");
4343
});
44+
45+
it("addRow and toApplySnapshot", () => {
46+
const buf = sample();
47+
buf.setCell(0, 1, "Alicia");
48+
buf.addRow(["3", "Carol", "carol@test.com"]);
49+
const snap = buf.toApplySnapshot();
50+
expect(snap.modifiedCells).toEqual([
51+
{ row: 0, col: 1, value: "Alicia" },
52+
]);
53+
expect(snap.insertedRows).toHaveLength(1);
54+
expect(snap.primaryKeys).toEqual(["id"]);
55+
});
4456
});

‎apps/tauri/src/staging/buffer.ts‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ export class StagingBuffer {
3333
replaceBaseline(
3434
columns: string[],
3535
rows: string[][],
36-
primaryKeys: string[] = [],
36+
primaryKeys?: string[],
3737
): void {
3838
this.columns = [...columns];
3939
this.originalRows = rows.map((r) => [...r]);
40-
this.primaryKeys = [...primaryKeys];
40+
if (primaryKeys) this.primaryKeys = [...primaryKeys];
4141
this.modifiedCells.clear();
4242
this.insertedRows = [];
4343
this.deletedRowIndices.clear();
@@ -165,6 +165,44 @@ export class StagingBuffer {
165165
this.revision += 1;
166166
}
167167

168+
addRow(initial?: string[]): number {
169+
const row =
170+
initial ?? Array.from({ length: this.columns.length }, () => "");
171+
this.insertedRows.push([...row]);
172+
this.revision += 1;
173+
return this.totalRowCount() - 1;
174+
}
175+
176+
/** Snapshot for `db_apply_staging` IPC. */
177+
toApplySnapshot(): {
178+
columns: string[];
179+
primaryKeys: string[];
180+
originalRows: string[][];
181+
modifiedCells: { row: number; col: number; value: string }[];
182+
insertedRows: string[][];
183+
deletedRowIndices: number[];
184+
} {
185+
const modifiedCells: { row: number; col: number; value: string }[] = [];
186+
for (const [row, cols] of this.modifiedCells) {
187+
for (const [col, value] of cols) {
188+
modifiedCells.push({ row, col, value });
189+
}
190+
}
191+
return {
192+
columns: [...this.columns],
193+
primaryKeys: [...this.primaryKeys],
194+
originalRows: this.originalRows.map((r) => [...r]),
195+
modifiedCells,
196+
insertedRows: this.insertedRows.map((r) => [...r]),
197+
deletedRowIndices: [...this.deletedRowIndices],
198+
};
199+
}
200+
201+
setPrimaryKeys(keys: string[]): void {
202+
this.primaryKeys = [...keys];
203+
this.revision += 1;
204+
}
205+
168206
/** Effective grid values (deleted rows kept for strike-through). */
169207
effectiveRows(): string[][] {
170208
const out: string[][] = [];

‎apps/tauri/src/stores/gridStaging.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,20 @@ describe("useGridStagingStore", () => {
3737
expect(store.isDirty).toBe(false);
3838
expect(store.getCellValue(0, 0)).toBe("2");
3939
});
40+
41+
it("revertAll discards dirty markers", () => {
42+
const store = useGridStagingStore();
43+
store.setTarget({
44+
connectionId: "c1",
45+
tableName: "users",
46+
primaryKeys: ["id"],
47+
});
48+
store.attachFromQuery(["id", "name"], [["1", "A"]]);
49+
store.setCell(0, 1, "B");
50+
expect(store.isDirty).toBe(true);
51+
expect(store.canApply).toBe(true);
52+
store.revertAll();
53+
expect(store.isDirty).toBe(false);
54+
expect(store.getCellValue(0, 1)).toBe("A");
55+
});
4056
});

0 commit comments

Comments
 (0)