Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(sqlite): reject ambiguous keyless updates on duplicate rows

Melody Ruch5814ff008882
diff --git a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts
index f97d7f594c..fbf9132d09 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
cancelConditionalUpdate: vi.fn(),
executeInTransaction: vi.fn(),
executeInManualTransaction: vi.fn(),
+ executeQuery: vi.fn(),
addHistory: vi.fn(),
}));
@@ -22,6 +23,7 @@ vi.mock("@/lib/backend/api", () => ({
cancelConditionalUpdate: mocks.cancelConditionalUpdate,
executeInTransaction: mocks.executeInTransaction,
executeInManualTransaction: mocks.executeInManualTransaction,
+ executeQuery: mocks.executeQuery,
unlockConnectionWrites: vi.fn(),
lockConnectionWrites: vi.fn(),
connectionWriteUnlockState: vi.fn().mockResolvedValue(0),
@@ -621,6 +623,7 @@ describe("useDataGridEditor saveChanges reload", () => {
mocks.cancelConditionalUpdate.mockReset();
mocks.executeInTransaction.mockReset();
mocks.executeInManualTransaction.mockReset();
+ mocks.executeQuery.mockReset();
mocks.addHistory.mockReset();
mocks.getConfig.mockReset();
});
@@ -635,6 +638,9 @@ describe("useDataGridEditor saveChanges reload", () => {
manualTransactionSessionId?: string;
refreshSavedRows?: ReturnType<typeof vi.fn>;
onManualTransactionMutation?: ReturnType<typeof vi.fn>;
+ connectionId?: string;
+ primaryKeys?: string[];
+ onExecuteSql?: (sql: string) => Promise<void>;
} = {},
) {
const emit = vi.fn();
@@ -651,7 +657,7 @@ describe("useDataGridEditor saveChanges reload", () => {
result: computed(() => result.value),
editable: computed(() => true),
databaseType: computed(() => "mysql"),
- connectionId: computed(() => "connection-1"),
+ connectionId: computed(() => ("connectionId" in options ? options.connectionId : "connection-1")),
database: computed(() => "app"),
tableMeta: computed(() => ({
tableName: "orders_test",
@@ -659,11 +665,11 @@ describe("useDataGridEditor saveChanges reload", () => {
{ name: "id", data_type: "int" },
{ name: "status", data_type: "varchar" },
],
- primaryKeys: ["id"],
+ primaryKeys: options.primaryKeys ?? ["id"],
})),
sourceColumns: computed(() => undefined),
joinedWriteTargets: computed(() => options.joinedWriteTargets),
- onExecuteSql: computed(() => undefined),
+ onExecuteSql: computed(() => options.onExecuteSql),
customSaveHandler: computed(() => options.customSaveHandler),
manualTransactionSessionId: computed(() => options.manualTransactionSessionId),
onManualTransactionMutation: options.onManualTransactionMutation,
@@ -685,6 +691,69 @@ describe("useDataGridEditor saveChanges reload", () => {
return { editor, emit, currentPage };
}
+ // https://github.com/t8y2/dbx/issues/8321: without a primary key the row is
+ // addressed by matching every column value, and the loaded page cannot show
+ // whether another physical row matches the same condition.
+ const keylessGuard = {
+ sql: "SELECT COUNT(*) AS dbx_keyless_row_matches FROM orders_test WHERE (status = 'pending')",
+ maxMatchedRows: 1,
+ message: "Cannot safely update or delete this row: more than one row matches.",
+ };
+
+ it("refuses a keyless save when the server counts more than one row matching the predicate the save sends", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({
+ statements: ["UPDATE orders_test SET status='shipped' WHERE status = 'pending'"],
+ rollbackStatements: [],
+ keylessGuards: [keylessGuard],
+ });
+ mocks.executeQuery.mockResolvedValue({ columns: ["dbx_keyless_row_matches"], rows: [[2]] });
+
+ const { editor } = createSaveTestEditor({ primaryKeys: [] });
+ editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
+
+ await editor.saveChanges();
+
+ expect(mocks.executeQuery).toHaveBeenCalledWith("connection-1", "app", keylessGuard.sql, undefined);
+ expect(mocks.executeBatch).not.toHaveBeenCalled();
+ expect(editor.saveError.value).toBe(keylessGuard.message);
+ });
+
+ it("runs a keyless save once the server confirms the predicate matches a single row", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({
+ statements: ["UPDATE orders_test SET status='shipped' WHERE status = 'pending'"],
+ rollbackStatements: [],
+ keylessGuards: [keylessGuard],
+ });
+ mocks.executeQuery.mockResolvedValue({ columns: ["dbx_keyless_row_matches"], rows: [[1]] });
+ mocks.executeBatch.mockResolvedValue({ affected_rows: 1 });
+
+ const { editor } = createSaveTestEditor({ primaryKeys: [] });
+ editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
+
+ await editor.saveChanges();
+
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(1);
+ expect(editor.saveError.value).toBeFalsy();
+ });
+
+ it("refuses a keyless save when the guard cannot be counted on the server at all", async () => {
+ const onExecuteSql = vi.fn().mockResolvedValue(undefined);
+ mocks.prepareDataGridSave.mockResolvedValue({
+ statements: ["UPDATE orders_test SET status='shipped' WHERE status = 'pending'"],
+ rollbackStatements: [],
+ keylessGuards: [keylessGuard],
+ });
+
+ const { editor } = createSaveTestEditor({ primaryKeys: [], connectionId: undefined, onExecuteSql });
+ editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
+
+ await editor.saveChanges();
+
+ expect(onExecuteSql).not.toHaveBeenCalled();
+ expect(mocks.executeQuery).not.toHaveBeenCalled();
+ expect(editor.saveError.value).toContain("could not check on the server");
+ });
+
it("reloads after a pure row update, so database-computed columns (e.g. ON UPDATE CURRENT_TIMESTAMP) refresh without a manual page reload", async () => {
mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders_test SET status='shipped' WHERE id=1"], rollbackStatements: [] });
mocks.executeBatch.mockResolvedValue({ affected_rows: 1 });
diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts
index dd7b643c43..d5364205ae 100644
--- a/apps/desktop/src/composables/useDataGridEditor.ts
+++ b/apps/desktop/src/composables/useDataGridEditor.ts
@@ -1,6 +1,7 @@
import { joinedSaveOptions } from "@/lib/dataGrid/joinedRowChanges";
import { ref, shallowRef, triggerRef, computed, nextTick, watch, getCurrentInstance, onActivated, onBeforeUnmount, onDeactivated, onMounted, toRaw, type ComputedRef, type Ref } from "vue";
import * as api from "@/lib/backend/api";
+import type { DataGridSaveGuard } from "@/lib/backend/tauri";
import type { CellValue } from "@/lib/dataGrid/cellValue";
import { coerceDataGridCellValue, dataGridCellEditorText } from "@/lib/dataGrid/dataGridCellCoercion";
import { focusDataGridEditorWithoutScrolling, preserveDataGridScrollPosition } from "@/lib/dataGrid/dataGridEditorFocus";
@@ -20,6 +21,8 @@ import { normalizeBackendError } from "@/lib/backend/errorUtils";
import { uuid } from "@/lib/common/utils";
import i18n from "@/i18n";
+const KEYLESS_GUARD_UNVERIFIED_ERROR = "Cannot safely update or delete this row: the table has no primary key, and DBX could not check on the server whether the row can be targeted uniquely. Add a primary key or unique index before editing.";
+
interface RowItem {
id: number;
sourceIndex?: number;
@@ -1507,18 +1510,44 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
dirtyRows: new Map(stmtOptions.dirtyRows.map(([index, changes]) => [index, new Map(changes)])),
deletedRows: new Set(stmtOptions.deletedRows),
});
- const prepared: Awaited<ReturnType<typeof api.prepareDataGridSave>> = { statements: [], rollbackStatements: [] };
+ const prepared: Awaited<ReturnType<typeof api.prepareDataGridSave>> = { statements: [], rollbackStatements: [], keylessGuards: [] };
for (const group of groups) {
const part = await api.prepareDataGridSave(group, saveDriverProfile());
if (part.validationError) return part;
prepared.statements.push(...part.statements);
prepared.rollbackStatements.unshift(...part.rollbackStatements);
+ prepared.keylessGuards!.push(...(part.keylessGuards ?? []));
if (prepared.executionSchema && part.executionSchema && prepared.executionSchema !== part.executionSchema) throw new Error("Joined source tables require incompatible execution schemas.");
prepared.executionSchema ??= part.executionSchema;
}
return prepared;
}
+ // A keyless save can only be trusted once the server confirms that each
+ // predicate it sends addresses a single physical row; the loaded page cannot
+ // see rows outside it. Returns the error to fail with, or undefined to allow.
+ async function verifyKeylessGuards(guards: DataGridSaveGuard[], executionSchema?: string) {
+ if (!guards.length) return undefined;
+ const txnSessionId = manualTransactionSessionId.value;
+ // Without a connection to count against there is no way to verify the
+ // predicate, and an unverified keyless write is exactly what must not run.
+ if (!hasBackendSaveTarget.value) return KEYLESS_GUARD_UNVERIFIED_ERROR;
+ for (const guard of guards) {
+ let matched: unknown;
+ if (txnSessionId) {
+ const results = await api.executeInManualTransaction(txnSessionId, guard.sql, database.value ?? "", executionSchema, 1);
+ matched = (results.find((result) => result.columns.length > 0) ?? results[results.length - 1])?.rows?.[0]?.[0];
+ } else {
+ const result = await api.executeQuery(connectionId.value!, database.value ?? "", guard.sql, executionSchema);
+ matched = result?.rows?.[0]?.[0];
+ }
+ const count = Number(matched);
+ if (!Number.isFinite(count)) return KEYLESS_GUARD_UNVERIFIED_ERROR;
+ if (count > guard.maxMatchedRows) return guard.message;
+ }
+ return undefined;
+ }
+
function saveDriverProfile() {
const id = connectionId.value;
return id ? connectionStore.getConfig(id)?.driver_profile : undefined;
@@ -1844,6 +1873,18 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
return;
}
const rollbackStmts = preparedSave?.rollbackStatements ?? [];
+ try {
+ const guardError = await verifyKeylessGuards(preparedSave?.keylessGuards ?? [], preparedSave?.executionSchema);
+ if (guardError) {
+ saveError.value = guardError;
+ await finishInterruptedSaveChanges(snapshot);
+ return;
+ }
+ } catch (e: any) {
+ saveError.value = normalizeDataGridSaveError(databaseType.value, e);
+ await finishInterruptedSaveChanges(snapshot);
+ return;
+ }
const productionAssessment = assessProductionSql(stmts.join(";\n"), connection, database.value);
if (productionAssessment.active && productionAssessment.isMutation) {
// Autosave must never write production data without an operator reviewing the generated statements.
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index df59d358da..710f428f48 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1840,11 +1840,23 @@ export async function analyzeEditableQueryEditability(sql: string): Promise<Quer
return invoke("analyze_editable_query_editability", { sql });
}
+/// A server-side check that must pass before `statements` may run. Without a
+/// primary key a row is addressed by matching every column value, so the same
+/// predicate can match rows outside the loaded page; `sql` counts the matches
+/// of a predicate the save actually sends, and the save must be refused with
+/// `message` unless the returned count is at most `maxMatchedRows`.
+export interface DataGridSaveGuard {
+ sql: string;
+ maxMatchedRows: number;
+ message: string;
+}
+
export interface DataGridSavePreparation {
validationError?: string;
statements: string[];
rollbackStatements: string[];
executionSchema?: string;
+ keylessGuards?: DataGridSaveGuard[];
}
export async function prepareDataGridSave(options: DataGridSaveStatementOptions, driverProfile?: string): Promise<DataGridSavePreparation> {
diff --git a/crates/dbx-core/src/data_grid_sql.rs b/crates/dbx-core/src/data_grid_sql.rs
index 1fb7bd64e8..ce00834d1b 100644
--- a/crates/dbx-core/src/data_grid_sql.rs
+++ b/crates/dbx-core/src/data_grid_sql.rs
@@ -33,6 +33,11 @@ pub(crate) const DBX_NEO4J_ELEMENT_ID_COLUMN: &str = "__DBX_ELEMENT_ID";
pub(crate) const DBX_TDENGINE_TBNAME_COLUMN: &str = "tbname";
const DATA_GRID_COLUMN_DISTINCT_VALUES_DEFAULT_LIMIT: usize = 1000;
const DATA_GRID_COLUMN_DISTINCT_VALUES_MAX_LIMIT: usize = 1000;
+/// Alias for the single cell a keyless guard query returns.
+const KEYLESS_GUARD_COUNT_ALIAS: &str = "dbx_keyless_row_matches";
+const KEYLESS_AMBIGUOUS_ROW_ERROR: &str = "Cannot safely update or delete this row: the table has no primary key, so the row is identified by matching every column value, and more than one row in the table matches that condition. Add a primary key or unique index, or make the rows distinguishable, before editing.";
+const KEYLESS_UNIDENTIFIABLE_ROW_ERROR: &str = "Cannot safely update or delete this row: the table has no primary key and none of the result columns map to a table column, so there is no condition that can target a single row. Add a primary key, or edit the table directly, before saving.";
+
const MYSQL_DATA_GRID_BATCH_MAX_ROWS: usize = 500;
const MYSQL_DATA_GRID_BATCH_TARGET_SQL_BYTES: usize = 256 * 1024;
const ORACLE_SQL_LITERAL_MAX_BYTES: usize = 4000;
@@ -305,6 +310,23 @@ pub struct HiveTablePropertiesSqlOptions {
pub property_name: String,
}
+/// A server-side check that must pass before a keyless save may run.
+///
+/// Without a primary key a row is identified by matching every column value,
+/// so the same predicate can match physical rows the loaded page never saw.
+/// `sql` counts, on the server, how many rows one of the predicates this save
+/// actually sends to the database matches. The save must be refused with
+/// `message` unless the returned count is at most `max_matched_rows`, and also
+/// refused when the count cannot be obtained at all — an unverified keyless
+/// write is exactly the ambiguous write this guard exists to prevent.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DataGridSaveGuard {
+ pub sql: String,
+ pub max_matched_rows: u32,
+ pub message: String,
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataGridSavePreparation {
@@ -314,6 +336,9 @@ pub struct DataGridSavePreparation {
pub rollback_statements: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub execution_schema: Option<String>,
+ /// Checks the caller must run — and pass — before executing `statements`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub keyless_guards: Vec<DataGridSaveGuard>,
}
pub fn prepare_data_grid_save(options: DataGridSaveStatementOptions) -> DataGridSavePreparation {
@@ -335,14 +360,18 @@ pub fn prepare_data_grid_save_for_driver_profile(
driver_profile,
&options.table_meta,
),
+ keyless_guards: Vec::new(),
};
}
+ let mut keyless_guards = Vec::new();
+ let statements = build_data_grid_save_statements(&options, driver_profile, &mut keyless_guards);
DataGridSavePreparation {
validation_error: None,
- statements: build_data_grid_save_statements(&options, driver_profile),
+ statements,
rollback_statements: build_data_grid_rollback_statements(&options, driver_profile),
execution_schema: data_grid_save_execution_schema(options.database_type, driver_profile, &options.table_meta),
+ keyless_guards,
}
}
@@ -1109,6 +1138,9 @@ fn validate_data_grid_save(options: &DataGridSaveStatementOptions) -> Option<Str
if let Some(error) = validate_oracle_keyless_lob_predicate(options) {
return Some(error);
}
+ if let Some(error) = validate_keyless_row_predicate(options) {
+ return Some(error);
+ }
let save_columns = effective_columns(options);
let not_null_columns: Vec<String> = options
@@ -1224,6 +1256,42 @@ fn validate_oracle_keyless_lob_predicate(options: &DataGridSaveStatementOptions)
Some("Cannot safely update or delete this Oracle-compatible row because the table has LOB columns but no primary key or ROWID identifier.".to_string())
}
+/// Without a primary key a row can only be addressed by matching every column
+/// value, and `build_row_where` drops columns that have no source column of
+/// their own. When nothing is left, the generated predicate is empty and the
+/// UPDATE/DELETE would target the whole table, so there is neither a reliable
+/// row identifier nor anything a server-side check could count: refuse.
+///
+/// Whether a non-empty predicate really addresses a single physical row cannot
+/// be decided here — the loaded page is not the table. That decision belongs to
+/// the `keyless_guards` this preparation emits, which count the matches of the
+/// exact predicate on the server.
+fn validate_keyless_row_predicate(options: &DataGridSaveStatementOptions) -> Option<String> {
+ if !options.table_meta.primary_keys.is_empty() || !uses_keyless_row_predicate(options.database_type) {
+ return None;
+ }
+ let save_columns = effective_columns(options);
+ let column_info = options.table_meta.columns.as_deref().unwrap_or(&[]);
+ let touched_row_indexes =
+ options.dirty_rows.iter().map(|(row_index, _)| *row_index).chain(options.deleted_rows.iter().copied());
+ for row_index in touched_row_indexes {
+ let Some(row) = options.rows.get(row_index) else {
+ continue;
+ };
+ let predicate = build_row_where(
+ options.database_type,
+ &save_columns,
+ row,
+ column_info,
+ options.identifier_quote.as_deref(),
+ );
+ if predicate.trim().is_empty() {
+ return Some(KEYLESS_UNIDENTIFIABLE_ROW_ERROR.to_string());
+ }
+ }
+ None
+}
+
fn validate_clickhouse_mutable_updates(options: &DataGridSaveStatementOptions) -> Option<String> {
if options.database_type != Some(DatabaseType::ClickHouse) || options.dirty_rows.is_empty() {
return None;
@@ -1302,9 +1370,15 @@ fn validate_inserted_primary_keys(options: &DataGridSaveStatementOptions) -> Opt
None
}
+/// Builds the statements the save executes, and alongside them the server-side
+/// guards for every keyless predicate those statements actually send. The guard
+/// is derived from the same `where_clause` value the UPDATE/DELETE carries, so
+/// the safety decision can never be made against a different set of columns or
+/// values than the mutation itself uses.
fn build_data_grid_save_statements(
options: &DataGridSaveStatementOptions,
driver_profile: Option<&str>,
+ keyless_guards: &mut Vec<DataGridSaveGuard>,
) -> Vec<String> {
if options.database_type == Some(DatabaseType::Neo4j) {
return build_neo4j_data_grid_save_statements(options);
@@ -1335,6 +1409,17 @@ fn build_data_grid_save_statements(
let primary_key_set: Vec<String> =
options.table_meta.primary_keys.iter().map(|primary_key| normalize_column_name(primary_key)).collect();
+ let guards_keyless_predicates = primary_key_set.is_empty() && uses_keyless_row_predicate(options.database_type);
+ let mut guarded_predicates: Vec<String> = Vec::new();
+ let guard_predicate = |predicate: &str, guarded: &mut Vec<String>| {
+ if !guards_keyless_predicates || predicate.trim().is_empty() {
+ return;
+ }
+ if !guarded.iter().any(|existing| existing == predicate) {
+ guarded.push(predicate.to_string());
+ }
+ };
+
let batch_mysql_writes = supports_mysql_data_grid_batch(options);
let mut update_sets: Option<String> = None;
let mut update_predicates = Vec::new();
@@ -1378,6 +1463,7 @@ fn build_data_grid_save_statements(
column_info,
options.identifier_quote.as_deref(),
);
+ guard_predicate(&where_clause, &mut guarded_predicates);
if batch_mysql_writes {
if update_sets.as_deref().is_some_and(|current| current != sets) {
let current_sets = update_sets.take().unwrap_or_default();
@@ -1413,6 +1499,7 @@ fn build_data_grid_save_statements(
column_info,
options.identifier_quote.as_deref(),
);
+ guard_predicate(&where_clause, &mut guarded_predicates);
if batch_mysql_writes {
delete_predicates.push(where_clause);
} else {
@@ -1482,6 +1569,12 @@ fn build_data_grid_save_statements(
));
}
+ keyless_guards.extend(guarded_predicates.into_iter().map(|predicate| DataGridSaveGuard {
+ sql: format!("SELECT COUNT(*) AS {KEYLESS_GUARD_COUNT_ALIAS} FROM {table} WHERE ({predicate})"),
+ max_matched_rows: 1,
+ message: KEYLESS_AMBIGUOUS_ROW_ERROR.to_string(),
+ }));
+
statements
}
@@ -6740,6 +6833,163 @@ mod tests {
assert!(result.rollback_statements.is_empty());
}
+ fn daily_stats_keyless_options() -> DataGridSaveStatementOptions {
+ DataGridSaveStatementOptions {
+ database_type: Some(DatabaseType::Sqlite),
+ identifier_quote: None,
+ table_meta: DataGridTableMeta {
+ catalog: None,
+ database: None,
+ schema: None,
+ table_name: "daily_stats".to_string(),
+ primary_keys: vec![],
+ columns: Some(vec![column("stat_date", "TEXT", false, None), column("period", "TEXT", true, None)]),
+ },
+ columns: vec!["stat_date".to_string(), "period".to_string()],
+ source_columns: None,
+ rows: vec![vec![json!("2026-09-07"), Value::Null], vec![json!("2026-09-07"), Value::Null]],
+ dirty_rows: vec![(0, vec![(1, json!("早上"))])],
+ deleted_rows: vec![],
+ new_rows: vec![],
+ }
+ }
+
+ /// The predicate a guard counts must be byte-identical to the one its
+ /// statement carries, otherwise the safety decision is made against a
+ /// different set of columns or values than the mutation actually uses.
+ fn assert_guards_cover_statement_predicates(preparation: &DataGridSavePreparation) {
+ for guard in &preparation.keyless_guards {
+ assert_eq!(guard.max_matched_rows, 1);
+ let predicate = guard
+ .sql
+ .split_once(" WHERE (")
+ .and_then(|(_, rest)| rest.strip_suffix(')'))
+ .unwrap_or_else(|| panic!("guard is not a counting query: {}", guard.sql));
+ assert!(
+ preparation.statements.iter().any(|statement| statement.contains(&format!("WHERE {predicate}"))),
+ "no statement carries the guarded predicate {predicate:?}"
+ );
+ }
+ for statement in &preparation.statements {
+ let Some((_, predicate)) = statement.split_once(" WHERE ") else {
+ continue;
+ };
+ let predicate = predicate.trim_end_matches(';');
+ assert!(
+ preparation.keyless_guards.iter().any(|guard| guard.sql.ends_with(&format!("WHERE ({predicate})"))),
+ "predicate {predicate:?} is sent to the database without a guard"
+ );
+ }
+ }
+
+ #[test]
+ fn guards_sqlite_keyless_update_with_a_server_side_row_count() {
+ // Regression test for https://github.com/t8y2/dbx/issues/8321: a SQLite
+ // table with no primary key, two rows inserted with only `stat_date`
+ // filled in. Editing row 0's `period` must not silently also rewrite
+ // row 1, which has identical values in every column. Whether a second
+ // matching row exists cannot be answered from the loaded page, so the
+ // save carries a guard that counts the matches on the server.
+ let result = prepare_data_grid_save(daily_stats_keyless_options());
+
+ assert_eq!(result.validation_error, None);
+ assert_eq!(
+ result.statements,
+ vec![
+ r#"UPDATE "daily_stats" SET "period" = '早上' WHERE "stat_date" = '2026-09-07' AND "period" IS NULL;"#
+ ]
+ );
+ assert_eq!(
+ result.keyless_guards,
+ vec![DataGridSaveGuard {
+ sql: r#"SELECT COUNT(*) AS dbx_keyless_row_matches FROM "daily_stats" WHERE ("stat_date" = '2026-09-07' AND "period" IS NULL)"#
+ .to_string(),
+ max_matched_rows: 1,
+ message: KEYLESS_AMBIGUOUS_ROW_ERROR.to_string(),
+ }]
+ );
+ assert_guards_cover_statement_predicates(&result);
+ }
+
+ #[test]
+ fn guards_sqlite_keyless_update_even_when_the_loaded_page_looks_unique() {
+ // The duplicate row may live outside the loaded/filtered page, so a
+ // page that shows only distinguishable rows proves nothing and must
+ // still be verified on the server.
+ let mut options = daily_stats_keyless_options();
+ options.rows = vec![vec![json!("2026-09-07"), json!("早上")], vec![json!("2026-09-07"), json!("中午")]];
+ options.dirty_rows = vec![(0, vec![(1, json!("上午"))])];
+ let result = prepare_data_grid_save(options);
+
+ assert_eq!(result.validation_error, None);
+ assert_eq!(
+ result.statements,
+ vec![
+ r#"UPDATE "daily_stats" SET "period" = '上午' WHERE "stat_date" = '2026-09-07' AND "period" = '早上';"#
+ ]
+ );
+ assert_eq!(result.keyless_guards.len(), 1);
+ assert_guards_cover_statement_predicates(&result);
+ }
+
+ #[test]
+ fn guards_keyless_predicate_without_the_columns_the_predicate_omits() {
+ // `build_row_where` drops result columns that have no source column, so
+ // a guard built from the visible values would decide uniqueness using
+ // `total`, a value the mutation predicate never mentions.
+ let mut options = daily_stats_keyless_options();
+ options.table_meta.columns =
+ Some(vec![column("stat_date", "TEXT", false, None), column("period", "TEXT", true, None)]);
+ options.columns = vec!["stat_date".to_string(), "period".to_string(), "total".to_string()];
+ options.source_columns = Some(vec![Some("stat_date".to_string()), Some("period".to_string()), None]);
+ options.rows =
+ vec![vec![json!("2026-09-07"), Value::Null, json!(1)], vec![json!("2026-09-07"), Value::Null, json!(2)]];
+ let result = prepare_data_grid_save(options);
+
+ assert_eq!(result.validation_error, None);
+ assert_eq!(result.keyless_guards.len(), 1);
+ assert!(!result.keyless_guards[0].sql.contains("total"));
+ assert_guards_cover_statement_predicates(&result);
+ }
+
+ #[test]
+ fn guards_keyless_delete_and_deduplicates_identical_predicates() {
+ let mut options = daily_stats_keyless_options();
+ options.dirty_rows = vec![];
+ options.deleted_rows = vec![0, 1];
+ let result = prepare_data_grid_save(options);
+
+ assert_eq!(result.validation_error, None);
+ assert_eq!(result.statements.len(), 2);
+ // Both rows produce the same predicate; one guard covers both.
+ assert_eq!(result.keyless_guards.len(), 1);
+ assert_guards_cover_statement_predicates(&result);
+ }
+
+ #[test]
+ fn omits_keyless_guards_when_the_table_has_a_primary_key() {
+ let mut options = daily_stats_keyless_options();
+ options.table_meta.primary_keys = vec!["stat_date".to_string()];
+ let result = prepare_data_grid_save(options);
+
+ assert_eq!(result.validation_error, None);
+ assert!(result.keyless_guards.is_empty());
+ }
+
+ #[test]
+ fn rejects_keyless_edit_when_no_column_can_address_the_row() {
+ // Every result column is computed, so `build_row_where` produces an
+ // empty predicate: there is neither a row identifier nor anything a
+ // server-side count could check, and the write must stay disabled.
+ let mut options = daily_stats_keyless_options();
+ options.source_columns = Some(vec![None, None]);
+ let result = prepare_data_grid_save(options);
+
+ assert_eq!(result.validation_error.as_deref(), Some(KEYLESS_UNIDENTIFIABLE_ROW_ERROR));
+ assert!(result.statements.is_empty());
+ assert!(result.keyless_guards.is_empty());
+ }
+
#[test]
fn preserves_oceanbase_oracle_keyless_predicates_for_comparable_columns() {
let result = prepare_data_grid_save(DataGridSaveStatementOptions {