Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apps/tauri/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::connection::{
};
use crate::profiles::{ConnectionProfile, ProfileStore, ProfileStoreError};
use crate::secrets::SharedSecretStore;
use crate::staging::{apply_staging_request, ApplyResult, StagingApplyRequest};
use serde::Deserialize;
use tauri::ipc::Channel;
use tauri::State;
Expand Down Expand Up @@ -505,3 +506,12 @@ pub fn db_execute_query(
.map_err(|e| ConnectionError::io(format!("query channel closed: {e}")))
})
}

/// Apply frontend staging edits in a single transaction (#1891).
#[tauri::command]
pub fn db_apply_staging(
request: StagingApplyRequest,
registry: State<'_, ConnectionRegistry>,
) -> Result<ApplyResult, ConnectionError> {
apply_staging_request(&registry, request)
}
7 changes: 4 additions & 3 deletions apps/tauri/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ pub use staging::{
};

use commands::{
db_connect_mysql, db_connect_postgres, db_connect_sqlite, db_describe_object, db_disconnect,
db_erd_schema, db_execute_query, db_is_connected, db_list_children, db_list_columns,
db_list_schemas, db_list_tables, db_postgres_object_detail, db_sqlite_overview,
db_apply_staging, db_connect_mysql, db_connect_postgres, db_connect_sqlite, db_describe_object,
db_disconnect, db_erd_schema, db_execute_query, db_is_connected, db_list_children,
db_list_columns, db_list_schemas, db_list_tables, db_postgres_object_detail, db_sqlite_overview,
profiles_connect_mysql, profiles_connect_postgres, profiles_connect_sqlite, profiles_delete,
profiles_list, profiles_upsert,
};
Expand Down Expand Up @@ -106,6 +106,7 @@ pub fn run() {
db_sqlite_overview,
db_erd_schema,
db_execute_query,
db_apply_staging,
profiles_list,
profiles_upsert,
profiles_delete,
Expand Down
98 changes: 98 additions & 0 deletions apps/tauri/src-tauri/src/staging/ipc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! IPC payload: rebuild a [`StagingBuffer`] from the frontend snapshot and apply.

use super::apply::{
apply_staging_mysql, apply_staging_postgres, apply_staging_sqlite, ApplyError, ApplyResult,
};
use super::StagingBuffer;
use crate::connection::{
ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, DriverKind,
};
use serde::Deserialize;
use std::collections::BTreeSet;

/// One staged cell edit (JSON-friendly; Maps don't round-trip cleanly).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StagedCellEdit {
pub row: usize,
pub col: usize,
pub value: String,
}

/// Frontend staging snapshot for apply (#1891).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StagingApplyRequest {
pub connection_id: ConnectionId,
pub table_name: String,
pub schema: Option<String>,
pub columns: Vec<String>,
pub primary_keys: Vec<String>,
pub original_rows: Vec<Vec<String>>,
pub modified_cells: Vec<StagedCellEdit>,
pub inserted_rows: Vec<Vec<String>>,
pub deleted_row_indices: Vec<usize>,
}

impl StagingApplyRequest {
pub fn into_buffer(self) -> StagingBuffer {
let mut buf = StagingBuffer::new(
self.columns,
self.original_rows,
self.primary_keys,
);
for edit in self.modified_cells {
buf.set_cell(edit.row, edit.col, edit.value);
}
for row in self.inserted_rows {
buf.add_row(Some(row));
}
let deleted: BTreeSet<usize> = self.deleted_row_indices.into_iter().collect();
for idx in deleted {
buf.toggle_delete_row(idx);
}
buf
}
}

/// Apply staged edits on the live connection; clears buffer only on success (Rust side).
pub fn apply_staging_request(
registry: &ConnectionRegistry,
req: StagingApplyRequest,
) -> Result<ApplyResult, ConnectionError> {
let id = req.connection_id.clone();
let table = req.table_name.clone();
let schema = req.schema.clone();
let mut buffer = req.into_buffer();

let driver = registry
.driver_of(&id)
.ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?;

let result = match driver {
DriverKind::Sqlite => registry.with_sqlite(&id, |s| {
s.with_connection(|conn| {
apply_staging_sqlite(conn, &mut buffer, &table, schema.as_deref())
.map_err(map_apply_error)
})
}),
DriverKind::Postgres => registry.with_postgres(&id, |s| {
s.with_pool(|pool| {
apply_staging_postgres(pool, &mut buffer, &table, schema.as_deref())
.map_err(map_apply_error)
})
}),
DriverKind::Mysql => registry.with_mysql(&id, |s| {
s.with_pool(|pool| {
apply_staging_mysql(pool, &mut buffer, &table, schema.as_deref())
.map_err(map_apply_error)
})
}),
}?;

Ok(result)
}

fn map_apply_error(err: ApplyError) -> ConnectionError {
ConnectionError::io(err.to_string())
}
2 changes: 2 additions & 0 deletions apps/tauri/src-tauri/src/staging/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod apply;
mod apply_live;
mod buffer;
mod dml;
mod ipc;

pub use apply::{
apply_plan_mysql, apply_plan_postgres, apply_plan_sqlite, apply_staging_mysql,
Expand All @@ -20,3 +21,4 @@ pub use dml::{
generate_plan, MutationType, SqlDialect, StagingColumnMeta, TableMutationPlan,
TableMutationStatement,
};
pub use ipc::{apply_staging_request, StagingApplyRequest};
24 changes: 24 additions & 0 deletions apps/tauri/src/api/staging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { invoke } from "@tauri-apps/api/core";

export type StagingApplyRequest = {
connectionId: string;
tableName: string;
schema?: string | null;
columns: string[];
primaryKeys: string[];
originalRows: string[][];
modifiedCells: { row: number; col: number; value: string }[];
insertedRows: string[][];
deletedRowIndices: number[];
};

export type ApplyResult = {
statements_applied: number;
};

/** Apply staged grid edits in one DB transaction. */
export async function dbApplyStaging(
request: StagingApplyRequest,
): Promise<ApplyResult> {
return invoke<ApplyResult>("db_apply_staging", { request });
}
12 changes: 12 additions & 0 deletions apps/tauri/src/staging/buffer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,16 @@ describe("StagingBuffer (frontend)", () => {
expect(buf.effectiveRows()[0]?.[2]).toBe("NULL");
expect(NULL_SENTINEL).toContain("QUERYA_NULL");
});

it("addRow and toApplySnapshot", () => {
const buf = sample();
buf.setCell(0, 1, "Alicia");
buf.addRow(["3", "Carol", "carol@test.com"]);
const snap = buf.toApplySnapshot();
expect(snap.modifiedCells).toEqual([
{ row: 0, col: 1, value: "Alicia" },
]);
expect(snap.insertedRows).toHaveLength(1);
expect(snap.primaryKeys).toEqual(["id"]);
});
});
42 changes: 40 additions & 2 deletions apps/tauri/src/staging/buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ export class StagingBuffer {
replaceBaseline(
columns: string[],
rows: string[][],
primaryKeys: string[] = [],
primaryKeys?: string[],
): void {
this.columns = [...columns];
this.originalRows = rows.map((r) => [...r]);
this.primaryKeys = [...primaryKeys];
if (primaryKeys) this.primaryKeys = [...primaryKeys];
this.modifiedCells.clear();
this.insertedRows = [];
this.deletedRowIndices.clear();
Expand Down Expand Up @@ -165,6 +165,44 @@ export class StagingBuffer {
this.revision += 1;
}

addRow(initial?: string[]): number {
const row =
initial ?? Array.from({ length: this.columns.length }, () => "");
this.insertedRows.push([...row]);
this.revision += 1;
return this.totalRowCount() - 1;
}

/** Snapshot for `db_apply_staging` IPC. */
toApplySnapshot(): {
columns: string[];
primaryKeys: string[];
originalRows: string[][];
modifiedCells: { row: number; col: number; value: string }[];
insertedRows: string[][];
deletedRowIndices: number[];
} {
const modifiedCells: { row: number; col: number; value: string }[] = [];
for (const [row, cols] of this.modifiedCells) {
for (const [col, value] of cols) {
modifiedCells.push({ row, col, value });
}
}
return {
columns: [...this.columns],
primaryKeys: [...this.primaryKeys],
originalRows: this.originalRows.map((r) => [...r]),
modifiedCells,
insertedRows: this.insertedRows.map((r) => [...r]),
deletedRowIndices: [...this.deletedRowIndices],
};
}

setPrimaryKeys(keys: string[]): void {
this.primaryKeys = [...keys];
this.revision += 1;
}

/** Effective grid values (deleted rows kept for strike-through). */
effectiveRows(): string[][] {
const out: string[][] = [];
Expand Down
16 changes: 16 additions & 0 deletions apps/tauri/src/stores/gridStaging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,20 @@ describe("useGridStagingStore", () => {
expect(store.isDirty).toBe(false);
expect(store.getCellValue(0, 0)).toBe("2");
});

it("revertAll discards dirty markers", () => {
const store = useGridStagingStore();
store.setTarget({
connectionId: "c1",
tableName: "users",
primaryKeys: ["id"],
});
store.attachFromQuery(["id", "name"], [["1", "A"]]);
store.setCell(0, 1, "B");
expect(store.isDirty).toBe(true);
expect(store.canApply).toBe(true);
store.revertAll();
expect(store.isDirty).toBe(false);
expect(store.getCellValue(0, 1)).toBe("A");
});
});
Loading
Loading