From 48c30c423fa8f73dee19d534a93e0b214242ae1d Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 10 Aug 2026 11:34:22 +0800 Subject: [PATCH 1/6] fix(database): isolate workspace state and improve execution feedback --- .../Application/DatabaseFeatureModel.swift | 456 ++++++++++++++---- .../Application/DatabaseSQLSupport.swift | 8 +- .../Services/DatabaseRecoveryStore.swift | 53 ++ .../Services/DatabaseSidecarService.swift | 18 + .../Views/DatabaseSQLWorkspaceView.swift | 80 ++- Sources/Lithe/Views/DatabaseSidebarView.swift | 6 +- .../DatabaseSpecializedWorkspaceViews.swift | 36 ++ Sources/Lithe/Views/DatabaseTableView.swift | 30 +- Tests/LitheTests/LitheCoreLogicTests.swift | 71 +++ rust/lithe-db-sidecar/src/main.rs | 61 ++- 10 files changed, 691 insertions(+), 128 deletions(-) diff --git a/Sources/Lithe/Application/DatabaseFeatureModel.swift b/Sources/Lithe/Application/DatabaseFeatureModel.swift index 5b360524d4..fb8e283e88 100644 --- a/Sources/Lithe/Application/DatabaseFeatureModel.swift +++ b/Sources/Lithe/Application/DatabaseFeatureModel.swift @@ -39,6 +39,7 @@ final class DatabaseFeatureModel: ObservableObject { @Published private(set) var lastDiagnostics: DatabaseQueryResult? @Published private(set) var recoveryPoints: [DatabaseRecoveryPoint] @Published private(set) var auditEntries: [DatabaseAuditEntry] + @Published private(set) var executionEvents: [DatabaseExecutionEvent] @Published private(set) var backupSchedules: [DatabaseBackupSchedule] @Published private(set) var sqlTabs: [DatabaseSQLTab] @Published var selectedSQLTabID: UUID? @@ -62,6 +63,8 @@ final class DatabaseFeatureModel: ObservableObject { private let connectionStore: DatabaseConnectionStore private let recoveryStore: DatabaseRecoveryStore private var backupTimer: Timer? + private var profileGeneration: UInt64 = 0 + private var tableRequestID: UUID? // Keep the unmasked page separate so primary-key mutations and exports never // accidentally persist the display placeholder. private var sourceRows: [DatabaseRow] = [] @@ -78,6 +81,7 @@ final class DatabaseFeatureModel: ObservableObject { sqlHistory = connectionStore.loadSQLHistory() recoveryPoints = recoveryStore.recoveryPoints() auditEntries = recoveryStore.auditEntries() + executionEvents = recoveryStore.executionEvents() backupSchedules = connectionStore.loadBackupSchedules() migrateLegacyGroupsIfNeeded() refreshBackupTimer() @@ -98,6 +102,7 @@ final class DatabaseFeatureModel: ObservableObject { } private func save(_ profile: DatabaseProfile, password: String?) async -> Bool { + let generation = profileGeneration isLoading = true; errorMessage = nil setConnectionStatus(.connecting, for: profile.id) do { @@ -123,18 +128,21 @@ final class DatabaseFeatureModel: ObservableObject { throw error } profiles = sortedProfiles(updated) - selectedProfileID = profile.id - isLoading = false + setConnectionStatus(.connected, for: profile.id) + guard profileGeneration == generation else { return true } + activateProfile(profile) if profile.kind.supportsDataGrid { await refreshTables() } else { - setConnectionStatus(.connected, for: profile.id) + isLoading = false } return true } catch { - errorMessage = error.localizedDescription setConnectionStatus(.failed, for: profile.id) - isLoading = false + if profileGeneration == generation { + errorMessage = executionError(error) + isLoading = false + } return false } } @@ -142,15 +150,15 @@ final class DatabaseFeatureModel: ObservableObject { func remove(_ profile: DatabaseProfile) { do { let updated = profiles.filter { $0.id != profile.id } - try connectionStore.save(updated); try connectionStore.deletePassword(for: profile.id); try connectionStore.deleteSQLHistory(for: profile.id); try connectionStore.deleteBackupSchedule(for: profile.id) + try connectionStore.save(updated); try connectionStore.deletePassword(for: profile.id); try connectionStore.deleteSQLHistory(for: profile.id); try connectionStore.deleteBackupSchedule(for: profile.id); try recoveryStore.deleteExecutionEvents(for: profile.id) profiles = updated connectionStatuses.removeValue(forKey: profile.id) sqlHistory.removeAll { $0.profileID == profile.id } + executionEvents.removeAll { $0.profileID == profile.id } backupSchedules.removeAll { $0.profileID == profile.id } refreshBackupTimer() if selectedProfileID == profile.id { - selectedProfileID = nil; tables = []; selectedTable = nil; openTableTabs = []; rows = []; sourceRows = []; indexes = []; foreignKeys = []; objects = [:]; lastExplainResult = nil; lastDiagnostics = nil - clearSpecializedWorkspace() + clearProfileScopedState() } } catch { errorMessage = error.localizedDescription } } @@ -298,9 +306,7 @@ final class DatabaseFeatureModel: ObservableObject { func disconnect(_ profile: DatabaseProfile) { setConnectionStatus(.idle, for: profile.id) if selectedProfileID == profile.id { - selectedProfileID = nil - tables = []; selectedTable = nil; openTableTabs = []; rows = []; sourceRows = []; columns = []; indexes = []; foreignKeys = []; objects = [:] - clearSpecializedWorkspace() + clearProfileScopedState() } } @@ -333,13 +339,12 @@ final class DatabaseFeatureModel: ObservableObject { } func select(_ profile: DatabaseProfile) async { - if selectedProfileID != profile.id { openTableTabs = [] } - setConnectionStatus(.connecting, for: profile.id) - selectedProfileID = profile.id; selectedTable = nil; rows = []; sourceRows = []; columns = []; indexes = []; foreignKeys = []; objects = [:]; lastExplainResult = nil; lastDiagnostics = nil - clearSQLResults() - clearSpecializedWorkspace() + activateProfile(profile) if profile.kind.supportsDataGrid { await refreshTables() + } else { + setConnectionStatus(.connected, for: profile.id) + isLoading = false } } @@ -349,26 +354,31 @@ final class DatabaseFeatureModel: ObservableObject { tables = [] return } + let generation = profileGeneration isLoading = true; errorMessage = nil + tables = []; objects = [:] setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) let result = try await Task.detached { [operations] in try operations.listTables(connection: connection, schema: "") }.value + guard isCurrent(profileID: profile.id, generation: generation) else { return } setConnectionStatus(.connected, for: profile.id) - guard selectedProfileID == profile.id else { isLoading = false; return } tables = result.compactMap { row in row["table_name"]?.text ?? row["TABLE_NAME"]?.text ?? row["name"]?.text } - if profile.kind.isSQLDatabase { await refreshObjects() } + if profile.kind.isSQLDatabase { await refreshObjects(profileID: profile.id, generation: generation) } } catch { - errorMessage = error.localizedDescription + guard isCurrent(profileID: profile.id, generation: generation) else { return } + tables = []; objects = [:] + errorMessage = executionError(error) setConnectionStatus(.failed, for: profile.id) } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } - func refreshObjects() async { - guard let profile = selectedProfile else { return } + private func refreshObjects(profileID: UUID, generation: UInt64) async { + guard isCurrent(profileID: profileID, generation: generation), + let profile = profiles.first(where: { $0.id == profileID }) else { return } let connection = connection(profile) do { let loaded = try await withThrowingTaskGroup(of: (DatabaseObjectKind, [DatabaseRow]).self) { group in @@ -381,9 +391,13 @@ final class DatabaseFeatureModel: ObservableObject { for try await (kind, rows) in group { result[kind] = rows } return result } + guard isCurrent(profileID: profileID, generation: generation) else { return } objects = loaded } catch { - errorMessage = error.localizedDescription + if isCurrent(profileID: profileID, generation: generation) { + objects = [:] + errorMessage = executionError(error) + } } } @@ -392,8 +406,12 @@ final class DatabaseFeatureModel: ObservableObject { errorMessage = "The selected database connection no longer exists." return nil } - isLoading = true - errorMessage = nil + let generation = profileGeneration + let tracksUI = selectedProfileID == profileID + if tracksUI { + isLoading = true + errorMessage = nil + } do { let connection = connection(profile) let tableRows = try await Task.detached { [operations] in @@ -445,11 +463,14 @@ final class DatabaseFeatureModel: ObservableObject { for try await table in group { snapshots.append(table) } return snapshots.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } } - isLoading = false + if tracksUI && !isCurrent(profileID: profileID, generation: generation) { return nil } + if tracksUI { isLoading = false } return DatabaseSchemaSnapshot(profileID: profile.id, profileName: profile.name, kind: profile.kind, schema: "", tables: tables) } catch { - errorMessage = error.localizedDescription - isLoading = false + if tracksUI && isCurrent(profileID: profileID, generation: generation) { + errorMessage = executionError(error) + isLoading = false + } return nil } } @@ -476,8 +497,12 @@ final class DatabaseFeatureModel: ObservableObject { errorMessage = "This migration contains a review-only SQL step and cannot be applied automatically." return false } - isLoading = true - errorMessage = nil + let generation = profileGeneration + let tracksUI = selectedProfileID == targetProfileID + if tracksUI { + isLoading = true + errorMessage = nil + } do { let recoveryPoint = try await createRecoveryPoint(profile: profile, reason: "Before schema migration") let connection = connection(profile) @@ -489,22 +514,26 @@ final class DatabaseFeatureModel: ObservableObject { } } appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "schemaMigration", summary: "Applied schema migration from \(diff.source.profileName)", createdAt: Date(), recoveryPointID: recoveryPoint.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) - if selectedProfileID == targetProfileID { + if tracksUI && isCurrent(profileID: targetProfileID, generation: generation) { await refreshTables() if let table = selectedTable { await openTable(table) } + isLoading = false } - isLoading = false return true } catch { - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "schemaMigration", summary: "Schema migration failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - errorMessage = error.localizedDescription - isLoading = false + let sanitizedError = executionError(error) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "schemaMigration", summary: "Schema migration failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if tracksUI && isCurrent(profileID: targetProfileID, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } return false } } func applySchemaChange(_ change: DatabaseSchemaChange, confirmed: Bool = false) async -> Bool { guard let profile = selectedProfile else { errorMessage = "Select a database connection first."; return false } + let generation = profileGeneration isLoading = true; errorMessage = nil do { let connection = connection(profile) @@ -513,51 +542,66 @@ final class DatabaseFeatureModel: ObservableObject { try operations.applySchemaChange(connection: connection, schema: "", change: change, confirmed: confirmed, allowWrite: false) }.value appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "schemaChange", summary: "Applied \(change.operation)", createdAt: Date(), recoveryPointID: recoveryPoint.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return true } await refreshTables() if let table = selectedTable { await openTable(table) } return true } catch { - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "schemaChange", summary: "Schema change failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - errorMessage = error.localizedDescription - isLoading = false + let sanitizedError = executionError(error) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "schemaChange", summary: "Schema change failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } return false } } func explainSQL(_ sql: String, format: String = "json") async -> DatabaseQueryResult? { guard let profile = selectedProfile else { errorMessage = "Select a database connection first."; return nil } + let generation = profileGeneration do { let connection = connection(profile) let result = try await Task.detached { [operations] in try operations.explain(connection: connection, sql: sql, format: format) }.value + guard isCurrent(profileID: profile.id, generation: generation) else { return nil } let displayResult = masked(result) lastExplainResult = displayResult return displayResult } catch { - errorMessage = error.localizedDescription + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = executionError(error) + } return nil } } func loadDiagnostics(_ request: DatabaseDiagnosticsRequest) async -> DatabaseQueryResult? { guard let profile = selectedProfile else { errorMessage = "Select a database connection first."; return nil } + let generation = profileGeneration do { let connection = connection(profile) let result = try await Task.detached { [operations] in try operations.diagnostics(connection: connection, request: request) }.value + guard isCurrent(profileID: profile.id, generation: generation) else { return nil } let displayResult = masked(result) lastDiagnostics = displayResult return displayResult } catch { - errorMessage = error.localizedDescription + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = executionError(error) + } return nil } } func openTable(_ table: String) async { guard let profile = selectedProfile else { return } + let generation = profileGeneration + let requestID = UUID() + tableRequestID = requestID if !openTableTabs.contains(table) { openTableTabs.append(table) } selectedTable = table; isLoading = true; errorMessage = nil do { @@ -567,6 +611,9 @@ final class DatabaseFeatureModel: ObservableObject { async let tableIndexes = Task.detached { [operations] in try operations.listIndexes(connection: connection, schema: "", table: table) }.value async let tableForeignKeys = Task.detached { [operations] in try operations.listForeignKeys(connection: connection, schema: "", table: table) }.value let (description, result, loadedIndexes, loadedForeignKeys) = try await (metadata, page, tableIndexes, tableForeignKeys) + guard isCurrent(profileID: profile.id, generation: generation), + selectedTable == table, + tableRequestID == requestID else { return } columns = description.compactMap { $0["column_name"]?.text ?? $0["COLUMN_NAME"]?.text ?? $0["name"]?.text } columnTypes = Dictionary(uniqueKeysWithValues: description.compactMap { row in guard let name = row["column_name"]?.text ?? row["COLUMN_NAME"]?.text ?? row["name"]?.text else { return nil } @@ -585,8 +632,13 @@ final class DatabaseFeatureModel: ObservableObject { totalRows = result.totalRows ?? Int64(result.rows.count) indexes = loadedIndexes; foreignKeys = loadedForeignKeys currentOffset = 0 - } catch { errorMessage = error.localizedDescription } - isLoading = false + } catch { + if isCurrent(profileID: profile.id, generation: generation), selectedTable == table, tableRequestID == requestID { + errorMessage = executionError(error) + rows = []; sourceRows = []; columns = []; columnTypes = [:]; indexes = []; foreignKeys = []; totalRows = 0 + } + } + if isCurrent(profileID: profile.id, generation: generation), tableRequestID == requestID { isLoading = false } } @discardableResult @@ -603,21 +655,30 @@ final class DatabaseFeatureModel: ObservableObject { func loadPage(filters: [DatabaseFilter], sort: [DatabaseSort], offset: Int) async { guard let profile = selectedProfile, let table = selectedTable else { return } + let generation = profileGeneration + let requestID = UUID() + tableRequestID = requestID isLoading = true; errorMessage = nil do { let connection = connection(profile) let result = try await Task.detached { [operations, pageSize] in try operations.pageTable(connection: connection, schema: "", table: table, limit: pageSize, offset: max(0, offset), filters: filters, sort: sort) }.value + guard isCurrent(profileID: profile.id, generation: generation), selectedTable == table, tableRequestID == requestID else { return } sourceRows = result.rows rows = masked(result.rows) totalRows = result.totalRows ?? Int64(result.rows.count); currentOffset = max(0, offset) - } catch { errorMessage = error.localizedDescription } - isLoading = false + } catch { + if isCurrent(profileID: profile.id, generation: generation), selectedTable == table, tableRequestID == requestID { + errorMessage = executionError(error) + } + } + if isCurrent(profileID: profile.id, generation: generation), tableRequestID == requestID { isLoading = false } } func apply(drafts: [DatabaseCellDraft], insertedRows: [DatabaseRow], deletedIndexes: Set, confirmed: Bool = false) async -> Bool { guard let profile = selectedProfile, let table = selectedTable else { return false } + let generation = profileGeneration var changesByRow: [Int: DatabaseRow] = [:] for draft in drafts { changesByRow[draft.rowIndex, default: [:]][draft.column] = typedValue(draft.value, for: draft.column) } var mutations = insertedRows.map { row in @@ -637,21 +698,29 @@ final class DatabaseFeatureModel: ObservableObject { let recoveryPoint = profile.kind == .mongodb ? nil : try await createRecoveryPoint(profile: profile, reason: "Before table edit") _ = try await Task.detached { [operations] in try operations.applyChanges(connection: connection, schema: "", mutations: mutations, confirmed: confirmed, allowWrite: false) }.value appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "tableEdit", summary: "Applied table cell changes", createdAt: Date(), recoveryPointID: recoveryPoint?.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return true } await openTable(table); return true } catch { - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "tableEdit", summary: "Table cell changes failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - errorMessage = error.localizedDescription; isLoading = false; return false + let sanitizedError = executionError(error) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "tableEdit", summary: "Table cell changes failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } + return false } } func exportData(format: DatabaseTransferFormat) async -> Data? { guard let profile = selectedProfile else { return nil } let connection = connection(profile) + let table = selectedTable + let generation = profileGeneration do { - let data = try await Task.detached { [operations, selectedTable] in + let data = try await Task.detached { [operations, table] in switch format { case .csv, .json: - guard let table = selectedTable else { throw DatabaseTransferError.tableRequired } + guard let table else { throw DatabaseTransferError.tableRequired } let sql = "SELECT * FROM \(Self.quotedIdentifier(table, for: connection.kind))" return format == .csv ? try operations.exportCSV(connection: connection, sql: sql, values: [], limit: 100_000) @@ -661,11 +730,17 @@ final class DatabaseFeatureModel: ObservableObject { } }.value return data - } catch { errorMessage = error.localizedDescription; return nil } + } catch { + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = executionError(error) + } + return nil + } } func exportDataFile(format: DatabaseTransferFormat) async -> URL? { guard format == .sql, let profile = selectedProfile else { return nil } + let generation = profileGeneration let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-database-\(UUID().uuidString).sql") do { let connection = connection(profile) @@ -682,40 +757,52 @@ final class DatabaseFeatureModel: ObservableObject { return outputURL } catch { try? FileManager.default.removeItem(at: outputURL) - errorMessage = error.localizedDescription + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = executionError(error) + } return nil } } func importData(_ data: Data, format: DatabaseTransferFormat, confirmed: Bool = false) async -> Bool { guard let profile = selectedProfile else { return false } + let generation = profileGeneration + let table = selectedTable isLoading = true; errorMessage = nil do { let connection = connection(profile) let recoveryPoint = try await createRecoveryPoint(profile: profile, reason: "Before import") - _ = try await Task.detached { [operations, selectedTable] in + _ = try await Task.detached { [operations, table] in switch format { case .csv: - guard let table = selectedTable else { throw DatabaseTransferError.tableRequired } + guard let table else { throw DatabaseTransferError.tableRequired } return try operations.importCSV(connection: connection, schema: "", table: table, data: data) case .json: - guard let table = selectedTable else { throw DatabaseTransferError.tableRequired } + guard let table else { throw DatabaseTransferError.tableRequired } return try operations.importJSON(connection: connection, schema: "", table: table, data: data) case .sql: return try operations.restoreSQL(connection: connection, data: data, confirmed: confirmed, allowWrite: false) } }.value appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "import", summary: "Imported \(format.rawValue) data", createdAt: Date(), recoveryPointID: recoveryPoint.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) - if let table = selectedTable { await openTable(table) } else { await refreshTables() } + guard isCurrent(profileID: profile.id, generation: generation) else { return true } + if let table { await openTable(table) } else { await refreshTables() } return true } catch { - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "import", summary: "Import failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - errorMessage = error.localizedDescription; isLoading = false; return false + let sanitizedError = executionError(error) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "import", summary: "Import failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } + return false } } func importDataFile(_ fileURL: URL, format: DatabaseTransferFormat, confirmed: Bool = false) async -> Bool { guard format == .sql, let profile = selectedProfile else { return false } + let generation = profileGeneration + let table = selectedTable isLoading = true errorMessage = nil do { @@ -725,12 +812,16 @@ final class DatabaseFeatureModel: ObservableObject { try operations.restoreSQLFile(connection: connection, fileURL: fileURL, confirmed: confirmed, allowWrite: false) }.value appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "import", summary: "Imported SQL backup", createdAt: Date(), recoveryPointID: recoveryPoint.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) - if let table = selectedTable { await openTable(table) } else { await refreshTables() } + guard isCurrent(profileID: profile.id, generation: generation) else { return true } + if let table { await openTable(table) } else { await refreshTables() } return true } catch { - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "import", summary: "SQL import failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - errorMessage = error.localizedDescription - isLoading = false + let sanitizedError = executionError(error) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "import", summary: "SQL import failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } return false } } @@ -807,26 +898,30 @@ final class DatabaseFeatureModel: ObservableObject { let sql = tab.sql.trimmingCharacters(in: .whitespacesAndNewlines) let connection = connection(profile) + let generation = profileGeneration let startedAt = Date() updateSQLTab(tabID) { tab in - tab.isRunning = true; tab.errorMessage = nil; tab.result = nil; tab.resultColumns = []; tab.rowsAffected = nil + tab.isRunning = true; tab.errorMessage = nil; tab.result = nil; tab.resultColumns = []; tab.rowsAffected = nil; tab.execution = nil } do { let recoveryPoint: DatabaseRecoveryPoint? = analysis.kind.usesQueryEndpoint ? nil : try await createRecoveryPoint(profile: profile, reason: "Before SQL execution") + guard isCurrent(profileID: profile.id, generation: generation) else { return } if analysis.kind.usesQueryEndpoint { let result = try await Task.detached { [operations] in try operations.query(connection: connection, sql: sql, values: [], limit: 10_000) }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) - let columns = result.rows.reduce(into: [String]()) { result, row in + let columns = result.columns ?? result.rows.reduce(into: [String]()) { result, row in for key in row.keys where !result.contains(key) { result.append(key) } - }.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending } + } let execution = DatabaseSQLExecution(startedAt: startedAt, durationMilliseconds: duration, rowsReturned: result.rows.count, rowsAffected: nil, truncated: result.truncated) + guard isCurrent(profileID: profile.id, generation: generation) else { return } updateSQLTab(tabID) { tab in tab.result = masked(result); tab.resultColumns = columns; tab.execution = execution; tab.isRunning = false } recordSQLHistory(profileID: profile.id, sql: sql, analysis: analysis, execution: execution) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: analysis.kind.rawValue, startedAt: startedAt, durationMilliseconds: execution.durationMilliseconds, status: .succeeded, rowsReturned: execution.rowsReturned, rowsAffected: execution.rowsAffected, errorMessage: nil)) if let recoveryPoint { appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "Executed \(analysis.kind.rawValue) statement", createdAt: startedAt, recoveryPointID: recoveryPoint.id, rowsAffected: execution.rowsAffected, succeeded: true, errorMessage: nil)) } } else { let result = try await Task.detached { [operations] in @@ -834,23 +929,30 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) let execution = DatabaseSQLExecution(startedAt: startedAt, durationMilliseconds: duration, rowsReturned: nil, rowsAffected: result.rowsAffected, truncated: false) + guard isCurrent(profileID: profile.id, generation: generation) else { return } updateSQLTab(tabID) { tab in tab.rowsAffected = result.rowsAffected; tab.execution = execution; tab.isRunning = false } recordSQLHistory(profileID: profile.id, sql: sql, analysis: analysis, execution: execution) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: analysis.kind.rawValue, startedAt: startedAt, durationMilliseconds: execution.durationMilliseconds, status: .succeeded, rowsReturned: execution.rowsReturned, rowsAffected: execution.rowsAffected, errorMessage: nil)) appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "Executed \(analysis.kind.rawValue) statement", createdAt: startedAt, recoveryPointID: recoveryPoint?.id, rowsAffected: execution.rowsAffected, succeeded: true, errorMessage: nil)) await refreshTables() } } catch { - if let profile = selectedProfile { appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "SQL execution failed", createdAt: startedAt, recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) } + guard isCurrent(profileID: profile.id, generation: generation) else { return } + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: analysis.kind.rawValue, startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "SQL execution failed", createdAt: startedAt, recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) updateSQLTab(tabID) { tab in - tab.isRunning = false; tab.errorMessage = error.localizedDescription + tab.isRunning = false; tab.errorMessage = sanitizedError; tab.execution = nil; tab.rowsAffected = nil; tab.result = nil; tab.resultColumns = [] } } } func rollback(to point: DatabaseRecoveryPoint) async -> Bool { guard let profile = selectedProfile, profile.id == point.profileID else { errorMessage = "Select the connection that owns this recovery point."; return false } + let generation = profileGeneration isLoading = true; errorMessage = nil do { let connection = connection(profile) @@ -862,13 +964,16 @@ final class DatabaseFeatureModel: ObservableObject { _ = try await Task.detached { [operations] in try operations.restoreSQLFile(connection: connection, fileURL: fileURL, confirmed: true, allowWrite: false) }.value } appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "rollback", summary: "Restored recovery point", createdAt: Date(), recoveryPointID: point.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return true } await refreshTables() if let table = selectedTable { await openTable(table) } isLoading = false return true } catch { - errorMessage = error.localizedDescription - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = executionError(error) + isLoading = false + } return false } } @@ -884,14 +989,18 @@ final class DatabaseFeatureModel: ObservableObject { func createBackup(profileID: UUID, reason: String = "Manual backup") async -> Bool { guard let profile = profiles.first(where: { $0.id == profileID }) else { errorMessage = "The backup connection no longer exists."; return false } + let generation = profileGeneration do { let point = try await createRecoveryPoint(profile: profile, reason: reason) pruneRecoveryPoints(for: profile.id) appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "backup", summary: reason, createdAt: Date(), recoveryPointID: point.id, rowsAffected: nil, succeeded: true, errorMessage: nil)) return true } catch { - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "backup", summary: "Backup failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "backup", summary: "Backup failed", createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profileID, generation: generation) { + errorMessage = sanitizedError + } return false } } @@ -942,8 +1051,10 @@ final class DatabaseFeatureModel: ObservableObject { func loadRedisKeys(pattern: String, reset: Bool = true) async { guard let profile = selectedProfile, profile.kind == .redis else { return } + let generation = profileGeneration let cursor = reset ? "0" : redisNextCursor if !reset && cursor == "0" { return } + let startedAt = Date() isLoading = true errorMessage = nil setConnectionStatus(.connecting, for: profile.id) @@ -952,19 +1063,27 @@ final class DatabaseFeatureModel: ObservableObject { let result = try await Task.detached { [operations] in try operations.redisScan(connection: connection, cursor: cursor, pattern: pattern.isEmpty ? "*" : pattern, count: 100) }.value + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "SCAN", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.keys.count, rowsAffected: nil, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } setConnectionStatus(.connected, for: profile.id) - guard selectedProfileID == profile.id else { isLoading = false; return } redisKeys = reset ? result.keys : Array(Dictionary(grouping: redisKeys + result.keys, by: \.key).compactMap { $0.value.first }) redisNextCursor = result.nextCursor } catch { - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "SCAN", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } func loadRedisKey(_ key: String) async { guard let profile = selectedProfile, profile.kind == .redis else { return } + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil do { @@ -972,13 +1091,19 @@ final class DatabaseFeatureModel: ObservableObject { let detail = try await Task.detached { [operations] in try operations.redisGetKey(connection: connection, key: key) }.value - guard selectedProfileID == profile.id else { isLoading = false; return } + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "GET \(key)", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: 1, rowsAffected: nil, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } redisSelectedKey = detail } catch { - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "GET \(key)", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } func saveRedisString(key: String, value: String, ttl: Int64?, confirmed: Bool) async -> Bool { @@ -1039,19 +1164,29 @@ final class DatabaseFeatureModel: ObservableObject { afterSuccess: @escaping @MainActor () async -> Void ) async -> Bool { guard let profile = selectedProfile, profile.kind == .redis else { return false } + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil do { let activeConnection = connection(profile) try await Task.detached { [operations] in try operation(activeConnection, operations) }.value + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: nil, rowsAffected: nil, errorMessage: nil)) appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "redis", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: true, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return true } await afterSuccess() isLoading = false return true } catch { - errorMessage = error.localizedDescription - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "redis", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - isLoading = false + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "redis", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } return false } } @@ -1060,6 +1195,8 @@ final class DatabaseFeatureModel: ObservableObject { func loadNacosConfigs(dataId: String, group: String, page: Int = 1) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil setConnectionStatus(.connecting, for: profile.id) @@ -1068,19 +1205,27 @@ final class DatabaseFeatureModel: ObservableObject { let result = try await Task.detached { [operations] in try operations.nacosListConfigs(connection: connection, dataId: dataId, group: group, page: page, pageSize: 100) }.value + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST CONFIGS", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.items.count, rowsAffected: nil, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } setConnectionStatus(.connected, for: profile.id) - guard selectedProfileID == profile.id else { isLoading = false; return } nacosConfigs = result.items nacosConfigTotalCount = result.totalCount } catch { - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST CONFIGS", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } func loadNacosConfig(dataId: String, group: String) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil do { @@ -1088,13 +1233,19 @@ final class DatabaseFeatureModel: ObservableObject { let detail = try await Task.detached { [operations] in try operations.nacosGetConfig(connection: connection, dataId: dataId, group: group) }.value - guard selectedProfileID == profile.id else { return } + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "GET CONFIG \(group)/\(dataId)", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: 1, rowsAffected: nil, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } nacosSelectedConfig = detail } catch { - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "GET CONFIG \(group)/\(dataId)", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } func publishNacosConfig(dataId: String, group: String, content: String, type: String?, confirmed: Bool) async -> Bool { @@ -1120,6 +1271,8 @@ final class DatabaseFeatureModel: ObservableObject { func loadNacosServices(serviceName: String, group: String, page: Int = 1) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil setConnectionStatus(.connecting, for: profile.id) @@ -1128,19 +1281,27 @@ final class DatabaseFeatureModel: ObservableObject { let result = try await Task.detached { [operations] in try operations.nacosListServices(connection: connection, serviceName: serviceName, group: group, page: page, pageSize: 100) }.value + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST SERVICES", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.items.count, rowsAffected: nil, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } setConnectionStatus(.connected, for: profile.id) - guard selectedProfileID == profile.id else { isLoading = false; return } nacosServices = result.items nacosServiceTotalCount = result.totalCount } catch { - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST SERVICES", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } func loadNacosInstances(serviceName: String, group: String) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil do { @@ -1148,12 +1309,18 @@ final class DatabaseFeatureModel: ObservableObject { let items = try await Task.detached { [operations] in try operations.nacosListInstances(connection: connection, serviceName: serviceName, group: group) }.value - guard selectedProfileID == profile.id else { return } + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST INSTANCES", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: items.count, rowsAffected: nil, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } nacosInstances = items } catch { - errorMessage = error.localizedDescription + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST INSTANCES", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + errorMessage = sanitizedError } - isLoading = false + if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } private func performNacosWrite( @@ -1162,19 +1329,29 @@ final class DatabaseFeatureModel: ObservableObject { operation: @escaping @Sendable (DatabaseConnection, any DatabaseOperations) throws -> Void, afterSuccess: @escaping @MainActor () async -> Void ) async -> Bool { + let generation = profileGeneration + let startedAt = Date() isLoading = true errorMessage = nil do { let activeConnection = connection(profile) try await Task.detached { [operations] in try operation(activeConnection, operations) }.value + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: nil, rowsAffected: nil, errorMessage: nil)) appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "nacos", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: true, errorMessage: nil)) + guard isCurrent(profileID: profile.id, generation: generation) else { return true } await afterSuccess() isLoading = false return true } catch { - errorMessage = error.localizedDescription - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "nacos", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: error.localizedDescription)) - isLoading = false + let sanitizedError = executionError(error) + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "nacos", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + if isCurrent(profileID: profile.id, generation: generation) { + errorMessage = sanitizedError + isLoading = false + } return false } } @@ -1234,11 +1411,13 @@ final class DatabaseFeatureModel: ObservableObject { private func createRecoveryPoint(profile: DatabaseProfile, reason: String) async throws -> DatabaseRecoveryPoint { let connection = connection(profile) + let generation = profileGeneration + let tracksUI = selectedProfileID == profile.id let temporaryURL = FileManager.default.temporaryDirectory.appendingPathComponent("lithe-recovery-\(UUID().uuidString).sql") - backupProgress = 0 + if tracksUI { backupProgress = 0 } defer { try? FileManager.default.removeItem(at: temporaryURL) - backupProgress = nil + if tracksUI && isCurrent(profileID: profile.id, generation: generation) { backupProgress = nil } } let export = try await Task.detached { [operations] in try operations.exportSQLToFile( @@ -1247,9 +1426,10 @@ final class DatabaseFeatureModel: ObservableObject { outputURL: temporaryURL ) }.value - backupProgress = 0.7 + if tracksUI && isCurrent(profileID: profile.id, generation: generation) { backupProgress = 0.7 } let point = try recoveryStore.createRecoveryPoint(profileID: profile.id, reason: reason, fileURL: temporaryURL, expectedSHA256: export.sha256) { [weak self] progress in - self?.backupProgress = 0.7 + progress * 0.3 + guard let self, tracksUI, self.isCurrent(profileID: profile.id, generation: generation) else { return } + self.backupProgress = 0.7 + progress * 0.3 } recoveryPoints = recoveryStore.recoveryPoints() return point @@ -1265,6 +1445,86 @@ final class DatabaseFeatureModel: ObservableObject { } } + private func appendExecutionEvent(_ event: DatabaseExecutionEvent) { + do { + try recoveryStore.appendExecutionEvent(event) + executionEvents = recoveryStore.executionEvents() + } catch { + // Execution logging must never change the result of a database operation. + } + } + + private func executionError(_ error: Error) -> String { + let message = error.localizedDescription + .replacingOccurrences(of: "\n", with: " ") + .trimmingCharacters(in: .whitespacesAndNewlines) + return message.count > 500 ? "\(message.prefix(497))..." : message + } + + private func activateProfile(_ profile: DatabaseProfile) { + profileGeneration &+= 1 + tableRequestID = nil + selectedProfileID = profile.id + selectedTable = nil + openTableTabs = [] + columns = [] + columnTypes = [:] + rows = [] + sourceRows = [] + totalRows = 0 + currentOffset = 0 + primaryKeyColumns = [] + indexes = [] + foreignKeys = [] + tables = [] + objects = [:] + lastExplainResult = nil + lastDiagnostics = nil + backupProgress = nil + clearSQLResults() + resetSQLWorkspace() + clearSpecializedWorkspace() + errorMessage = nil + isLoading = true + setConnectionStatus(.connecting, for: profile.id) + } + + private func clearProfileScopedState() { + profileGeneration &+= 1 + tableRequestID = nil + selectedProfileID = nil + selectedTable = nil + openTableTabs = [] + columns = [] + columnTypes = [:] + rows = [] + sourceRows = [] + totalRows = 0 + currentOffset = 0 + primaryKeyColumns = [] + indexes = [] + foreignKeys = [] + tables = [] + objects = [:] + lastExplainResult = nil + lastDiagnostics = nil + backupProgress = nil + resetSQLWorkspace() + clearSpecializedWorkspace() + errorMessage = nil + isLoading = false + } + + private func resetSQLWorkspace() { + let tab = DatabaseSQLTab(title: "Query 1") + sqlTabs = [tab] + selectedSQLTabID = tab.id + } + + private func isCurrent(profileID: UUID, generation: UInt64) -> Bool { + selectedProfileID == profileID && profileGeneration == generation + } + private func clearSQLResults() { sqlTabs = sqlTabs.map { tab in var tab = tab @@ -1306,7 +1566,7 @@ final class DatabaseFeatureModel: ObservableObject { } private func masked(_ result: DatabaseQueryResult) -> DatabaseQueryResult { - DatabaseQueryResult(rows: masked(result.rows), truncated: result.truncated, totalRows: result.totalRows) + DatabaseQueryResult(rows: masked(result.rows), columns: result.columns, truncated: result.truncated, totalRows: result.totalRows) } private func masked(_ rows: [DatabaseRow]) -> [DatabaseRow] { diff --git a/Sources/Lithe/Application/DatabaseSQLSupport.swift b/Sources/Lithe/Application/DatabaseSQLSupport.swift index 3aad7f4269..0dd1f59efd 100644 --- a/Sources/Lithe/Application/DatabaseSQLSupport.swift +++ b/Sources/Lithe/Application/DatabaseSQLSupport.swift @@ -139,15 +139,15 @@ enum DatabaseSQLAnalyzer { let isUnqualifiedWrite = (tokens.contains("UPDATE") || tokens.contains("DELETE")) && !tokens.contains("WHERE") let isDestructive = tokens.contains("DROP") || tokens.contains("TRUNCATE") - let isUnknownWrite = kind == .unknown - let requiresConfirmation = isUnqualifiedWrite || isDestructive || isUnknownWrite + let isUnknownStatement = kind == .unknown + let requiresConfirmation = isUnqualifiedWrite || isDestructive let warning: String? if isUnqualifiedWrite { warning = "This UPDATE or DELETE has no WHERE clause and can affect every row." } else if isDestructive { warning = "This statement can permanently remove database objects or data." - } else if isUnknownWrite { - warning = "This statement could change the database and needs confirmation." + } else if isUnknownStatement { + warning = "This statement type is not recognized locally; the database will validate it." } else { warning = nil } diff --git a/Sources/Lithe/Services/DatabaseRecoveryStore.swift b/Sources/Lithe/Services/DatabaseRecoveryStore.swift index 9c142c5d9e..9bccbecb00 100644 --- a/Sources/Lithe/Services/DatabaseRecoveryStore.swift +++ b/Sources/Lithe/Services/DatabaseRecoveryStore.swift @@ -71,7 +71,34 @@ struct DatabaseAuditEntry: Codable, Equatable, Identifiable, Sendable { let errorMessage: String? } +enum DatabaseExecutionSource: String, Codable, Equatable, Sendable { + case sql + case redis + case nacos +} + +enum DatabaseExecutionStatus: String, Codable, Equatable, Sendable { + case succeeded + case failed + case cancelled +} + +struct DatabaseExecutionEvent: Codable, Equatable, Identifiable, Sendable { + let id: UUID + let profileID: UUID + let profileName: String + let source: DatabaseExecutionSource + let operation: String + let startedAt: Date + let durationMilliseconds: Int + let status: DatabaseExecutionStatus + let rowsReturned: Int? + let rowsAffected: UInt64? + let errorMessage: String? +} + final class DatabaseRecoveryStore: @unchecked Sendable { + private static let executionLogLock = NSRecursiveLock() private let rootURL: URL private let fileManager: FileManager private let encoder: JSONEncoder @@ -168,6 +195,31 @@ final class DatabaseRecoveryStore: @unchecked Sendable { return entries.filter { $0.profileID == profileID } } + func appendExecutionEvent(_ event: DatabaseExecutionEvent, maximumEntries: Int = 1_000) throws { + Self.executionLogLock.lock() + defer { Self.executionLogLock.unlock() } + try fileManager.createDirectory(at: rootURL, withIntermediateDirectories: true) + var entries = executionEvents().filter { $0.id != event.id } + entries.insert(event, at: 0) + try encoder.encode(Array(entries.prefix(maximumEntries))).write(to: executionURL, options: [.atomic]) + } + + func executionEvents(for profileID: UUID? = nil) -> [DatabaseExecutionEvent] { + Self.executionLogLock.lock() + defer { Self.executionLogLock.unlock() } + let entries = (try? decoder.decode([DatabaseExecutionEvent].self, from: Data(contentsOf: executionURL))) ?? [] + guard let profileID else { return entries } + return entries.filter { $0.profileID == profileID } + } + + func deleteExecutionEvents(for profileID: UUID) throws { + Self.executionLogLock.lock() + defer { Self.executionLogLock.unlock() } + let remaining = executionEvents().filter { $0.profileID != profileID } + try fileManager.createDirectory(at: rootURL, withIntermediateDirectories: true) + try encoder.encode(remaining).write(to: executionURL, options: [.atomic]) + } + private func loadRecoveryPoints() throws -> [DatabaseRecoveryPoint] { guard fileManager.fileExists(atPath: manifestURL.path) else { return [] } return try decoder.decode([DatabaseRecoveryPoint].self, from: Data(contentsOf: manifestURL)) @@ -175,6 +227,7 @@ final class DatabaseRecoveryStore: @unchecked Sendable { private var manifestURL: URL { rootURL.appendingPathComponent("recovery-points.json") } private var auditURL: URL { rootURL.appendingPathComponent("audit.json") } + private var executionURL: URL { rootURL.appendingPathComponent("execution-events.json") } private func validated(_ data: Data, for point: DatabaseRecoveryPoint) throws -> Data { if !point.sha256.isEmpty && Self.sha256(data: data) != point.sha256 { diff --git a/Sources/Lithe/Services/DatabaseSidecarService.swift b/Sources/Lithe/Services/DatabaseSidecarService.swift index 60ab8b1f24..0d7f1e7e5e 100644 --- a/Sources/Lithe/Services/DatabaseSidecarService.swift +++ b/Sources/Lithe/Services/DatabaseSidecarService.swift @@ -240,8 +240,26 @@ typealias DatabaseRow = [String: DatabaseValue] struct DatabaseQueryResult: Codable, Equatable, Sendable { let rows: [DatabaseRow] + let columns: [String]? let truncated: Bool var totalRows: Int64? + + init(rows: [DatabaseRow], columns: [String]? = nil, truncated: Bool, totalRows: Int64? = nil) { + self.rows = rows + self.columns = columns + self.truncated = truncated + self.totalRows = totalRows + } + + private enum CodingKeys: String, CodingKey { case rows, columns, truncated, totalRows } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + rows = try container.decode([DatabaseRow].self, forKey: .rows) + columns = try container.decodeIfPresent([String].self, forKey: .columns) + truncated = try container.decode(Bool.self, forKey: .truncated) + totalRows = try container.decodeIfPresent(Int64.self, forKey: .totalRows) + } } struct DatabaseExecuteResult: Codable, Equatable, Sendable { diff --git a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift index c5c1b83104..826c25fc77 100644 --- a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift +++ b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift @@ -730,16 +730,21 @@ private struct DatabaseQueryResultGrid: View { private func display(_ value: DatabaseValue?) -> String { switch value { case nil, .null: "NULL" - case let .string(value): value + case let .string(value): value.isEmpty ? "\"\"" : value case let .integer(value): String(value) case let .number(value): String(value) case let .bool(value): value ? "true" : "false" - case let .object(value): String(describing: value) - case let .array(value): String(describing: value) + case let .object(value): databaseSQLJSONText(.object(value)) + case let .array(value): databaseSQLJSONText(.array(value)) } } } +private func databaseSQLJSONText(_ value: DatabaseValue) -> String { + guard let data = try? JSONEncoder().encode(value) else { return String(describing: value) } + return String(decoding: data, as: UTF8.self) +} + private struct DatabaseStructureView: View { @EnvironmentObject private var model: AppModel @State private var editor: DatabaseSchemaEditorKind? @@ -1017,18 +1022,62 @@ private struct DatabaseDiagnosticsView: View { .foregroundStyle(LitheTheme.success) } } + Section("Execution log") { + let events = model.databaseFeature.executionEvents + .filter { $0.profileID == model.databaseFeature.selectedProfileID } + .prefix(20) + if events.isEmpty { + Text("No execution events yet").foregroundStyle(LitheTheme.secondaryText) + } else { + ForEach(events) { event in + HStack(alignment: .top, spacing: 8) { + Image(systemName: event.status == .succeeded ? "checkmark.circle.fill" : "xmark.circle.fill") + .foregroundStyle(event.status == .succeeded ? LitheTheme.success : LitheTheme.error) + VStack(alignment: .leading, spacing: 2) { + HStack { + Text("\(event.source.rawValue.uppercased()) · \(event.operation)") + .font(.system(size: 11, weight: .medium)) + Spacer() + Text("\(event.durationMilliseconds) ms") + .font(.system(size: 10, design: .monospaced)) + .foregroundStyle(LitheTheme.secondaryText) + } + if let error = event.errorMessage { + Text(error) + .font(.system(size: 10)) + .foregroundStyle(LitheTheme.error) + .lineLimit(2) + } else if let rows = event.rowsReturned { + Text("\(rows) rows returned") + .font(.system(size: 10)) + .foregroundStyle(LitheTheme.secondaryText) + } + } + } + } + } + } Section("Recent executions") { - let entries = model.databaseFeature.sqlHistory.prefix(10) + let entries = model.databaseFeature.sqlHistory + .filter { $0.profileID == model.databaseFeature.selectedProfileID } + .prefix(10) if entries.isEmpty { Text("No executed SQL yet").foregroundStyle(LitheTheme.secondaryText) } else { ForEach(entries) { entry in - HStack { - DatabaseLocalization.statementKind(entry.kind) - Spacer() - Text("\(entry.durationMilliseconds) ms") - .font(.system(size: 11, design: .monospaced)) + VStack(alignment: .leading, spacing: 3) { + HStack { + DatabaseLocalization.statementKind(entry.kind) + Spacer() + Text("\(entry.durationMilliseconds) ms") + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(LitheTheme.secondaryText) + } + Text(entry.sql.replacingOccurrences(of: "\n", with: " ")) + .font(.system(size: 10, design: .monospaced)) .foregroundStyle(LitheTheme.secondaryText) + .lineLimit(1) + .textSelection(.enabled) } } } @@ -1051,7 +1100,13 @@ private struct DatabaseDiagnosticsView: View { } } Section("Audit") { - ForEach(model.databaseFeature.auditEntries.prefix(10)) { entry in + let entries = model.databaseFeature.auditEntries + .filter { $0.profileID == model.databaseFeature.selectedProfileID } + .prefix(10) + if entries.isEmpty { + Text("No audit entries yet").foregroundStyle(LitheTheme.secondaryText) + } + ForEach(entries) { entry in HStack { Image(systemName: entry.succeeded ? "checkmark.circle" : "xmark.circle") .foregroundStyle(entry.succeeded ? LitheTheme.success : LitheTheme.error) @@ -1065,7 +1120,10 @@ private struct DatabaseDiagnosticsView: View { .listStyle(.inset) if let result = model.databaseFeature.lastDiagnostics { Rectangle().fill(LitheTheme.divider).frame(height: 1) - DatabaseQueryResultGrid(columns: result.rows.reduce(into: [String]()) { result, row in for key in row.keys where !result.contains(key) { result.append(key) } }.sorted(), rows: result.rows) + let columns = result.columns ?? result.rows.reduce(into: [String]()) { columns, row in + for key in row.keys where !columns.contains(key) { columns.append(key) } + } + DatabaseQueryResultGrid(columns: columns, rows: result.rows) .frame(minHeight: 170) } } diff --git a/Sources/Lithe/Views/DatabaseSidebarView.swift b/Sources/Lithe/Views/DatabaseSidebarView.swift index 280fbb94e0..99f2f8ccd1 100644 --- a/Sources/Lithe/Views/DatabaseSidebarView.swift +++ b/Sources/Lithe/Views/DatabaseSidebarView.swift @@ -1733,6 +1733,10 @@ struct DatabaseConnectionEditor: View { ) if kind == .redis { TextField("Redis database index", text: $database) + .onChange(of: database) { _, value in + let digitsOnly = value.filter(\.isNumber) + if digitsOnly != value { database = digitsOnly } + } Text("Leave the database index at 0 for the standard Redis database.") .font(.system(size: 10.5)) .foregroundStyle(LitheTheme.secondaryText) @@ -1807,7 +1811,7 @@ struct DatabaseConnectionEditor: View { case .sqlserver: port = "1433"; username = "sa"; database = "master"; path = "" case .mongodb: port = "27017"; username = ""; database = "admin"; path = "" case .redis: port = "6379"; username = ""; database = "0"; path = "" - case .nacos: port = "8848"; username = "nacos"; database = ""; path = "/nacos" + case .nacos: port = "8848"; username = ""; database = ""; path = "/nacos" } } .onAppear { diff --git a/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift b/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift index 0435177174..23547dcd11 100644 --- a/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift +++ b/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift @@ -105,6 +105,12 @@ struct RedisWorkspaceView: View { .padding(10) Rectangle().fill(LitheTheme.divider).frame(height: 1) + if let profile, feature.connectionStatuses[profile.id] == .failed, let error = feature.errorMessage { + specializedErrorBanner(message: error) { + Task { await feature.loadRedisKeys(pattern: pattern) } + } + } + if feature.redisKeys.isEmpty && !feature.isLoading { specializedEmptyState(symbol: "magnifyingglass", title: "No keys loaded", detail: "Search with a Redis pattern to scan this database incrementally.") } else { @@ -348,6 +354,14 @@ struct NacosWorkspaceView: View { } .labelsHidden().pickerStyle(.segmented).frame(width: 250).padding(10) Rectangle().fill(LitheTheme.divider).frame(height: 1) + if let profile, feature.connectionStatuses[profile.id] == .failed, let error = feature.errorMessage { + specializedErrorBanner(message: error) { + Task { + await feature.loadNacosConfigs(dataId: dataIDSearch, group: groupSearch) + await feature.loadNacosServices(serviceName: serviceSearch, group: serviceGroupSearch) + } + } + } if section == .configs { configurations } else { services } } .background(LitheTheme.editor) @@ -573,6 +587,28 @@ private func specializedEmptyState(symbol: String, title: LocalizedStringKey, de .padding(22) } +private func specializedErrorBanner(message: String, retry: @escaping () -> Void) -> some View { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(LitheTheme.error) + Text(message) + .font(.system(size: 10.5)) + .foregroundStyle(LitheTheme.primaryText) + .lineLimit(3) + .textSelection(.enabled) + Spacer(minLength: 4) + Button(action: retry) { + Image(systemName: "arrow.clockwise") + } + .litheIconButton() + .help("Retry") + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .background(LitheTheme.error.opacity(0.1)) + .overlay(alignment: .bottom) { Rectangle().fill(LitheTheme.error.opacity(0.35)).frame(height: 1) } +} + private func redisTypeSymbol(_ type: String) -> String { switch type.lowercased() { case "string": "text.alignleft" diff --git a/Sources/Lithe/Views/DatabaseTableView.swift b/Sources/Lithe/Views/DatabaseTableView.swift index a641cd2fa1..67a017921f 100644 --- a/Sources/Lithe/Views/DatabaseTableView.swift +++ b/Sources/Lithe/Views/DatabaseTableView.swift @@ -574,12 +574,12 @@ struct DatabaseTableView: View { .background(LitheTheme.toolHeader) .disabled(deletedRows.contains(index)) ForEach(model.databaseFeature.columns, id: \.self) { column in - TextField("NULL", text: binding(row: index, column: column, original: row[column])) + TextField("", text: binding(row: index, column: column, original: row[column])) .textFieldStyle(.plain).font(.system(size: 12, design: .monospaced)).padding(.horizontal, 7) .frame(width: columnWidth, height: 29).background(drafts[CellKey(row: index, column: column)] == nil ? Color.clear : LitheTheme.warning.opacity(0.12)) .overlay(alignment: .trailing) { Rectangle().fill(LitheTheme.divider).frame(width: 1) } .onTapGesture { pasteAnchor = CellKey(row: index, column: column) } - .contextMenu { rowContextMenu(index: index) } + .contextMenu { cellContextMenu(row: index, column: column) } } } .background(selectedRows.contains(index) ? LitheTheme.selection.opacity(0.34) : Color.clear) @@ -615,6 +615,16 @@ struct DatabaseTableView: View { .disabled(model.databaseFeature.selectedProfile?.readOnly == true) } + @ViewBuilder + private func cellContextMenu(row: Int, column: String) -> some View { + Button("Set NULL") { setNull(row: row, column: column) } + .disabled(model.databaseFeature.selectedProfile?.readOnly == true) + Button("Set Empty String") { setEmptyString(row: row, column: column) } + .disabled(model.databaseFeature.selectedProfile?.readOnly == true) + Divider() + rowContextMenu(index: row) + } + private func columnWidth(availableWidth: CGFloat) -> CGFloat { guard !model.databaseFeature.columns.isEmpty else { return 160 } return max(140, floor((availableWidth - selectionColumnWidth) / CGFloat(model.databaseFeature.columns.count))) @@ -658,6 +668,12 @@ struct DatabaseTableView: View { else { drafts[key] = .null } } + private func setEmptyString(row: Int, column: String) { + let key = CellKey(row: row, column: column) + if model.databaseFeature.rows[row][column] == .string("") { drafts.removeValue(forKey: key) } + else { drafts[key] = .string("") } + } + private func applyBatchUpdate(column: String, value: String, setNull: Bool) { for rowIndex in selectedRows where model.databaseFeature.rows.indices.contains(rowIndex) && !deletedRows.contains(rowIndex) { let key = CellKey(row: rowIndex, column: column) @@ -693,7 +709,15 @@ struct DatabaseTableView: View { } private func display(_ value: DatabaseValue?) -> String { - switch value { case nil, .null: ""; case let .string(value): value; case let .integer(value): String(value); case let .number(value): String(value); case let .bool(value): value ? "true" : "false"; case let .object(value): databaseJSONText(.object(value)); case let .array(value): databaseJSONText(.array(value)) } + switch value { + case nil, .null: "NULL" + case let .string(value): value.isEmpty ? "\"\"" : value + case let .integer(value): String(value) + case let .number(value): String(value) + case let .bool(value): value ? "true" : "false" + case let .object(value): databaseJSONText(.object(value)) + case let .array(value): databaseJSONText(.array(value)) + } } private func metadataLabel(_ row: DatabaseRow) -> String { diff --git a/Tests/LitheTests/LitheCoreLogicTests.swift b/Tests/LitheTests/LitheCoreLogicTests.swift index 2ab2d9eb46..2e6a4f078b 100644 --- a/Tests/LitheTests/LitheCoreLogicTests.swift +++ b/Tests/LitheTests/LitheCoreLogicTests.swift @@ -340,6 +340,49 @@ struct LitheCoreLogicTests { #expect(feature.selectedProfileID == nil) } + @Test + @MainActor + func databaseProfileSwitchResetsProfileScopedWorkspaceState() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let first = DatabaseProfile(name: "First", kind: .sqlite, host: "first", path: "/tmp/first.sqlite") + let second = DatabaseProfile(name: "Second", kind: .sqlite, host: "second", path: "/tmp/second.sqlite") + try store.save([first, second]) + let tableRequestCounter = TestCounter() + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let result: String + switch method { + case "listTables": + tableRequestCounter.value += 1 + let tableName = tableRequestCounter.value == 1 ? "first_table" : "second_table" + result = #"[{"table_name":"\#(tableName)"}]"# + default: + result = "[]" + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":\#(result)}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(first) + #expect(feature.tables == ["first_table"]) + feature.addSQLTab(sql: "SELECT from_first") + #expect(feature.selectedSQLTab?.sql == "SELECT from_first") + + await feature.select(second) + #expect(feature.tables == ["second_table"]) + #expect(feature.rows.isEmpty) + #expect(feature.selectedTable == nil) + #expect(feature.sqlTabs.count == 1) + #expect(feature.selectedSQLTab?.sql.isEmpty == true) + } + @Test @MainActor func databaseConnectionStatusTracksSuccessfulConnection() async throws { @@ -454,6 +497,19 @@ struct LitheCoreLogicTests { let query = DatabaseSQLAnalyzer.analyze("SELECT 'UPDATE users SET x = 1' AS example") #expect(query.kind == .query) #expect(!query.requiresConfirmation) + + let invalid = DatabaseSQLAnalyzer.analyze("SELEC 1") + #expect(invalid.kind == .unknown) + #expect(!invalid.requiresConfirmation) + #expect(invalid.warning?.contains("not recognized") == true) + } + + @Test + func databaseQueryResultPreservesProtocolColumnOrder() throws { + let data = Data(#"{"columns":["z_col","a_col"],"rows":[{"z_col":1,"a_col":2}],"truncated":false}"#.utf8) + let result = try JSONDecoder().decode(DatabaseQueryResult.self, from: data) + #expect(result.columns == ["z_col", "a_col"]) + #expect(result.rows.first?["z_col"] == .integer(1)) } @Test @@ -511,6 +567,17 @@ struct LitheCoreLogicTests { #expect(loadedAudit.profileID == profileID) #expect(loadedAudit.recoveryPointID == point.id) #expect(loadedAudit.summary == "snapshot") + + let event = DatabaseExecutionEvent( + id: UUID(), profileID: profileID, profileName: "Test DB", source: .sql, + operation: "query", startedAt: Date(timeIntervalSince1970: 1_700_000_000), durationMilliseconds: 12, + status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: "syntax error" + ) + try store.appendExecutionEvent(event) + let loadedEvent = try #require(store.executionEvents(for: profileID).first) + #expect(loadedEvent == event) + try store.deleteExecutionEvents(for: profileID) + #expect(store.executionEvents(for: profileID).isEmpty) } @Test @@ -1544,6 +1611,10 @@ private final class RecordingProcessRunner: ProcessRunner, @unchecked Sendable { } } +private final class TestCounter: @unchecked Sendable { + var value = 0 +} + private final class DatabaseTestKeyValueStore: KeyValueStore, @unchecked Sendable { private var values: [String: Any] = [:] func data(forKey key: String) -> Data? { values[key] as? Data } diff --git a/rust/lithe-db-sidecar/src/main.rs b/rust/lithe-db-sidecar/src/main.rs index fe28ae4555..4b44015ec8 100644 --- a/rust/lithe-db-sidecar/src/main.rs +++ b/rust/lithe-db-sidecar/src/main.rs @@ -2131,7 +2131,7 @@ async fn query_direct(pool: &DirectPool, sql: &str, values: &[Value], limit: u32 require_sql(sql)?; let maximum = limit.clamp(1, 100_000) as usize; let mut rows = Vec::with_capacity(maximum.min(200)); - let truncated = match pool { + let (truncated, columns) = match pool { DirectPool::MySql(pool) => { let mut stream = bind_mysql(sqlx::query(sql), values)?.fetch(pool); collect_query_rows(&mut stream, maximum, &mut rows, mysql_row_json).await? @@ -2145,7 +2145,7 @@ async fn query_direct(pool: &DirectPool, sql: &str, values: &[Value], limit: u32 collect_query_rows(&mut stream, maximum, &mut rows, sqlite_row_json).await? } }; - Ok(json!({"truncated": truncated, "rows": rows})) + Ok(json!({"columns": columns, "truncated": truncated, "rows": rows})) } async fn collect_query_rows<'a, R, S>( @@ -2153,17 +2153,26 @@ async fn collect_query_rows<'a, R, S>( maximum: usize, destination: &mut Vec, decode: fn(&R) -> Result, -) -> Result +) -> Result<(bool, Vec), (String, String)> where S: futures_util::TryStream + Unpin, + R: Row, { + let mut columns = Vec::new(); while let Some(row) = stream.try_next().await.map_err(db_error)? { + if columns.is_empty() { + columns = row + .columns() + .iter() + .map(|column| column.name().to_string()) + .collect(); + } if destination.len() == maximum { - return Ok(true); + return Ok((true, columns)); } destination.push(decode(&row)?); } - Ok(false) + Ok((false, columns)) } fn bind_mysql<'q>( @@ -2355,10 +2364,23 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { .try_get::(index) .map(|v| Value::String(v.to_string())) .unwrap_or_else(|_| mysql_text(row, index)), - "DATETIME" | "TIMESTAMP" => row + "DATETIME" => row .try_get::(index) .map(|v| Value::String(v.to_string())) .unwrap_or_else(|_| mysql_text(row, index)), + "TIMESTAMP" => row + .try_get::, _>(index) + .map(|v| Value::String(v.to_rfc3339())) + .or_else(|_| { + row.try_get::(index) + .map(|v| Value::String(v.to_string())) + }) + .unwrap_or_else(|_| mysql_text(row, index)), + "BOOLEAN" | "BOOL" => row + .try_get::(index) + .map(Value::Bool) + .or_else(|_| row.try_get::(index).map(|v| Value::Bool(v != 0))) + .unwrap_or_else(|_| mysql_text(row, index)), "JSON" => row .try_get::(index) .unwrap_or_else(|_| mysql_text(row, index)), @@ -2370,6 +2392,12 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { .try_get::(index) .map(|v| json!(v)) .unwrap_or_else(|_| mysql_text(row, index)), + value if value == "TINYINT" => row + .try_get::(index) + .map(|v| json!(v)) + .or_else(|_| row.try_get::(index).map(|v| json!(v))) + .or_else(|_| row.try_get::(index).map(|v| json!(v))) + .unwrap_or_else(|_| mysql_text(row, index)), value if value.contains("INT") || value == "YEAR" => row .try_get::(index) .map(|v| json!(v)) @@ -2908,11 +2936,22 @@ fn placeholder(kind: &str, index: usize) -> String { async fn export_csv(pool: &DirectPool, sql: &str, values: &[Value], limit: u32) -> DbResult { let result = query_direct(pool, sql, values, limit).await?; let rows = result["rows"].as_array().cloned().unwrap_or_default(); - let headers: Vec = rows - .first() - .and_then(Value::as_object) - .map(|row| row.keys().cloned().collect()) - .unwrap_or_default(); + let headers: Vec = result["columns"] + .as_array() + .map(|columns| { + columns + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .filter(|columns: &Vec| !columns.is_empty()) + .unwrap_or_else(|| { + rows.first() + .and_then(Value::as_object) + .map(|row| row.keys().cloned().collect()) + .unwrap_or_default() + }); let mut writer = csv::Writer::from_writer(Vec::new()); writer.write_record(&headers).map_err(csv_error)?; for row in rows { From 3184b9268ce34ea122d6db31c0c8f0c23a87c170 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 10 Aug 2026 11:59:05 +0800 Subject: [PATCH 2/6] fix(database): complete workspace type and scan handling --- .../Application/DatabaseFeatureModel.swift | 68 +++++++- .../Services/DatabaseSidecarService.swift | 29 +++- .../Views/DatabaseSQLWorkspaceView.swift | 4 + Sources/Lithe/Views/DatabaseSidebarView.swift | 27 ++++ .../DatabaseSpecializedWorkspaceViews.swift | 18 ++- Sources/Lithe/Views/DatabaseTableView.swift | 4 + Tests/LitheTests/LitheCoreLogicTests.swift | 66 ++++++++ rust/lithe-db-sidecar/src/main.rs | 153 ++++++++++++++---- .../lithe-db-sidecar/src/sqlserver_adapter.rs | 2 +- 9 files changed, 332 insertions(+), 39 deletions(-) diff --git a/Sources/Lithe/Application/DatabaseFeatureModel.swift b/Sources/Lithe/Application/DatabaseFeatureModel.swift index fb8e283e88..472a810971 100644 --- a/Sources/Lithe/Application/DatabaseFeatureModel.swift +++ b/Sources/Lithe/Application/DatabaseFeatureModel.swift @@ -23,6 +23,7 @@ final class DatabaseFeatureModel: ObservableObject { @Published private(set) var folders: [DatabaseConnectionFolder] @Published var selectedProfileID: UUID? @Published private(set) var tables: [String] = [] + @Published private(set) var databaseOptions: [String] = [] @Published var selectedTable: String? @Published private(set) var openTableTabs: [String] = [] @Published private(set) var columns: [String] = [] @@ -52,6 +53,7 @@ final class DatabaseFeatureModel: ObservableObject { @Published private(set) var redisKeys: [RedisKeySummary] = [] @Published private(set) var redisNextCursor = "0" @Published private(set) var redisSelectedKey: RedisKeyDetail? + @Published var redisIncludeSize = true @Published private(set) var nacosConfigs: [NacosConfigSummary] = [] @Published private(set) var nacosConfigTotalCount = 0 @Published var nacosSelectedConfig: NacosConfigDetail? @@ -349,9 +351,14 @@ final class DatabaseFeatureModel: ObservableObject { } func refreshTables() async { - guard let profile = selectedProfile else { return } + guard let profile = selectedProfile else { + tables = [] + databaseOptions = [] + return + } guard profile.kind.supportsDataGrid else { tables = [] + databaseOptions = [] return } let generation = profileGeneration @@ -360,6 +367,15 @@ final class DatabaseFeatureModel: ObservableObject { setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) + if profile.kind == .mysql || profile.kind == .mariadb { + let databaseRows = try await Task.detached { [operations] in + try operations.listDatabases(connection: connection) + }.value + guard isCurrent(profileID: profile.id, generation: generation) else { return } + databaseOptions = databaseRows + } else { + databaseOptions = [] + } let result = try await Task.detached { [operations] in try operations.listTables(connection: connection, schema: "") }.value guard isCurrent(profileID: profile.id, generation: generation) else { return } setConnectionStatus(.connected, for: profile.id) @@ -369,13 +385,54 @@ final class DatabaseFeatureModel: ObservableObject { if profile.kind.isSQLDatabase { await refreshObjects(profileID: profile.id, generation: generation) } } catch { guard isCurrent(profileID: profile.id, generation: generation) else { return } - tables = []; objects = [:] + tables = []; objects = [:]; databaseOptions = [] errorMessage = executionError(error) setConnectionStatus(.failed, for: profile.id) } if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } + func refreshDatabases() async { + guard let profile = selectedProfile, profile.kind == .mysql || profile.kind == .mariadb else { return } + let generation = profileGeneration + isLoading = true + errorMessage = nil + do { + let connection = connection(profile) + let rows = try await Task.detached { [operations] in + try operations.listDatabases(connection: connection) + }.value + guard isCurrent(profileID: profile.id, generation: generation) else { return } + databaseOptions = rows + isLoading = false + } catch { + if isCurrent(profileID: profile.id, generation: generation) { + databaseOptions = [] + errorMessage = executionError(error) + isLoading = false + } + } + } + + func selectDatabase(_ database: String, for profile: DatabaseProfile) async { + guard selectedProfileID == profile.id, + (profile.kind == .mysql || profile.kind == .mariadb), + databaseOptions.contains(database) else { return } + var updated = profiles + guard let index = updated.firstIndex(where: { $0.id == profile.id }) else { return } + var updatedProfile = updated[index] + updatedProfile.database = database + updated[index] = updatedProfile + do { + try connectionStore.save(updated) + profiles = sortedProfiles(updated) + activateProfile(updatedProfile) + await refreshTables() + } catch { + errorMessage = executionError(error) + } + } + private func refreshObjects(profileID: UUID, generation: UInt64) async { guard isCurrent(profileID: profileID, generation: generation), let profile = profiles.first(where: { $0.id == profileID }) else { return } @@ -1055,13 +1112,14 @@ final class DatabaseFeatureModel: ObservableObject { let cursor = reset ? "0" : redisNextCursor if !reset && cursor == "0" { return } let startedAt = Date() + let includeSize = redisIncludeSize isLoading = true errorMessage = nil setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) let result = try await Task.detached { [operations] in - try operations.redisScan(connection: connection, cursor: cursor, pattern: pattern.isEmpty ? "*" : pattern, count: 100) + try operations.redisScan(connection: connection, cursor: cursor, pattern: pattern.isEmpty ? "*" : pattern, count: 100, includeSize: includeSize) }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "SCAN", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.keys.count, rowsAffected: nil, errorMessage: nil)) @@ -1477,6 +1535,7 @@ final class DatabaseFeatureModel: ObservableObject { indexes = [] foreignKeys = [] tables = [] + databaseOptions = [] objects = [:] lastExplainResult = nil lastDiagnostics = nil @@ -1505,6 +1564,7 @@ final class DatabaseFeatureModel: ObservableObject { indexes = [] foreignKeys = [] tables = [] + databaseOptions = [] objects = [:] lastExplainResult = nil lastDiagnostics = nil @@ -1578,7 +1638,7 @@ final class DatabaseFeatureModel: ObservableObject { guard case let .string(text) = value else { return value } let type = columnTypes[column] ?? "" if type.contains("int"), let number = Int64(text) { return .integer(number) } - if type.contains("numeric") || type.contains("decimal") { return .object(["decimal": .string(text)]) } + if type.contains("numeric") || type.contains("decimal") { return .decimal(text) } if type.contains("double") || type.contains("float") || type.contains("real"), let number = Double(text) { return .number(number) } if type == "boolean" || type == "bool" { if ["true", "1"].contains(text.lowercased()) { return .bool(true) } diff --git a/Sources/Lithe/Services/DatabaseSidecarService.swift b/Sources/Lithe/Services/DatabaseSidecarService.swift index 0d7f1e7e5e..57d4cc0b64 100644 --- a/Sources/Lithe/Services/DatabaseSidecarService.swift +++ b/Sources/Lithe/Services/DatabaseSidecarService.swift @@ -207,7 +207,9 @@ enum DatabaseValue: Codable, Equatable, Sendable { case bool(Bool) case integer(Int64) case number(Double) + case decimal(String) case string(String) + case binary(Data) case object([String: DatabaseValue]) case array([DatabaseValue]) @@ -218,6 +220,13 @@ enum DatabaseValue: Codable, Equatable, Sendable { else if let value = try? container.decode(Int64.self) { self = .integer(value) } else if let value = try? container.decode(Double.self) { self = .number(value) } else if let value = try? container.decode(String.self) { self = .string(value) } + else if let tagged = try? container.decode([String: String].self), tagged.count == 1, let value = tagged["decimal"] { + self = .decimal(value) + } else if let tagged = try? container.decode([String: String].self), tagged.count == 1, + let encoded = tagged["binary"], + let value = Data(base64Encoded: encoded) { + self = .binary(value) + } else if let value = try? container.decode([String: DatabaseValue].self) { self = .object(value) } else { self = .array(try container.decode([DatabaseValue].self)) } } @@ -229,7 +238,9 @@ enum DatabaseValue: Codable, Equatable, Sendable { case let .bool(value): try container.encode(value) case let .integer(value): try container.encode(value) case let .number(value): try container.encode(value) + case let .decimal(value): try container.encode(["decimal": value]) case let .string(value): try container.encode(value) + case let .binary(value): try container.encode(["binary": value.base64EncodedString()]) case let .object(value): try container.encode(value) case let .array(value): try container.encode(value) } @@ -332,6 +343,7 @@ struct DatabaseDiagnosticsRequest: Codable, Equatable, Sendable { protocol DatabaseOperations: Sendable { func capabilities() throws -> DatabaseCapabilities func testConnection(_ connection: DatabaseConnection) throws + func listDatabases(connection: DatabaseConnection) throws -> [String] func listTables(connection: DatabaseConnection, schema: String) throws -> [DatabaseRow] func describeTable(connection: DatabaseConnection, schema: String, table: String) throws -> [DatabaseRow] func listIndexes(connection: DatabaseConnection, schema: String, table: String) throws -> [DatabaseRow] @@ -356,7 +368,7 @@ protocol DatabaseOperations: Sendable { func restoreSQL(connection: DatabaseConnection, data: Data, confirmed: Bool, allowWrite: Bool) throws -> DatabaseExecuteResult func restoreSQLFile(connection: DatabaseConnection, fileURL: URL, confirmed: Bool, allowWrite: Bool) throws -> DatabaseExecuteResult - func redisScan(connection: DatabaseConnection, cursor: String, pattern: String, count: Int) throws -> RedisScanResult + func redisScan(connection: DatabaseConnection, cursor: String, pattern: String, count: Int, includeSize: Bool) throws -> RedisScanResult func redisGetKey(connection: DatabaseConnection, key: String) throws -> RedisKeyDetail func redisSetString(connection: DatabaseConnection, key: String, value: String, ttl: Int64?, confirmed: Bool, allowWrite: Bool) throws func redisReplaceHash(connection: DatabaseConnection, key: String, entries: [RedisHashEntry], confirmed: Bool, allowWrite: Bool) throws @@ -374,7 +386,11 @@ protocol DatabaseOperations: Sendable { } extension DatabaseOperations { - func redisScan(connection: DatabaseConnection, cursor: String, pattern: String, count: Int) throws -> RedisScanResult { throw DatabaseSidecarError.requestFailed(code: "unsupported_operation", message: "Redis is not available in this database service.") } + func listDatabases(connection: DatabaseConnection) throws -> [String] { throw DatabaseSidecarError.requestFailed(code: "unsupported_operation", message: "Database selection is not available for this database service.") } + func redisScan(connection: DatabaseConnection, cursor: String, pattern: String, count: Int) throws -> RedisScanResult { + try redisScan(connection: connection, cursor: cursor, pattern: pattern, count: count, includeSize: true) + } + func redisScan(connection: DatabaseConnection, cursor: String, pattern: String, count: Int, includeSize: Bool) throws -> RedisScanResult { throw DatabaseSidecarError.requestFailed(code: "unsupported_operation", message: "Redis is not available in this database service.") } func redisGetKey(connection: DatabaseConnection, key: String) throws -> RedisKeyDetail { throw DatabaseSidecarError.requestFailed(code: "unsupported_operation", message: "Redis is not available in this database service.") } func redisSetString(connection: DatabaseConnection, key: String, value: String, ttl: Int64?, confirmed: Bool, allowWrite: Bool) throws { throw DatabaseSidecarError.requestFailed(code: "unsupported_operation", message: "Redis is not available in this database service.") } func redisReplaceHash(connection: DatabaseConnection, key: String, entries: [RedisHashEntry], confirmed: Bool, allowWrite: Bool) throws { throw DatabaseSidecarError.requestFailed(code: "unsupported_operation", message: "Redis is not available in this database service.") } @@ -427,6 +443,10 @@ final class DatabaseSidecarService: DatabaseOperations, @unchecked Sendable { let _: ConnectedResult = try request(method: "testConnection", params: ConnectionParams(connection: connection)) } + func listDatabases(connection: DatabaseConnection) throws -> [String] { + try request(method: "listDatabases", params: ConnectionParams(connection: connection)) + } + func listTables(connection: DatabaseConnection, schema: String = "") throws -> [DatabaseRow] { try request(method: "listTables", params: TableParams(connection: connection, schema: schema)) } @@ -532,8 +552,8 @@ final class DatabaseSidecarService: DatabaseOperations, @unchecked Sendable { try request(method: "restoreSqlFile", params: SQLFileImportParams(connection: connection, outputPath: fileURL.path, confirmed: confirmed, allowWrite: allowWrite), timeoutMilliseconds: 120_000) } - func redisScan(connection: DatabaseConnection, cursor: String = "0", pattern: String = "*", count: Int = 100) throws -> RedisScanResult { - try request(method: "redisScan", params: RedisScanParams(connection: connection, cursor: cursor, pattern: pattern, count: count)) + func redisScan(connection: DatabaseConnection, cursor: String = "0", pattern: String = "*", count: Int = 100, includeSize: Bool = true) throws -> RedisScanResult { + try request(method: "redisScan", params: RedisScanParams(connection: connection, cursor: cursor, pattern: pattern, count: count, includeSize: includeSize)) } func redisGetKey(connection: DatabaseConnection, key: String) throws -> RedisKeyDetail { @@ -762,6 +782,7 @@ private struct RedisScanParams: Codable { var cursor = "0" var pattern = "*" var count = 100 + var includeSize = true } private struct RedisKeyParams: Codable { let connection: DatabaseConnection; let key: String } private struct RedisWriteParams: Codable { diff --git a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift index 826c25fc77..2bb480706c 100644 --- a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift +++ b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift @@ -733,7 +733,9 @@ private struct DatabaseQueryResultGrid: View { case let .string(value): value.isEmpty ? "\"\"" : value case let .integer(value): String(value) case let .number(value): String(value) + case let .decimal(value): value case let .bool(value): value ? "true" : "false" + case let .binary(value): "Binary (\(value.count) bytes)" case let .object(value): databaseSQLJSONText(.object(value)) case let .array(value): databaseSQLJSONText(.array(value)) } @@ -853,7 +855,9 @@ private struct DatabaseStructureView: View { case let .string(value): value case let .integer(value): String(value) case let .number(value): String(value) + case let .decimal(value): value case let .bool(value): value ? "true" : "false" + case let .binary(value): "Binary (\(value.count) bytes)" case let .object(value): String(describing: value) case let .array(value): String(describing: value) } diff --git a/Sources/Lithe/Views/DatabaseSidebarView.swift b/Sources/Lithe/Views/DatabaseSidebarView.swift index 99f2f8ccd1..445b6e317f 100644 --- a/Sources/Lithe/Views/DatabaseSidebarView.swift +++ b/Sources/Lithe/Views/DatabaseSidebarView.swift @@ -74,6 +74,33 @@ struct DatabaseSidebarView: View { .foregroundStyle(LitheTheme.tertiaryText) } Spacer() + if let selected = model.databaseFeature.selectedProfile, + selected.kind == .mysql || selected.kind == .mariadb { + Menu { + Button("Refresh databases") { + Task { await model.databaseFeature.refreshDatabases() } + } + Divider() + if model.databaseFeature.databaseOptions.isEmpty { + Text("No databases loaded") + } else { + ForEach(model.databaseFeature.databaseOptions, id: \.self) { database in + Button { + Task { await model.databaseFeature.selectDatabase(database, for: selected) } + } label: { + HStack { + Text(database) + if selected.database == database { Image(systemName: "checkmark") } + } + } + } + } + } label: { + Image(systemName: "cylinder.split.1x2") + } + .litheIconButton() + .help("Choose database") + } Button { presentConnectionEditor() } label: { Image(systemName: "plus") } .litheIconButton().help("Add database connection") Button { editingFolder = nil; creatingFolderParentID = nil; showsFolderEditor = true } label: { Image(systemName: "folder.badge.plus") } diff --git a/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift b/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift index 23547dcd11..e9aa4392cc 100644 --- a/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift +++ b/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift @@ -28,6 +28,9 @@ struct RedisWorkspaceView: View { .task(id: feature.selectedProfileID) { await feature.loadRedisKeys(pattern: pattern) } + .onChange(of: feature.redisIncludeSize) { _, _ in + Task { await feature.loadRedisKeys(pattern: pattern) } + } .onChange(of: feature.redisSelectedKey) { _, detail in guard let detail else { stringDraft = ""; hashDraft = "{}"; ttlDraft = ""; renameDraft = "" @@ -82,6 +85,13 @@ struct RedisWorkspaceView: View { .background(LitheTheme.inputBackground) .clipShape(Capsule()) } + Toggle("Estimate size", isOn: Binding( + get: { feature.redisIncludeSize }, + set: { feature.redisIncludeSize = $0 } + )) + .toggleStyle(.switch) + .controlSize(.mini) + .help("Estimate key size during SCAN") Button { Task { await feature.loadRedisKeys(pattern: pattern) } } label: { Image(systemName: "arrow.clockwise") } .litheIconButton().help("Rescan from the beginning") .disabled(feature.isLoading || profile == nil) @@ -129,7 +139,7 @@ struct RedisWorkspaceView: View { .clipShape(RoundedRectangle(cornerRadius: 5)) VStack(alignment: .leading, spacing: 2) { Text(key.key).font(.system(size: 11.5, weight: .medium)).lineLimit(1) - Text("\(key.type.uppercased()) · \(redisTTLText(key.ttl)) · \(key.size)") + Text("\(key.type.uppercased()) · \(redisTTLText(key.ttl)) · \(redisSizeText(key.size))") .font(.system(size: 9.5)).foregroundStyle(LitheTheme.secondaryText).lineLimit(1) } Spacer(minLength: 0) @@ -172,7 +182,7 @@ struct RedisWorkspaceView: View { .clipShape(RoundedRectangle(cornerRadius: 7)) VStack(alignment: .leading, spacing: 3) { Text(detail.key).font(.system(size: 12.5, weight: .semibold)).textSelection(.enabled) - Text("\(detail.type.uppercased()) · \(detail.size) entries / bytes · \(redisTTLText(detail.ttl))") + Text("\(detail.type.uppercased()) · \(redisSizeText(detail.size)) · \(redisTTLText(detail.ttl))") .font(.system(size: 9.5)).foregroundStyle(LitheTheme.secondaryText) } Spacer() @@ -641,3 +651,7 @@ private func redisTTLText(_ ttl: Int64) -> String { default: "TTL unknown" } } + +private func redisSizeText(_ size: Int64) -> String { + size < 0 ? "size not estimated" : "size \(size)" +} diff --git a/Sources/Lithe/Views/DatabaseTableView.swift b/Sources/Lithe/Views/DatabaseTableView.swift index 67a017921f..45634b14c3 100644 --- a/Sources/Lithe/Views/DatabaseTableView.swift +++ b/Sources/Lithe/Views/DatabaseTableView.swift @@ -714,7 +714,9 @@ struct DatabaseTableView: View { case let .string(value): value.isEmpty ? "\"\"" : value case let .integer(value): String(value) case let .number(value): String(value) + case let .decimal(value): value case let .bool(value): value ? "true" : "false" + case let .binary(value): "Binary (\(value.count) bytes)" case let .object(value): databaseJSONText(.object(value)) case let .array(value): databaseJSONText(.array(value)) } @@ -1214,7 +1216,9 @@ private struct DatabaseRowDetailsSheet: View { case let .string(value): value case let .integer(value): String(value) case let .number(value): String(value) + case let .decimal(value): value case let .bool(value): value ? "true" : "false" + case let .binary(value): "Binary (\(value.count) bytes)" case let .object(value): databaseJSONText(.object(value)) case let .array(value): databaseJSONText(.array(value)) } diff --git a/Tests/LitheTests/LitheCoreLogicTests.swift b/Tests/LitheTests/LitheCoreLogicTests.swift index 2e6a4f078b..2bc5352353 100644 --- a/Tests/LitheTests/LitheCoreLogicTests.swift +++ b/Tests/LitheTests/LitheCoreLogicTests.swift @@ -73,6 +73,26 @@ struct LitheCoreLogicTests { #expect(nacosRequest.contains(#""kind":"nacos""#)) } + @Test + func databaseSidecarSerializesRedisSizePreference() throws { + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + return ProcessResult( + output: #"{"id":"\#(id)","ok":true,"result":{"keys":[],"nextCursor":"0"}}"#, + exitCode: 0 + ) + } + let service = DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")) + let redis = DatabaseConnection(kind: .redis, host: "127.0.0.1", port: 6379, database: "0") + + _ = try service.redisScan(connection: redis, includeSize: false) + + let request = String(decoding: try #require(runner.requests[0].standardInput), as: UTF8.self) + #expect(request.contains(#""includeSize":false"#)) + } + @Test func databaseSidecarMapsFailedProcessToStableError() { let runner = RecordingProcessRunner(result: ProcessResult(output: "connection store failed", exitCode: 2)) @@ -383,6 +403,40 @@ struct LitheCoreLogicTests { #expect(feature.selectedSQLTab?.sql.isEmpty == true) } + @Test + @MainActor + func databaseMySQLDatabaseSelectionPersistsAndRefreshesTables() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "MySQL", kind: .mysql, host: "localhost", username: "root") + try store.save([profile]) + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let result: String + switch method { + case "listDatabases": result = #"["alpha","beta"]"# + case "listTables": result = #"[{"table_name":"items"}]"# + default: result = "[]" + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":\#(result)}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + #expect(feature.databaseOptions == ["alpha", "beta"]) + await feature.selectDatabase("beta", for: profile) + + #expect(feature.selectedProfile?.database == "beta") + #expect(feature.tables == ["items"]) + #expect(store.load().first?.database == "beta") + } + @Test @MainActor func databaseConnectionStatusTracksSuccessfulConnection() async throws { @@ -512,6 +566,18 @@ struct LitheCoreLogicTests { #expect(result.rows.first?["z_col"] == .integer(1)) } + @Test + func databaseValuePreservesTaggedDecimalAndBinaryValues() throws { + let data = Data(#"[{"decimal":"0.00"},{"binary":"AAEC"}]"#.utf8) + let values = try JSONDecoder().decode([DatabaseValue].self, from: data) + #expect(values == [.decimal("0.00"), .binary(Data([0, 1, 2]))]) + let encoded = try JSONEncoder().encode(values) + #expect(String(decoding: encoded, as: UTF8.self).contains(#""decimal":"0.00""#)) + #expect(String(decoding: encoded, as: UTF8.self).contains(#""binary":"AAEC""#)) + let mongoObject = try JSONDecoder().decode(DatabaseValue.self, from: Data(#"{"base64":"AAEC"}"#.utf8)) + #expect(mongoObject == .object(["base64": .string("AAEC")])) + } + @Test func databaseSQLFormatterPreservesQuotedTextAndNormalizesKeywords() { let formatted = DatabaseSQLFormatter.format("select name, 'a b' from users where id=1;") diff --git a/rust/lithe-db-sidecar/src/main.rs b/rust/lithe-db-sidecar/src/main.rs index 4b44015ec8..b9040c303d 100644 --- a/rust/lithe-db-sidecar/src/main.rs +++ b/rust/lithe-db-sidecar/src/main.rs @@ -160,6 +160,8 @@ struct Params { pattern: String, #[serde(default)] count: usize, + #[serde(default = "default_true")] + include_size: bool, #[serde(default)] key: String, #[serde(default)] @@ -324,6 +326,7 @@ async fn sql_database_method(method: &str, params: Params) -> DbResult { let pool = connect(&connection).await?; let result = match method { "testConnection" => Ok(json!({"connected": true})), + "listDatabases" => list_databases(&pool, kind).await, "listTables" => list_tables(&pool, kind, ¶ms.schema).await, "describeTable" => describe_table(&pool, kind, ¶ms.schema, ¶ms.table).await, "listIndexes" => list_indexes(&pool, kind, ¶ms.schema, ¶ms.table).await, @@ -740,27 +743,77 @@ async fn redis_scan( .query_async(redis) .await .map_err(|e| redis_error(e, connection))?; + let (replies, size_enabled) = match redis_scan_metadata(redis, &keys, params.include_size).await + { + Ok(replies) => (replies, params.include_size), + Err(error) if params.include_size && redis_memory_usage_unsupported(&error) => { + let replies = redis_scan_metadata(redis, &keys, false) + .await + .map_err(|e| redis_error(e, connection))?; + (replies, false) + } + Err(error) => return Err(redis_error(error, connection)), + }; + let stride = if size_enabled { 3 } else { 2 }; + if replies.len() != keys.len() * stride { + return Err(( + "redis_error".into(), + "Redis returned an incomplete scan metadata response".into(), + )); + } let mut summaries = Vec::with_capacity(keys.len()); - for key in keys { - let kind: String = redis::cmd("TYPE") - .arg(&key) - .query_async(redis) - .await - .map_err(|e| redis_error(e, connection))?; + for (index, key) in keys.into_iter().enumerate() { + let offset = index * stride; + let kind: String = redis::from_redis_value(&replies[offset]).map_err(|e| { + ( + "redis_error".into(), + format!("Redis returned an invalid key type: {e}"), + ) + })?; if kind == "none" { continue; } - let ttl: i64 = redis::cmd("TTL") - .arg(&key) - .query_async(redis) - .await - .map_err(|e| redis_error(e, connection))?; - let size = redis_key_size(redis, &key, &kind, connection).await?; + let ttl: i64 = redis::from_redis_value(&replies[offset + 1]).map_err(|e| { + ( + "redis_error".into(), + format!("Redis returned an invalid key TTL: {e}"), + ) + })?; + let size = if size_enabled { + redis::from_redis_value::>(&replies[offset + 2]) + .unwrap_or(None) + .unwrap_or(-1) + } else { + -1 + }; summaries.push(json!({"key": key, "type": kind, "ttl": ttl, "size": size})); } Ok(json!({"keys": summaries, "nextCursor": next_cursor.to_string()})) } +async fn redis_scan_metadata( + redis: &mut redis::aio::MultiplexedConnection, + keys: &[String], + include_size: bool, +) -> redis::RedisResult> { + let mut pipeline = redis::pipe(); + for key in keys { + pipeline.cmd("TYPE").arg(key); + pipeline.cmd("TTL").arg(key); + if include_size { + pipeline.cmd("MEMORY").arg("USAGE").arg(key); + } + } + pipeline.query_async(redis).await +} + +fn redis_memory_usage_unsupported(error: &redis::RedisError) -> bool { + let message = error.to_string().to_ascii_lowercase(); + message.contains("unknown command") + || message.contains("unknown subcommand") + || message.contains("unsupported") +} + async fn redis_key_size( redis: &mut redis::aio::MultiplexedConnection, key: &str, @@ -1720,6 +1773,23 @@ async fn list_tables(pool: &AnyPool, kind: &str, schema: &str) -> DbResult { rows_value(q.fetch_all(pool).await.map_err(db_error)?) } +async fn list_databases(pool: &AnyPool, kind: &str) -> DbResult { + let sql = match kind { + "mysql" => "SELECT SCHEMA_NAME AS name FROM information_schema.schemata ORDER BY SCHEMA_NAME", + "postgresql" => "SELECT schema_name AS name FROM information_schema.schemata WHERE catalog_name = current_database() ORDER BY schema_name", + _ => return Ok(json!([])), + }; + let rows = rows_value(sqlx::query(sql).fetch_all(pool).await.map_err(db_error)?)?; + let names = rows + .as_array() + .into_iter() + .flat_map(|rows| rows.iter()) + .filter_map(|row| row.get("name").and_then(Value::as_str)) + .map(|name| Value::String(name.to_string())) + .collect(); + Ok(Value::Array(names)) +} + async fn describe_table(pool: &AnyPool, kind: &str, schema: &str, table: &str) -> DbResult { validate_identifier(table)?; let sql = match kind { @@ -2203,6 +2273,20 @@ fn bind_sqlite<'q>( Ok(query) } +fn binary_input(object: &Map) -> Option<&str> { + if object.len() != 1 { + return None; + } + object + .get("binary") + .or_else(|| object.get("base64")) + .and_then(Value::as_str) +} + +fn tagged_binary(bytes: impl AsRef<[u8]>) -> Value { + json!({"binary": BASE64.encode(bytes.as_ref())}) +} + macro_rules! bind_value_fn { ($name:ident, $db:ty, $args:ty) => { fn $name<'q>( @@ -2269,8 +2353,8 @@ macro_rules! bind_value_fn { Value::Object(v) if v.get("json").is_some() => { query.bind(sqlx::types::Json(v["json"].clone())) } - Value::Object(v) if v.get("base64").and_then(Value::as_str).is_some() => { - match BASE64.decode(v["base64"].as_str().unwrap()) { + Value::Object(v) if binary_input(v).is_some() => { + match BASE64.decode(binary_input(v).unwrap()) { Ok(value) => query.bind(value), Err(_) => query.bind(Vec::::new()), } @@ -2294,11 +2378,9 @@ fn bind_sqlite_value<'q>( Value::Number(v) if v.is_u64() => query.bind(v.as_u64().unwrap() as i64), Value::Number(v) => query.bind(v.as_f64().unwrap()), Value::String(v) => query.bind(v), - Value::Object(v) if v.get("base64").and_then(Value::as_str).is_some() => query.bind( - BASE64 - .decode(v["base64"].as_str().unwrap()) - .unwrap_or_default(), - ), + Value::Object(v) if binary_input(v).is_some() => { + query.bind(BASE64.decode(binary_input(v).unwrap()).unwrap_or_default()) + } Value::Object(v) if v.get("json").is_some() => query.bind(v["json"].to_string()), Value::Object(v) => { let tagged = [ @@ -2354,7 +2436,7 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { match kind.to_ascii_uppercase().as_str() { "DECIMAL" | "NEWDECIMAL" => row .try_get::(index) - .map(|v| Value::String(v.to_string())) + .map(|v| json!({"decimal": v.to_string()})) .unwrap_or_else(|_| mysql_text(row, index)), "DATE" => row .try_get::(index) @@ -2386,7 +2468,7 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { .unwrap_or_else(|_| mysql_text(row, index)), "BLOB" | "BINARY" | "VARBINARY" => row .try_get::, _>(index) - .map(|v| json!({"base64": BASE64.encode(v)})) + .map(tagged_binary) .unwrap_or_else(|_| mysql_text(row, index)), "FLOAT" | "DOUBLE" => row .try_get::(index) @@ -2416,7 +2498,7 @@ fn postgres_value(row: &PgRow, index: usize, kind: &str) -> Value { match kind.to_ascii_uppercase().as_str() { "NUMERIC" => row .try_get::(index) - .map(|v| Value::String(v.to_string())) + .map(|v| json!({"decimal": v.to_string()})) .unwrap_or_else(|_| pg_text(row, index)), "DATE" => row .try_get::(index) @@ -2443,7 +2525,7 @@ fn postgres_value(row: &PgRow, index: usize, kind: &str) -> Value { .unwrap_or_else(|_| pg_text(row, index)), "BYTEA" => row .try_get::, _>(index) - .map(|v| json!({"base64":BASE64.encode(v)})) + .map(tagged_binary) .unwrap_or_else(|_| pg_text(row, index)), "BOOL" => row .try_get::(index) @@ -2490,7 +2572,7 @@ fn sqlite_value(row: &SqliteRow, index: usize, kind: &str) -> Value { .unwrap_or_else(|_| sqlite_text(row, index)), "BLOB" => row .try_get::, _>(index) - .map(|v| json!({"base64":BASE64.encode(v)})) + .map(tagged_binary) .unwrap_or_else(|_| sqlite_text(row, index)), "BOOL" | "BOOLEAN" => row .try_get::(index) @@ -3697,9 +3779,9 @@ fn sql_literal(kind: &str, value: &Value) -> Result { Value::Bool(value) => Ok(if *value { "TRUE" } else { "FALSE" }.into()), Value::Number(value) => Ok(value.to_string()), Value::String(value) => Ok(format!("'{}'", value.replace('\'', "''"))), - Value::Object(object) if object.get("base64").and_then(Value::as_str).is_some() => { + Value::Object(object) if binary_input(object).is_some() => { let bytes = BASE64 - .decode(object["base64"].as_str().unwrap()) + .decode(binary_input(object).unwrap()) .map_err(|e| ("export_failed".into(), e.to_string()))?; let hex = bytes .iter() @@ -3752,7 +3834,7 @@ fn metadata_rows_value(rows: Vec) -> DbResult { let Some(Value::Object(binary)) = object.get(key) else { continue; }; - let Some(encoded) = binary.get("base64").and_then(Value::as_str) else { + let Some(encoded) = binary_input(binary) else { continue; }; let Ok(bytes) = BASE64.decode(encoded) else { @@ -3800,7 +3882,7 @@ fn typed_value(row: &sqlx::any::AnyRow, index: usize, kind: &str) -> Value { .unwrap_or_else(|_| text_value(row, index)), "BLOB" | "BYTEA" | "BINARY" | "VARBINARY" => row .try_get::, _>(index) - .map(|v| json!({"base64": BASE64.encode(v)})) + .map(tagged_binary) .unwrap_or_else(|_| text_value(row, index)), _ => text_value(row, index), } @@ -3995,12 +4077,27 @@ mod tests { sql_literal("sqlite", &json!({"base64":"AP8="})).unwrap(), "X'00ff'" ); + assert_eq!( + sql_literal("sqlite", &json!({"binary":"AP8="})).unwrap(), + "X'00ff'" + ); assert_eq!( sql_literal("postgresql", &json!({"base64":"AP8="})).unwrap(), "decode('00ff','hex')" ); } + #[test] + fn binary_values_use_an_explicit_tag_without_accepting_mixed_objects() { + assert_eq!(tagged_binary([0, 255]), json!({"binary":"AP8="})); + let explicit = json!({"binary":"AP8="}); + assert_eq!(binary_input(explicit.as_object().unwrap()), Some("AP8=")); + let legacy = json!({"base64":"AP8="}); + assert_eq!(binary_input(legacy.as_object().unwrap()), Some("AP8=")); + let mixed = json!({"binary":"AP8=","label":"payload"}); + assert_eq!(binary_input(mixed.as_object().unwrap()), None); + } + #[test] fn restore_drops_existing_objects_before_replaying_snapshot() { assert_eq!( diff --git a/rust/lithe-db-sidecar/src/sqlserver_adapter.rs b/rust/lithe-db-sidecar/src/sqlserver_adapter.rs index 64b62fe3fd..d6bbac71ca 100644 --- a/rust/lithe-db-sidecar/src/sqlserver_adapter.rs +++ b/rust/lithe-db-sidecar/src/sqlserver_adapter.rs @@ -648,7 +648,7 @@ fn cell_json(cell: &ColumnData<'static>) -> Value { return Value::String(format_numeric(value.value(), value.scale())); } if let ColumnData::Binary(Some(value)) = cell { - return Value::String(BASE64.encode(value.as_ref())); + return json!({"binary": BASE64.encode(value.as_ref())}); } if let ColumnData::String(Some(Cow::Borrowed(value))) = cell { return Value::String((*value).to_string()); From 8ec845a3a03217750cbc7a920e628a6508d04aec Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 10 Aug 2026 12:15:04 +0800 Subject: [PATCH 3/6] fix(database): harden metadata and workspace states --- .../Application/DatabaseFeatureModel.swift | 15 +++ .../Services/DatabaseSidecarService.swift | 42 ++++-- Tests/LitheTests/LitheCoreLogicTests.swift | 123 ++++++++++++++++++ rust/lithe-db-sidecar/src/mongodb_adapter.rs | 48 ++++--- 4 files changed, 201 insertions(+), 27 deletions(-) diff --git a/Sources/Lithe/Application/DatabaseFeatureModel.swift b/Sources/Lithe/Application/DatabaseFeatureModel.swift index 472a810971..cbc8ff70cd 100644 --- a/Sources/Lithe/Application/DatabaseFeatureModel.swift +++ b/Sources/Lithe/Application/DatabaseFeatureModel.swift @@ -944,6 +944,13 @@ final class DatabaseFeatureModel: ObservableObject { return } let analysis = DatabaseSQLAnalyzer.analyze(tab.sql) + updateSQLTab(tabID) { tab in + tab.errorMessage = nil + tab.result = nil + tab.resultColumns = [] + tab.rowsAffected = nil + tab.execution = nil + } guard analysis.canExecute else { updateSQLTab(tabID) { $0.errorMessage = analysis.warning } return @@ -1152,6 +1159,7 @@ final class DatabaseFeatureModel: ObservableObject { let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "GET \(key)", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: 1, rowsAffected: nil, errorMessage: nil)) guard isCurrent(profileID: profile.id, generation: generation) else { return } + setConnectionStatus(.connected, for: profile.id) redisSelectedKey = detail } catch { let sanitizedError = executionError(error) @@ -1233,6 +1241,7 @@ final class DatabaseFeatureModel: ObservableObject { appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: nil, rowsAffected: nil, errorMessage: nil)) appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "redis", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: true, errorMessage: nil)) guard isCurrent(profileID: profile.id, generation: generation) else { return true } + setConnectionStatus(.connected, for: profile.id) await afterSuccess() isLoading = false return true @@ -1243,6 +1252,7 @@ final class DatabaseFeatureModel: ObservableObject { appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "redis", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) if isCurrent(profileID: profile.id, generation: generation) { errorMessage = sanitizedError + setConnectionStatus(.failed, for: profile.id) isLoading = false } return false @@ -1294,6 +1304,7 @@ final class DatabaseFeatureModel: ObservableObject { let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "GET CONFIG \(group)/\(dataId)", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: 1, rowsAffected: nil, errorMessage: nil)) guard isCurrent(profileID: profile.id, generation: generation) else { return } + setConnectionStatus(.connected, for: profile.id) nacosSelectedConfig = detail } catch { let sanitizedError = executionError(error) @@ -1370,6 +1381,7 @@ final class DatabaseFeatureModel: ObservableObject { let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST INSTANCES", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: items.count, rowsAffected: nil, errorMessage: nil)) guard isCurrent(profileID: profile.id, generation: generation) else { return } + setConnectionStatus(.connected, for: profile.id) nacosInstances = items } catch { let sanitizedError = executionError(error) @@ -1377,6 +1389,7 @@ final class DatabaseFeatureModel: ObservableObject { appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST INSTANCES", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) guard isCurrent(profileID: profile.id, generation: generation) else { return } errorMessage = sanitizedError + setConnectionStatus(.failed, for: profile.id) } if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } } @@ -1398,6 +1411,7 @@ final class DatabaseFeatureModel: ObservableObject { appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: nil, rowsAffected: nil, errorMessage: nil)) appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "nacos", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: true, errorMessage: nil)) guard isCurrent(profileID: profile.id, generation: generation) else { return true } + setConnectionStatus(.connected, for: profile.id) await afterSuccess() isLoading = false return true @@ -1408,6 +1422,7 @@ final class DatabaseFeatureModel: ObservableObject { appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "nacos", summary: summary, createdAt: Date(), recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) if isCurrent(profileID: profile.id, generation: generation) { errorMessage = sanitizedError + setConnectionStatus(.failed, for: profile.id) isLoading = false } return false diff --git a/Sources/Lithe/Services/DatabaseSidecarService.swift b/Sources/Lithe/Services/DatabaseSidecarService.swift index 57d4cc0b64..eb88e5e292 100644 --- a/Sources/Lithe/Services/DatabaseSidecarService.swift +++ b/Sources/Lithe/Services/DatabaseSidecarService.swift @@ -415,11 +415,18 @@ enum DatabaseSidecarError: LocalizedError, Equatable { var errorDescription: String? { switch self { case .executableNotFound: return "The Lithe database helper is not installed." - case let .processFailed(exitCode, output): return "The database helper exited with code \(exitCode): \(output)" - case let .invalidResponse(message): return "The database helper returned invalid JSON: \(message)" - case let .requestFailed(code, message): return "Database request failed (\(code)): \(message)" + case let .processFailed(exitCode, output): return "The database helper exited with code \(exitCode): \(Self.bounded(output))" + case let .invalidResponse(message): return "The database helper returned invalid JSON: \(Self.bounded(message))" + case let .requestFailed(code, message): return "Database request failed (\(code)): \(Self.bounded(message))" } } + + private static func bounded(_ value: String) -> String { + let normalized = value + .replacingOccurrences(of: "\n", with: " ") + .trimmingCharacters(in: .whitespacesAndNewlines) + return normalized.count > 500 ? "\(normalized.prefix(497))..." : normalized + } } /// Executes the independently packaged database core only on demand. Connection @@ -448,23 +455,28 @@ final class DatabaseSidecarService: DatabaseOperations, @unchecked Sendable { } func listTables(connection: DatabaseConnection, schema: String = "") throws -> [DatabaseRow] { - try request(method: "listTables", params: TableParams(connection: connection, schema: schema)) + let result: DatabaseRowsResult = try request(method: "listTables", params: TableParams(connection: connection, schema: schema)) + return result.rows } func describeTable(connection: DatabaseConnection, schema: String = "", table: String) throws -> [DatabaseRow] { - try request(method: "describeTable", params: TableParams(connection: connection, schema: schema, table: table)) + let result: DatabaseRowsResult = try request(method: "describeTable", params: TableParams(connection: connection, schema: schema, table: table)) + return result.rows } func listIndexes(connection: DatabaseConnection, schema: String = "", table: String) throws -> [DatabaseRow] { - try request(method: "listIndexes", params: TableParams(connection: connection, schema: schema, table: table)) + let result: DatabaseRowsResult = try request(method: "listIndexes", params: TableParams(connection: connection, schema: schema, table: table)) + return result.rows } func listForeignKeys(connection: DatabaseConnection, schema: String = "", table: String) throws -> [DatabaseRow] { - try request(method: "listForeignKeys", params: TableParams(connection: connection, schema: schema, table: table)) + let result: DatabaseRowsResult = try request(method: "listForeignKeys", params: TableParams(connection: connection, schema: schema, table: table)) + return result.rows } func listObjects(connection: DatabaseConnection, schema: String = "", kind: DatabaseObjectKind) throws -> [DatabaseRow] { - try request(method: "listObjects", params: ObjectParams(connection: connection, schema: schema, objectKind: kind.rawValue)) + let result: DatabaseRowsResult = try request(method: "listObjects", params: ObjectParams(connection: connection, schema: schema, objectKind: kind.rawValue)) + return result.rows } func pageTable(connection: DatabaseConnection, schema: String = "", table: String, limit: Int = 200, offset: Int = 0, filters: [DatabaseFilter] = [], sort: [DatabaseSort] = []) throws -> DatabaseQueryResult { @@ -657,6 +669,20 @@ private struct EmptyParams: Codable {} private struct ConnectionParams: Codable { let connection: DatabaseConnection } private struct ConnectedResult: Codable { let connected: Bool } private struct EmptyResult: Codable {} +private struct DatabaseRowsResult: Decodable { + let rows: [DatabaseRow] + + init(from decoder: Decoder) throws { + if let rows = try? decoder.singleValueContainer().decode([DatabaseRow].self) { + self.rows = rows + return + } + let container = try decoder.container(keyedBy: CodingKeys.self) + rows = try container.decode([DatabaseRow].self, forKey: .rows) + } + + private enum CodingKeys: String, CodingKey { case rows } +} private struct ExportResult: Codable { let encoding: String; let data: String } private struct ExplainResult: Codable { let format: String; let rows: [DatabaseRow]; let truncated: Bool } private struct DiagnosticsResult: Codable { let rows: [DatabaseRow]; let truncated: Bool } diff --git a/Tests/LitheTests/LitheCoreLogicTests.swift b/Tests/LitheTests/LitheCoreLogicTests.swift index 2bc5352353..054d839bac 100644 --- a/Tests/LitheTests/LitheCoreLogicTests.swift +++ b/Tests/LitheTests/LitheCoreLogicTests.swift @@ -93,6 +93,38 @@ struct LitheCoreLogicTests { #expect(request.contains(#""includeSize":false"#)) } + @Test + func databaseSidecarDecodesLegacyMongoMetadataRowsEnvelope() throws { + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let result: String + switch method { + case "listTables": result = #"{"rows":[{"table_name":"events","table_type":"collection"}],"truncated":false}"# + case "describeTable": result = #"{"rows":[{"column_name":"_id","data_type":"objectId"}],"truncated":false}"# + case "listIndexes": result = #"{"rows":[{"index_name":"_id_","definition":"{\"_id\":1}"}],"truncated":false}"# + case "listForeignKeys": result = #"{"rows":[],"truncated":false}"# + case "listObjects": result = #"{"rows":[{"object_name":"events","object_kind":"collection"}],"truncated":false}"# + default: result = "[]" + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":\#(result)}"#, exitCode: 0) + } + let service = DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")) + let mongo = DatabaseConnection(kind: .mongodb, host: "127.0.0.1", port: 27017, database: "lithe_test") + func stringValue(_ row: DatabaseRow?, _ key: String) -> String? { + guard case let .string(value) = row?[key] else { return nil } + return value + } + + #expect(stringValue(try service.listTables(connection: mongo).first, "table_name") == "events") + #expect(stringValue(try service.describeTable(connection: mongo, table: "events").first, "column_name") == "_id") + #expect(stringValue(try service.listIndexes(connection: mongo, table: "events").first, "index_name") == "_id_") + #expect((try service.listForeignKeys(connection: mongo, table: "events")).isEmpty) + #expect(stringValue(try service.listObjects(connection: mongo, kind: DatabaseObjectKind.tables).first, "object_name") == "events") + } + @Test func databaseSidecarMapsFailedProcessToStableError() { let runner = RecordingProcessRunner(result: ProcessResult(output: "connection store failed", exitCode: 2)) @@ -106,6 +138,15 @@ struct LitheCoreLogicTests { } } + @Test + func databaseSidecarErrorsAreSingleLineAndBounded() { + let error = DatabaseSidecarError.requestFailed(code: "database_error", message: String(repeating: "x", count: 800) + "\nnext line") + let description = error.localizedDescription + #expect(description.count <= 500 + "Database request failed (database_error): ".count) + #expect(!description.contains("\n")) + #expect(description.hasSuffix("...")) + } + @Test func databaseProfilesKeepPasswordsOutOfPreferences() throws { let preferences = DatabaseTestKeyValueStore() @@ -437,6 +478,76 @@ struct LitheCoreLogicTests { #expect(store.load().first?.database == "beta") } + @Test + @MainActor + func databaseInvalidSQLClearsPreviousExecutionState() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "SQLite", kind: .sqlite, path: "/tmp/lithe-test.sqlite") + try store.save([profile]) + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let result: String + if method == "query" { + result = #"{"rows":[{"value":1}],"columns":["value"],"truncated":false}"# + } else { + result = "[]" + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":\#(result)}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + feature.addSQLTab(sql: "SELECT 1") + let tabID = try #require(feature.selectedSQLTabID) + await feature.runSQL(in: tabID) + #expect(feature.selectedSQLTab?.result?.rows.count == 1) + #expect(feature.selectedSQLTab?.execution != nil) + + feature.updateSQL("SELEC 1", in: tabID) + await feature.runSQL(in: tabID) + #expect(feature.selectedSQLTab?.result == nil) + #expect(feature.selectedSQLTab?.execution == nil) + #expect(feature.selectedSQLTab?.rowsAffected == nil) + #expect(feature.selectedSQLTab?.errorMessage != nil) + } + + @Test + @MainActor + func databaseRedisStatusRecoversAfterSuccessfulKeyLoad() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "Redis", kind: .redis, host: "127.0.0.1", port: 6379, database: "0") + try store.save([profile]) + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + if method == "redisScan" { + return ProcessResult(output: #"{"id":"\#(id)","ok":false,"error":{"code":"redis_error","message":"NOAUTH"}}"#, exitCode: 0) + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"key":"session:42","type":"string","ttl":60,"size":9,"stringValue":"ready","hashEntries":[]}}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + await feature.loadRedisKeys(pattern: "*") + #expect(feature.connectionStatus(for: profile) == .failed) + await feature.loadRedisKey("session:42") + #expect(feature.connectionStatus(for: profile) == .connected) + #expect(feature.redisSelectedKey?.stringValue == "ready") + } + @Test @MainActor func databaseConnectionStatusTracksSuccessfulConnection() async throws { @@ -566,6 +677,18 @@ struct LitheCoreLogicTests { #expect(result.rows.first?["z_col"] == .integer(1)) } + @Test + func databaseMongoQueryFixtureDecodesExtendedJSONWithoutLosingDocuments() throws { + let data = Data(#"{"rows":[{"_id":{"$oid":"507f1f77bcf86cd799439011"},"empty":"","null":null,"nested":{"base64":"AAEC"},"array":[1,{"$date":"2024-01-01T00:00:00Z"}],"binary":{"$binary":{"base64":"AAEC","subType":"00"}}}],"truncated":false}"#.utf8) + let result = try JSONDecoder().decode(DatabaseQueryResult.self, from: data) + let row = try #require(result.rows.first) + #expect(row["empty"] == .string("")) + #expect(row["null"] == .null) + #expect(row["_id"] == .object(["$oid": .string("507f1f77bcf86cd799439011")])) + #expect(row["nested"] == .object(["base64": .string("AAEC")])) + #expect(row["binary"] == .object(["$binary": .object(["base64": .string("AAEC"), "subType": .string("00")])])) + } + @Test func databaseValuePreservesTaggedDecimalAndBinaryValues() throws { let data = Data(#"[{"decimal":"0.00"},{"binary":"AAEC"}]"#.utf8) diff --git a/rust/lithe-db-sidecar/src/mongodb_adapter.rs b/rust/lithe-db-sidecar/src/mongodb_adapter.rs index d2128cc15b..30f444d490 100644 --- a/rust/lithe-db-sidecar/src/mongodb_adapter.rs +++ b/rust/lithe-db-sidecar/src/mongodb_adapter.rs @@ -39,24 +39,30 @@ pub(super) async fn method(method: &str, params: Params) -> DbResult { .list_collection_names() .await .map_err(driver_error)?; - Ok( - json!({"rows": names.into_iter().map(|name| json!({"table_name": name, "table_type": "collection"})).collect::>(), "truncated": false}), - ) + Ok(Value::Array( + names + .into_iter() + .map(|name| json!({"table_name": name, "table_type": "collection"})) + .collect(), + )) } "describeTable" => describe_collection(&database, ¶ms.table).await, "listIndexes" => list_indexes(&database, ¶ms.table).await, - "listForeignKeys" => Ok(json!({"rows": [], "truncated": false})), + "listForeignKeys" => Ok(Value::Array(Vec::new())), "listObjects" => { if !params.object_kind.is_empty() && params.object_kind != "tables" { - return Ok(json!({"rows": [], "truncated": false})); + return Ok(Value::Array(Vec::new())); } let names = database .list_collection_names() .await .map_err(driver_error)?; - Ok( - json!({"rows": names.into_iter().map(|name| json!({"object_name": name, "object_kind": "collection"})).collect::>(), "truncated": false}), - ) + Ok(Value::Array( + names + .into_iter() + .map(|name| json!({"object_name": name, "object_kind": "collection"})) + .collect(), + )) } "pageTable" => page_collection(&database, ¶ms).await, "query" => find_json(&database, ¶ms).await, @@ -168,16 +174,20 @@ async fn describe_collection(database: &mongodb::Database, collection_name: &str if fields.is_empty() { fields.insert("_id".into(), "objectId".into()); } - Ok(json!({ - "rows": fields.into_iter().map(|(name, data_type)| json!({ - "column_name": name, - "data_type": data_type, - "is_nullable": "YES", - "column_default": Value::Null, - "column_key": if name == "_id" { "PRI" } else { "" } - })).collect::>(), - "truncated": false - })) + Ok(Value::Array( + fields + .into_iter() + .map(|(name, data_type)| { + json!({ + "column_name": name, + "data_type": data_type, + "is_nullable": "YES", + "column_default": Value::Null, + "column_key": if name == "_id" { "PRI" } else { "" } + }) + }) + .collect(), + )) } async fn list_indexes(database: &mongodb::Database, collection_name: &str) -> DbResult { @@ -187,7 +197,7 @@ async fn list_indexes(database: &mongodb::Database, collection_name: &str) -> Db while let Some(index) = cursor.try_next().await.map_err(driver_error)? { rows.push(index_json(index)); } - Ok(json!({"rows": rows, "truncated": false})) + Ok(Value::Array(rows)) } fn index_json(index: IndexModel) -> Value { From b1d1cb02cbd9e1acbc67e1fc776c899c253d0c98 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 10 Aug 2026 12:29:20 +0800 Subject: [PATCH 4/6] fix(database): harden value rendering and refresh state --- .../Application/DatabaseFeatureModel.swift | 86 +++++++++++++++---- .../Services/DatabaseSidecarService.swift | 22 +++++ .../Views/DatabaseSQLWorkspaceView.swift | 29 +------ Sources/Lithe/Views/DatabaseSidebarView.swift | 22 ++++- Sources/Lithe/Views/DatabaseTableView.swift | 29 +------ Tests/LitheTests/LitheCoreLogicTests.swift | 41 +++++++++ rust/lithe-db-sidecar/src/main.rs | 37 ++++++++ 7 files changed, 192 insertions(+), 74 deletions(-) diff --git a/Sources/Lithe/Application/DatabaseFeatureModel.swift b/Sources/Lithe/Application/DatabaseFeatureModel.swift index cbc8ff70cd..d2218984a7 100644 --- a/Sources/Lithe/Application/DatabaseFeatureModel.swift +++ b/Sources/Lithe/Application/DatabaseFeatureModel.swift @@ -67,6 +67,12 @@ final class DatabaseFeatureModel: ObservableObject { private var backupTimer: Timer? private var profileGeneration: UInt64 = 0 private var tableRequestID: UUID? + private var redisScanRequestID: UUID? + private var redisDetailRequestID: UUID? + private var nacosConfigListRequestID: UUID? + private var nacosConfigDetailRequestID: UUID? + private var nacosServiceListRequestID: UUID? + private var nacosInstanceRequestID: UUID? // Keep the unmasked page separate so primary-key mutations and exports never // accidentally persist the display placeholder. private var sourceRows: [DatabaseRow] = [] @@ -397,6 +403,7 @@ final class DatabaseFeatureModel: ObservableObject { let generation = profileGeneration isLoading = true errorMessage = nil + setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) let rows = try await Task.detached { [operations] in @@ -404,11 +411,13 @@ final class DatabaseFeatureModel: ObservableObject { }.value guard isCurrent(profileID: profile.id, generation: generation) else { return } databaseOptions = rows + setConnectionStatus(.connected, for: profile.id) isLoading = false } catch { if isCurrent(profileID: profile.id, generation: generation) { databaseOptions = [] errorMessage = executionError(error) + setConnectionStatus(.failed, for: profile.id) isLoading = false } } @@ -1118,10 +1127,18 @@ final class DatabaseFeatureModel: ObservableObject { let generation = profileGeneration let cursor = reset ? "0" : redisNextCursor if !reset && cursor == "0" { return } + let requestID = UUID() + redisScanRequestID = requestID let startedAt = Date() let includeSize = redisIncludeSize isLoading = true errorMessage = nil + if reset { + redisKeys = [] + redisNextCursor = "0" + redisSelectedKey = nil + redisDetailRequestID = nil + } setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) @@ -1130,7 +1147,7 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "SCAN", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.keys.count, rowsAffected: nil, errorMessage: nil)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), redisScanRequestID == requestID else { return } setConnectionStatus(.connected, for: profile.id) redisKeys = reset ? result.keys : Array(Dictionary(grouping: redisKeys + result.keys, by: \.key).compactMap { $0.value.first }) redisNextCursor = result.nextCursor @@ -1138,19 +1155,22 @@ final class DatabaseFeatureModel: ObservableObject { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "SCAN", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), redisScanRequestID == requestID else { return } errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), redisScanRequestID == requestID { isLoading = false } } func loadRedisKey(_ key: String) async { guard let profile = selectedProfile, profile.kind == .redis else { return } let generation = profileGeneration + let requestID = UUID() + redisDetailRequestID = requestID let startedAt = Date() isLoading = true errorMessage = nil + redisSelectedKey = nil do { let connection = connection(profile) let detail = try await Task.detached { [operations] in @@ -1158,18 +1178,18 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "GET \(key)", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: 1, rowsAffected: nil, errorMessage: nil)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), redisDetailRequestID == requestID else { return } setConnectionStatus(.connected, for: profile.id) redisSelectedKey = detail } catch { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "GET \(key)", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), redisDetailRequestID == requestID else { return } errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), redisDetailRequestID == requestID { isLoading = false } } func saveRedisString(key: String, value: String, ttl: Int64?, confirmed: Bool) async -> Bool { @@ -1264,9 +1284,15 @@ final class DatabaseFeatureModel: ObservableObject { func loadNacosConfigs(dataId: String, group: String, page: Int = 1) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } let generation = profileGeneration + let requestID = UUID() + nacosConfigListRequestID = requestID let startedAt = Date() isLoading = true errorMessage = nil + if page == 1 { + nacosConfigs = [] + nacosConfigTotalCount = 0 + } setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) @@ -1275,7 +1301,7 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST CONFIGS", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.items.count, rowsAffected: nil, errorMessage: nil)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosConfigListRequestID == requestID else { return } setConnectionStatus(.connected, for: profile.id) nacosConfigs = result.items nacosConfigTotalCount = result.totalCount @@ -1283,19 +1309,22 @@ final class DatabaseFeatureModel: ObservableObject { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST CONFIGS", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosConfigListRequestID == requestID else { return } errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), nacosConfigListRequestID == requestID { isLoading = false } } func loadNacosConfig(dataId: String, group: String) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } let generation = profileGeneration + let requestID = UUID() + nacosConfigDetailRequestID = requestID let startedAt = Date() isLoading = true errorMessage = nil + nacosSelectedConfig = nil do { let connection = connection(profile) let detail = try await Task.detached { [operations] in @@ -1303,18 +1332,18 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "GET CONFIG \(group)/\(dataId)", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: 1, rowsAffected: nil, errorMessage: nil)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosConfigDetailRequestID == requestID else { return } setConnectionStatus(.connected, for: profile.id) nacosSelectedConfig = detail } catch { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "GET CONFIG \(group)/\(dataId)", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosConfigDetailRequestID == requestID else { return } errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), nacosConfigDetailRequestID == requestID { isLoading = false } } func publishNacosConfig(dataId: String, group: String, content: String, type: String?, confirmed: Bool) async -> Bool { @@ -1341,9 +1370,15 @@ final class DatabaseFeatureModel: ObservableObject { func loadNacosServices(serviceName: String, group: String, page: Int = 1) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } let generation = profileGeneration + let requestID = UUID() + nacosServiceListRequestID = requestID let startedAt = Date() isLoading = true errorMessage = nil + if page == 1 { + nacosServices = [] + nacosServiceTotalCount = 0 + } setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) @@ -1352,7 +1387,7 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST SERVICES", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: result.items.count, rowsAffected: nil, errorMessage: nil)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosServiceListRequestID == requestID else { return } setConnectionStatus(.connected, for: profile.id) nacosServices = result.items nacosServiceTotalCount = result.totalCount @@ -1360,19 +1395,22 @@ final class DatabaseFeatureModel: ObservableObject { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST SERVICES", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosServiceListRequestID == requestID else { return } errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), nacosServiceListRequestID == requestID { isLoading = false } } func loadNacosInstances(serviceName: String, group: String) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } let generation = profileGeneration + let requestID = UUID() + nacosInstanceRequestID = requestID let startedAt = Date() isLoading = true errorMessage = nil + nacosInstances = [] do { let connection = connection(profile) let items = try await Task.detached { [operations] in @@ -1380,18 +1418,18 @@ final class DatabaseFeatureModel: ObservableObject { }.value let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST INSTANCES", startedAt: startedAt, durationMilliseconds: duration, status: .succeeded, rowsReturned: items.count, rowsAffected: nil, errorMessage: nil)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosInstanceRequestID == requestID else { return } setConnectionStatus(.connected, for: profile.id) nacosInstances = items } catch { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .nacos, operation: "LIST INSTANCES", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), nacosInstanceRequestID == requestID else { return } errorMessage = sanitizedError setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), nacosInstanceRequestID == requestID { isLoading = false } } private func performNacosWrite( @@ -1537,6 +1575,12 @@ final class DatabaseFeatureModel: ObservableObject { private func activateProfile(_ profile: DatabaseProfile) { profileGeneration &+= 1 tableRequestID = nil + redisScanRequestID = nil + redisDetailRequestID = nil + nacosConfigListRequestID = nil + nacosConfigDetailRequestID = nil + nacosServiceListRequestID = nil + nacosInstanceRequestID = nil selectedProfileID = profile.id selectedTable = nil openTableTabs = [] @@ -1566,6 +1610,12 @@ final class DatabaseFeatureModel: ObservableObject { private func clearProfileScopedState() { profileGeneration &+= 1 tableRequestID = nil + redisScanRequestID = nil + redisDetailRequestID = nil + nacosConfigListRequestID = nil + nacosConfigDetailRequestID = nil + nacosServiceListRequestID = nil + nacosInstanceRequestID = nil selectedProfileID = nil selectedTable = nil openTableTabs = [] diff --git a/Sources/Lithe/Services/DatabaseSidecarService.swift b/Sources/Lithe/Services/DatabaseSidecarService.swift index eb88e5e292..cffc6cc8d5 100644 --- a/Sources/Lithe/Services/DatabaseSidecarService.swift +++ b/Sources/Lithe/Services/DatabaseSidecarService.swift @@ -245,6 +245,28 @@ enum DatabaseValue: Codable, Equatable, Sendable { case let .array(value): try container.encode(value) } } + + /// A stable value representation for grids, details panels, and metadata. + /// Keeping this on the protocol value prevents an empty string from being + /// rendered like a missing value in one of the database workspaces. + var displayText: String { + switch self { + case .null: "NULL" + case let .bool(value): value ? "true" : "false" + case let .integer(value): String(value) + case let .number(value): String(value) + case let .decimal(value): value + case let .string(value): value.isEmpty ? "\"\"" : value + case let .binary(value): "Binary (\(value.count) bytes)" + case let .object(value): Self.jsonText(.object(value)) + case let .array(value): Self.jsonText(.array(value)) + } + } + + private static func jsonText(_ value: DatabaseValue) -> String { + guard let data = try? JSONEncoder().encode(value) else { return String(describing: value) } + return String(decoding: data, as: UTF8.self) + } } typealias DatabaseRow = [String: DatabaseValue] diff --git a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift index 2bb480706c..52867cb053 100644 --- a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift +++ b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift @@ -728,25 +728,10 @@ private struct DatabaseQueryResultGrid: View { } private func display(_ value: DatabaseValue?) -> String { - switch value { - case nil, .null: "NULL" - case let .string(value): value.isEmpty ? "\"\"" : value - case let .integer(value): String(value) - case let .number(value): String(value) - case let .decimal(value): value - case let .bool(value): value ? "true" : "false" - case let .binary(value): "Binary (\(value.count) bytes)" - case let .object(value): databaseSQLJSONText(.object(value)) - case let .array(value): databaseSQLJSONText(.array(value)) - } + value?.displayText ?? "NULL" } } -private func databaseSQLJSONText(_ value: DatabaseValue) -> String { - guard let data = try? JSONEncoder().encode(value) else { return String(describing: value) } - return String(decoding: data, as: UTF8.self) -} - private struct DatabaseStructureView: View { @EnvironmentObject private var model: AppModel @State private var editor: DatabaseSchemaEditorKind? @@ -850,17 +835,7 @@ private struct DatabaseStructureView: View { } private func display(_ value: DatabaseValue) -> String { - switch value { - case .null: "NULL" - case let .string(value): value - case let .integer(value): String(value) - case let .number(value): String(value) - case let .decimal(value): value - case let .bool(value): value ? "true" : "false" - case let .binary(value): "Binary (\(value.count) bytes)" - case let .object(value): String(describing: value) - case let .array(value): String(describing: value) - } + value.displayText } } diff --git a/Sources/Lithe/Views/DatabaseSidebarView.swift b/Sources/Lithe/Views/DatabaseSidebarView.swift index 445b6e317f..f17b6617bc 100644 --- a/Sources/Lithe/Views/DatabaseSidebarView.swift +++ b/Sources/Lithe/Views/DatabaseSidebarView.swift @@ -1230,7 +1230,7 @@ struct DatabaseSidebarView: View { } return row.keys.sorted().compactMap { key in guard let value = row[key] else { return nil } - return "\(key): \(String(describing: value))" + return "\(key): \(value.displayText)" }.joined(separator: " ") } } @@ -1764,6 +1764,11 @@ struct DatabaseConnectionEditor: View { let digitsOnly = value.filter(\.isNumber) if digitsOnly != value { database = digitsOnly } } + if let redisDatabaseValidationMessage { + Text(redisDatabaseValidationMessage) + .font(.system(size: 10.5)) + .foregroundStyle(LitheTheme.error) + } Text("Leave the database index at 0 for the standard Redis database.") .font(.system(size: 10.5)) .foregroundStyle(LitheTheme.secondaryText) @@ -1822,7 +1827,7 @@ struct DatabaseConnectionEditor: View { .buttonStyle(LitheSecondaryButtonStyle()) Button("Connect") { connect() } .buttonStyle(LithePrimaryButtonStyle()) - .disabled(name.isEmpty || (kind == .sqlite ? path.isEmpty : host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) || model.databaseFeature.isLoading) + .disabled(name.isEmpty || (kind == .sqlite ? path.isEmpty : host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) || redisDatabaseValidationMessage != nil || model.databaseFeature.isLoading) } .padding(.horizontal, 16) .frame(height: 58) @@ -1850,6 +1855,10 @@ struct DatabaseConnectionEditor: View { } private func connect() { + if let redisDatabaseValidationMessage { + model.databaseFeature.errorMessage = redisDatabaseValidationMessage + return + } let candidate = DatabaseProfile(id: profile?.id ?? UUID(), name: name, kind: kind, host: host, port: UInt16(port) ?? 0, username: username, database: database, path: path, ssl: ssl, group: "", folderID: folderID, colorHex: colorHex, readOnly: readOnly, productionProtection: productionProtection, maskSensitiveFields: maskSensitiveFields, sensitiveColumnPatterns: sensitiveColumnPatterns.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }, caCertificatePath: ssl ? caCertificatePath : "", serverName: ssl ? serverName : "", sshHost: usesSSHTunnel ? sshHost : "", sshPort: usesSSHTunnel ? (UInt16(sshPort) ?? 22) : 0, sshUsername: usesSSHTunnel ? sshUsername : "", sshKeyPath: usesSSHTunnel ? sshKeyPath : "", sshLocalPort: usesSSHTunnel ? (UInt16(sshLocalPort) ?? 0) : 0, proxyURL: usesSSHTunnel ? proxyURL : "") Task { let saved = if profile == nil { @@ -1860,4 +1869,13 @@ struct DatabaseConnectionEditor: View { if saved { isPresented = false } } } + + private var redisDatabaseValidationMessage: String? { + guard kind == .redis else { return nil } + let value = database.trimmingCharacters(in: .whitespacesAndNewlines) + guard value.isEmpty || UInt32(value) != nil else { + return "Redis database index must be between 0 and 4294967295." + } + return nil + } } diff --git a/Sources/Lithe/Views/DatabaseTableView.swift b/Sources/Lithe/Views/DatabaseTableView.swift index 45634b14c3..320d977e1a 100644 --- a/Sources/Lithe/Views/DatabaseTableView.swift +++ b/Sources/Lithe/Views/DatabaseTableView.swift @@ -709,17 +709,7 @@ struct DatabaseTableView: View { } private func display(_ value: DatabaseValue?) -> String { - switch value { - case nil, .null: "NULL" - case let .string(value): value.isEmpty ? "\"\"" : value - case let .integer(value): String(value) - case let .number(value): String(value) - case let .decimal(value): value - case let .bool(value): value ? "true" : "false" - case let .binary(value): "Binary (\(value.count) bytes)" - case let .object(value): databaseJSONText(.object(value)) - case let .array(value): databaseJSONText(.array(value)) - } + value?.displayText ?? "NULL" } private func metadataLabel(_ row: DatabaseRow) -> String { @@ -1211,25 +1201,10 @@ private struct DatabaseRowDetailsSheet: View { } private func valueText(_ value: DatabaseValue?) -> String { - switch value { - case nil, .null: "NULL" - case let .string(value): value - case let .integer(value): String(value) - case let .number(value): String(value) - case let .decimal(value): value - case let .bool(value): value ? "true" : "false" - case let .binary(value): "Binary (\(value.count) bytes)" - case let .object(value): databaseJSONText(.object(value)) - case let .array(value): databaseJSONText(.array(value)) - } + value?.displayText ?? "NULL" } } -private func databaseJSONText(_ value: DatabaseValue) -> String { - guard let data = try? JSONEncoder().encode(value) else { return String(describing: value) } - return String(decoding: data, as: UTF8.self) -} - private struct DatabaseReplaceSheet: View { @Environment(\.dismiss) private var dismiss let columns: [String] diff --git a/Tests/LitheTests/LitheCoreLogicTests.swift b/Tests/LitheTests/LitheCoreLogicTests.swift index 054d839bac..d337c1a01e 100644 --- a/Tests/LitheTests/LitheCoreLogicTests.swift +++ b/Tests/LitheTests/LitheCoreLogicTests.swift @@ -147,6 +147,14 @@ struct LitheCoreLogicTests { #expect(description.hasSuffix("...")) } + @Test + func databaseValueDisplayKeepsNullAndEmptyStringDistinct() { + #expect(DatabaseValue.null.displayText == "NULL") + #expect(DatabaseValue.string("").displayText == "\"\"") + #expect(DatabaseValue.string("NULL").displayText == "NULL") + #expect(DatabaseValue.object(["empty": .string("")]).displayText == #"{"empty":""}"#) + } + @Test func databaseProfilesKeepPasswordsOutOfPreferences() throws { let preferences = DatabaseTestKeyValueStore() @@ -471,6 +479,7 @@ struct LitheCoreLogicTests { await feature.select(profile) #expect(feature.databaseOptions == ["alpha", "beta"]) + #expect(feature.connectionStatus(for: profile) == .connected) await feature.selectDatabase("beta", for: profile) #expect(feature.selectedProfile?.database == "beta") @@ -548,6 +557,38 @@ struct LitheCoreLogicTests { #expect(feature.redisSelectedKey?.stringValue == "ready") } + @Test + @MainActor + func databaseRedisRescanFailureDoesNotLeaveOldKeysVisible() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "Redis", kind: .redis, host: "127.0.0.1", port: 6379, database: "0") + try store.save([profile]) + let calls = TestCounter() + let runner = RecordingProcessRunner { request in + calls.value += 1 + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + if calls.value == 1 { + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"keys":[{"key":"session:42","type":"string","ttl":60,"size":9}],"nextCursor":"0"}}"#, exitCode: 0) + } + return ProcessResult(output: #"{"id":"\#(id)","ok":false,"error":{"code":"redis_error","message":"NOAUTH"}}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + await feature.loadRedisKeys(pattern: "*") + #expect(feature.redisKeys.map(\.key) == ["session:42"]) + await feature.loadRedisKeys(pattern: "*") + #expect(feature.redisKeys.isEmpty) + #expect(feature.errorMessage?.contains("NOAUTH") == true) + #expect(feature.connectionStatus(for: profile) == .failed) + } + @Test @MainActor func databaseConnectionStatusTracksSuccessfulConnection() async throws { diff --git a/rust/lithe-db-sidecar/src/main.rs b/rust/lithe-db-sidecar/src/main.rs index b9040c303d..4acca41ef8 100644 --- a/rust/lithe-db-sidecar/src/main.rs +++ b/rust/lithe-db-sidecar/src/main.rs @@ -2449,6 +2449,10 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { "DATETIME" => row .try_get::(index) .map(|v| Value::String(v.to_string())) + .or_else(|_| { + row.try_get::, _>(index) + .map(|v| Value::String(v.to_rfc3339())) + }) .unwrap_or_else(|_| mysql_text(row, index)), "TIMESTAMP" => row .try_get::, _>(index) @@ -2457,11 +2461,17 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { row.try_get::(index) .map(|v| Value::String(v.to_string())) }) + .or_else(|_| { + row.try_get::, _>(index) + .map(|v| Value::String(v.to_rfc3339())) + }) .unwrap_or_else(|_| mysql_text(row, index)), "BOOLEAN" | "BOOL" => row .try_get::(index) .map(Value::Bool) .or_else(|_| row.try_get::(index).map(|v| Value::Bool(v != 0))) + .or_else(|_| row.try_get::(index).map(|v| Value::Bool(v != 0))) + .or_else(|_| row.try_get::(index).map(|v| Value::Bool(v != 0))) .unwrap_or_else(|_| mysql_text(row, index)), "JSON" => row .try_get::(index) @@ -2478,7 +2488,9 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { .try_get::(index) .map(|v| json!(v)) .or_else(|_| row.try_get::(index).map(|v| json!(v))) + .or_else(|_| row.try_get::(index).map(|v| json!(v))) .or_else(|_| row.try_get::(index).map(|v| json!(v))) + .or_else(|_| row.try_get::(index).map(|v| json!(v))) .unwrap_or_else(|_| mysql_text(row, index)), value if value.contains("INT") || value == "YEAR" => row .try_get::(index) @@ -2491,9 +2503,28 @@ fn mysql_value(row: &MySqlRow, index: usize, kind: &str) -> Value { fn mysql_text(row: &MySqlRow, index: usize) -> Value { row.try_get::(index) .map(Value::String) + .or_else(|_| row.try_get_unchecked::(index).map(Value::String)) + .or_else(|_| { + row.try_get::, _>(index) + .map(|value| mysql_bytes_value(&value)) + }) + .or_else(|_| { + row.try_get_unchecked::, _>(index) + .map(|value| mysql_bytes_value(&value)) + }) + .or_else(|_| row.try_get::(index).map(|value| json!(value))) + .or_else(|_| row.try_get::(index).map(|value| json!(value))) + .or_else(|_| row.try_get::(index).map(|value| json!(value))) .unwrap_or_else(|_| Value::String("".into())) } +fn mysql_bytes_value(value: &[u8]) -> Value { + match String::from_utf8(value.to_vec()) { + Ok(text) => Value::String(text), + Err(_) => tagged_binary(value), + } +} + fn postgres_value(row: &PgRow, index: usize, kind: &str) -> Value { match kind.to_ascii_uppercase().as_str() { "NUMERIC" => row @@ -4098,6 +4129,12 @@ mod tests { assert_eq!(binary_input(mixed.as_object().unwrap()), None); } + #[test] + fn mysql_text_fallback_preserves_utf8_names_and_binary_payloads() { + assert_eq!(mysql_bytes_value(b"analytics"), json!("analytics")); + assert_eq!(mysql_bytes_value(&[0, 255]), json!({"binary":"AP8="})); + } + #[test] fn restore_drops_existing_objects_before_replaying_snapshot() { assert_eq!( From c9d001312146c30b53000481333aad721721dd03 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 10 Aug 2026 13:33:42 +0800 Subject: [PATCH 5/6] test(database): add local validation compose --- docker/database-validation/compose.yaml | 86 +++++++++++ docker/database-validation/mariadb-init.sql | 35 +++++ docker/database-validation/mongodb-init.js | 32 ++++ docker/database-validation/redis-seed.sh | 13 ++ rust/lithe-db-sidecar/src/mongodb_adapter.rs | 139 ++++++++++++++---- scripts/database-validation-smoke.sh | 146 +++++++++++++++++++ 6 files changed, 422 insertions(+), 29 deletions(-) create mode 100644 docker/database-validation/compose.yaml create mode 100644 docker/database-validation/mariadb-init.sql create mode 100644 docker/database-validation/mongodb-init.js create mode 100755 docker/database-validation/redis-seed.sh create mode 100755 scripts/database-validation-smoke.sh diff --git a/docker/database-validation/compose.yaml b/docker/database-validation/compose.yaml new file mode 100644 index 0000000000..40abed4e78 --- /dev/null +++ b/docker/database-validation/compose.yaml @@ -0,0 +1,86 @@ +name: lithe-database-validation + +services: + mariadb: + image: mariadb:11.4 + container_name: lithe-database-validation-mariadb + restart: unless-stopped + ports: + - "${LITHE_BIND_ADDRESS:-127.0.0.1}:${LITHE_MARIADB_PORT:-53307}:3306" + environment: + MARIADB_ROOT_PASSWORD: "${LITHE_DB_PASSWORD:-lithe_root}" + MARIADB_DATABASE: lithe_test + volumes: + - mariadb-data:/var/lib/mysql + - ./mariadb-init.sql:/docker-entrypoint-initdb.d/001-validation.sql:ro + healthcheck: + test: + - CMD-SHELL + - mariadb-admin ping -h 127.0.0.1 -uroot -p"$$MARIADB_ROOT_PASSWORD" --silent + interval: 5s + timeout: 5s + retries: 30 + start_period: 20s + + mongodb: + image: mongo:7.0 + container_name: lithe-database-validation-mongodb + restart: unless-stopped + ports: + - "${LITHE_BIND_ADDRESS:-127.0.0.1}:${LITHE_MONGODB_PORT:-57019}:27017" + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: "${LITHE_DB_PASSWORD:-lithe_root}" + MONGO_INITDB_DATABASE: lithe_test + volumes: + - mongodb-data:/data/db + - ./mongodb-init.js:/docker-entrypoint-initdb.d/001-validation.js:ro + healthcheck: + test: + - CMD-SHELL + - 'mongosh --quiet --username root --password "$$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --eval ''db.adminCommand({ ping: 1 }).ok'' | grep 1' + interval: 5s + timeout: 5s + retries: 30 + start_period: 20s + + redis: + image: redis:7.4-alpine + container_name: lithe-database-validation-redis + restart: unless-stopped + command: + - redis-server + - --appendonly + - "yes" + - --requirepass + - "${LITHE_DB_PASSWORD:-lithe_root}" + environment: + REDIS_PASSWORD: "${LITHE_DB_PASSWORD:-lithe_root}" + REDISCLI_AUTH: "${LITHE_DB_PASSWORD:-lithe_root}" + ports: + - "${LITHE_BIND_ADDRESS:-127.0.0.1}:${LITHE_REDIS_PORT:-6381}:6379" + volumes: + - redis-data:/data + healthcheck: + test: ["CMD-SHELL", "redis-cli ping | grep PONG"] + interval: 5s + timeout: 5s + retries: 30 + + redis-seed: + image: redis:7.4-alpine + container_name: lithe-database-validation-redis-seed + depends_on: + redis: + condition: service_healthy + environment: + REDIS_PASSWORD: "${LITHE_DB_PASSWORD:-lithe_root}" + entrypoint: ["/bin/sh", "/usr/local/bin/redis-seed.sh"] + volumes: + - ./redis-seed.sh:/usr/local/bin/redis-seed.sh:ro + restart: "no" + +volumes: + mariadb-data: + mongodb-data: + redis-data: diff --git a/docker/database-validation/mariadb-init.sql b/docker/database-validation/mariadb-init.sql new file mode 100644 index 0000000000..a40dc1af3f --- /dev/null +++ b/docker/database-validation/mariadb-init.sql @@ -0,0 +1,35 @@ +ALTER DATABASE lithe_test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +USE lithe_test; +SET NAMES utf8mb4; + +CREATE TABLE IF NOT EXISTS records ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + title VARCHAR(120) NOT NULL, + nullable_note TEXT NULL, + empty_value VARCHAR(32) NOT NULL, + flag BOOLEAN NOT NULL, + tiny_value TINYINT NOT NULL, + event_time TIMESTAMP(6) NOT NULL, + amount DECIMAL(10, 2) NOT NULL, + payload JSON NOT NULL, + binary_value VARBINARY(8) NOT NULL, + PRIMARY KEY (id), + KEY records_title_idx (title), + KEY records_event_time_idx (event_time) +) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS audit_log ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + action_name VARCHAR(64) NOT NULL, + created_at DATETIME(6) NOT NULL, + PRIMARY KEY (id) +) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; + +INSERT INTO records + (title, nullable_note, empty_value, flag, tiny_value, event_time, amount, payload, binary_value) +VALUES + ('中文 / emoji 🚀', NULL, '', TRUE, 1, '2026-08-10 09:30:00.123456', 1234.50, '{"tags":["demo","中文"],"active":true}', UNHEX('00010203')), + ('second row', 'a non-empty note', 'filled', FALSE, 127, '2026-08-11 10:45:01.000000', 0.01, '{"tags":[],"active":false}', UNHEX('FF00')); + +INSERT INTO audit_log (action_name, created_at) +VALUES ('seed', '2026-08-10 09:00:00.000000'); diff --git a/docker/database-validation/mongodb-init.js b/docker/database-validation/mongodb-init.js new file mode 100644 index 0000000000..0c9cf09cc1 --- /dev/null +++ b/docker/database-validation/mongodb-init.js @@ -0,0 +1,32 @@ +const validation = db.getSiblingDB('lithe_test'); + +validation.items.deleteMany({}); +validation.items.insertMany([ + { + _id: ObjectId('66b5a9a00000000000000001'), + name: '中文 / emoji 🚀', + empty_value: '', + nullable_value: null, + active: true, + score: NumberInt(42), + amount: NumberDecimal('1234.50'), + happened_at: ISODate('2026-08-10T09:30:00.123Z'), + nested: { region: 'cn', labels: ['demo', '数据库'] }, + binary_value: new BinData(0, 'AAEC') + }, + { + _id: ObjectId('66b5a9a00000000000000002'), + name: 'second row', + empty_value: 'filled', + nullable_value: null, + active: false, + score: NumberInt(7), + amount: NumberDecimal('0.01'), + happened_at: ISODate('2026-08-11T10:45:01.000Z'), + nested: { region: 'us', labels: [] }, + binary_value: new BinData(0, '/wA=') + } +]); + +validation.items.createIndex({ name: 1 }, { name: 'items_name_idx' }); +validation.items.createIndex({ active: 1, score: -1 }, { name: 'items_active_score_idx' }); diff --git a/docker/database-validation/redis-seed.sh b/docker/database-validation/redis-seed.sh new file mode 100755 index 0000000000..aa38601246 --- /dev/null +++ b/docker/database-validation/redis-seed.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +set -eu + +export REDISCLI_AUTH="$REDIS_PASSWORD" + +redis-cli -h redis DEL profile:42 cache:empty session:42 queue:jobs ttl:short +redis-cli -h redis SET profile:42 'Alice / demo' +redis-cli -h redis SET cache:empty '' +redis-cli -h redis HSET session:42 user_id 42 locale zh-CN +redis-cli -h redis RPUSH queue:jobs job-1 job-2 +redis-cli -h redis SETEX ttl:short 3600 'expires later' +redis-cli -h redis DBSIZE diff --git a/rust/lithe-db-sidecar/src/mongodb_adapter.rs b/rust/lithe-db-sidecar/src/mongodb_adapter.rs index 30f444d490..877c1462e4 100644 --- a/rust/lithe-db-sidecar/src/mongodb_adapter.rs +++ b/rust/lithe-db-sidecar/src/mongodb_adapter.rs @@ -96,7 +96,38 @@ pub(super) async fn method(method: &str, params: Params) -> DbResult { async fn connect(connection: &Connection) -> Result { let host = connection.host.trim(); - let uri = if host.starts_with("mongodb://") || host.starts_with("mongodb+srv://") { + let uri = mongo_uri(connection); + let timeout = Duration::from_secs(8); + let mut options = tokio::time::timeout(timeout, ClientOptions::parse(&uri)) + .await + .map_err(|_| { + ( + "connection_failed".into(), + "MongoDB connection timed out.".into(), + ) + })? + .map_err(|error| { + ( + "connection_failed".into(), + redact(error.to_string(), &connection.password), + ) + })?; + options.connect_timeout = Some(timeout); + options.server_selection_timeout = Some(timeout); + if !host.starts_with("mongodb+srv://") && !host.contains(',') { + options.direct_connection = Some(true); + } + Client::with_options(options).map_err(|error| { + ( + "connection_failed".into(), + redact(error.to_string(), &connection.password), + ) + }) +} + +fn mongo_uri(connection: &Connection) -> String { + let host = connection.host.trim(); + if host.starts_with("mongodb://") || host.starts_with("mongodb+srv://") { if connection.ssl && !host.to_ascii_lowercase().contains("tls=") { format!( "{host}{}tls=true", @@ -125,35 +156,21 @@ async fn connect(connection: &Connection) -> Result { } else { connection.database.trim() }; - let separator = if connection.ssl { "?tls=true" } else { "" }; - format!("mongodb://{credentials}{host}:{port}/{database}{separator}") - }; - let timeout = Duration::from_secs(8); - let mut options = tokio::time::timeout(timeout, ClientOptions::parse(&uri)) - .await - .map_err(|_| { - ( - "connection_failed".into(), - "MongoDB connection timed out.".into(), - ) - })? - .map_err(|error| { - ( - "connection_failed".into(), - redact(error.to_string(), &connection.password), - ) - })?; - options.connect_timeout = Some(timeout); - options.server_selection_timeout = Some(timeout); - if !host.starts_with("mongodb+srv://") && !host.contains(',') { - options.direct_connection = Some(true); + let mut query = Vec::new(); + if !connection.username.is_empty() { + // MongoDB users are commonly created in admin while the selected database is an app database. + query.push("authSource=admin"); + } + if connection.ssl { + query.push("tls=true"); + } + let suffix = if query.is_empty() { + String::new() + } else { + format!("?{}", query.join("&")) + }; + format!("mongodb://{credentials}{host}:{port}/{database}{suffix}") } - Client::with_options(options).map_err(|error| { - ( - "connection_failed".into(), - redact(error.to_string(), &connection.password), - ) - }) } async fn describe_collection(database: &mongodb::Database, collection_name: &str) -> DbResult { @@ -451,3 +468,67 @@ fn redact(mut message: String, password: &str) -> String { } message } + +#[cfg(test)] +mod tests { + use super::*; + + fn connection( + host: &str, + username: &str, + password: &str, + database: &str, + ssl: bool, + ) -> Connection { + Connection { + kind: "mongodb".into(), + host: host.into(), + port: 27017, + username: username.into(), + password: password.into(), + database: database.into(), + path: String::new(), + ssl, + ca_certificate_path: String::new(), + server_name: String::new(), + ssh_host: String::new(), + ssh_port: 0, + ssh_username: String::new(), + ssh_key_path: String::new(), + ssh_local_port: 0, + proxy_url: String::new(), + read_only: false, + production_protection: false, + } + } + + #[test] + fn host_connections_authenticate_against_admin_by_default() { + let uri = mongo_uri(&connection( + "127.0.0.1", + "root", + "secret", + "lithe_test", + false, + )); + assert_eq!( + uri, + "mongodb://root:secret@127.0.0.1:27017/lithe_test?authSource=admin" + ); + } + + #[test] + fn explicit_mongodb_uri_keeps_its_options() { + let uri = mongo_uri(&connection( + "mongodb://root:secret@db.example/lithe_test?authSource=custom", + "", + "", + "", + true, + )); + assert_eq!( + uri, + "mongodb://root:secret@db.example/lithe_test?authSource=custom&tls=true" + ); + } +} diff --git a/scripts/database-validation-smoke.sh b/scripts/database-validation-smoke.sh new file mode 100755 index 0000000000..67c9225cc7 --- /dev/null +++ b/scripts/database-validation-smoke.sh @@ -0,0 +1,146 @@ +#!/bin/zsh + +set -euo pipefail + +ROOT_DIR="${0:A:h:h}" +COMPOSE_FILE="$ROOT_DIR/docker/database-validation/compose.yaml" +SIDECAR="${LITHE_DB_SIDECAR_EXECUTABLE:-$ROOT_DIR/rust/target/debug/lithe-db-sidecar}" +BIND_ADDRESS="${LITHE_BIND_ADDRESS:-127.0.0.1}" +MARIADB_PORT="${LITHE_MARIADB_PORT:-53307}" +MONGODB_PORT="${LITHE_MONGODB_PORT:-57019}" +REDIS_PORT="${LITHE_REDIS_PORT:-6381}" +DB_PASSWORD="${LITHE_DB_PASSWORD:-lithe_root}" + +if [[ ! -x "$SIDECAR" ]]; then + print -u2 -- "Database sidecar is not executable: $SIDECAR" + print -u2 -- "Build it with: cargo build --manifest-path $ROOT_DIR/rust/Cargo.toml -p lithe-db-sidecar" + exit 2 +fi + +docker compose -f "$COMPOSE_FILE" config --quiet +docker compose -f "$COMPOSE_FILE" up -d mariadb mongodb redis + +wait_for_health() { + local container="$1" + local attempt + local health_status + for attempt in {1..60}; do + health_status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || true) + if [[ "$health_status" == "healthy" ]]; then + return 0 + fi + if [[ "$health_status" == "unhealthy" || "$health_status" == "exited" || "$health_status" == "dead" ]]; then + docker logs "$container" >&2 || true + print -u2 -- "$container did not become healthy (status: $health_status)" + return 1 + fi + sleep 1 + done + docker logs "$container" >&2 || true + print -u2 -- "$container healthcheck timed out" + return 1 +} + +wait_for_health lithe-database-validation-mariadb +wait_for_health lithe-database-validation-mongodb +wait_for_health lithe-database-validation-redis +docker compose -f "$COMPOSE_FILE" up --no-deps redis-seed + +typeset -g LAST_RESPONSE + +request() { + local request_id="$1" + local method="$2" + local params="$3" + LAST_RESPONSE=$(print -rn -- "{\"id\":\"$request_id\",\"method\":\"$method\",\"params\":$params}" | "$SIDECAR" || true) + print -r -- "$LAST_RESPONSE" + print -rn -- "$LAST_RESPONSE" | python3 -c ' +import json +import sys +response = json.load(sys.stdin) +if not response.get("ok"): + error = response.get("error", {}) + code = error.get("code", "unknown") + message = error.get("message", "unknown error") + raise SystemExit(f"sidecar request failed: {code}: {message}") +' +} + +assert_result_contains() { + local needle="$1" + print -rn -- "$LAST_RESPONSE" | python3 -c ' +import json +import sys +response = json.load(sys.stdin) +needle = sys.argv[1] +if needle not in json.dumps(response.get("result"), ensure_ascii=False): + raise SystemExit(f"expected result to contain {needle!r}") +' "$needle" +} + +assert_result() { + local check="$1" + print -rn -- "$LAST_RESPONSE" | python3 -c ' +import json +import sys +response = json.load(sys.stdin) +check = sys.argv[1] +result = response.get("result") +if check == "mariadb_rows": + rows = result.get("rows", []) + assert len(rows) == 2 and rows[0]["empty_value"] == "" and rows[0]["nullable_note"] is None +elif check == "mariadb_page": + assert result.get("totalRows") == 2 and len(result.get("rows", [])) == 1 +elif check == "mongo_page": + assert result.get("totalRows") == 2 and len(result.get("rows", [])) == 2 +elif check == "mongo_query": + assert len(result.get("rows", [])) == 1 and result["rows"][0]["name"] == "中文 / emoji 🚀" +elif check == "redis_scan": + keys = {item["key"] for item in result.get("keys", [])} + assert {"profile:42", "session:42", "queue:jobs", "ttl:short"}.issubset(keys) +elif check == "redis_hash": + assert result["type"] == "hash" and {entry["field"] for entry in result["hashEntries"]} == {"user_id", "locale"} +else: + raise SystemExit(f"unknown assertion {check!r}") +' "$check" +} + +mariadb='{"kind":"mariadb","host":"'$BIND_ADDRESS'","port":'$MARIADB_PORT',"username":"root","password":"'$DB_PASSWORD'","database":"lithe_test"}' +mongodb='{"kind":"mongodb","host":"'$BIND_ADDRESS'","port":'$MONGODB_PORT',"username":"root","password":"'$DB_PASSWORD'","database":"lithe_test"}' +redis='{"kind":"redis","host":"'$BIND_ADDRESS'","port":'$REDIS_PORT',"password":"'$DB_PASSWORD'","database":"0"}' + +print -r -- "MariaDB: test connection, metadata, typed values, and pagination" +request mariadb-connect testConnection '{"connection":'$mariadb'}' +request mariadb-tables listTables '{"connection":'$mariadb'}' +assert_result_contains records +request mariadb-columns describeTable '{"connection":'$mariadb',"table":"records"}' +assert_result_contains empty_value +assert_result_contains tiny_value +request mariadb-query query '{"connection":'$mariadb',"sql":"SELECT id, empty_value, nullable_note, flag, tiny_value, amount FROM records ORDER BY id","limit":10}' +assert_result mariadb_rows +request mariadb-page pageTable '{"connection":'$mariadb',"table":"records","limit":1,"offset":1,"sort":[{"column":"id"}]}' +assert_result mariadb_page + +print -r -- "MongoDB: test connection, collections, indexes, documents, and filters" +request mongodb-connect testConnection '{"connection":'$mongodb'}' +request mongodb-tables listTables '{"connection":'$mongodb'}' +assert_result_contains items +request mongodb-indexes listIndexes '{"connection":'$mongodb',"table":"items"}' +assert_result_contains items_name_idx +request mongodb-page pageTable '{"connection":'$mongodb',"table":"items","limit":10,"sort":[{"column":"score","descending":true}]}' +assert_result mongo_page +request mongodb-query query '{"connection":'$mongodb',"table":"items","sql":"{\"name\":\"中文 / emoji 🚀\"}","limit":10}' +assert_result mongo_query + +print -r -- "Redis: test connection, scan, string/hash/list metadata, and key detail" +request redis-connect testConnection '{"connection":'$redis'}' +request redis-scan redisScan '{"connection":'$redis',"cursor":"0","pattern":"*","count":100,"includeSize":true}' +assert_result redis_scan +request redis-string redisGetKey '{"connection":'$redis',"key":"profile:42"}' +assert_result_contains 'Alice / demo' +request redis-hash redisGetKey '{"connection":'$redis',"key":"session:42"}' +assert_result redis_hash +request redis-list redisGetKey '{"connection":'$redis',"key":"queue:jobs"}' +assert_result_contains 'list' + +print -r -- "Database validation smoke passed. Containers remain running for manual Lithe verification." From 4afe4cb6dc165192d925dfa0ec75944a24bdd11c Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Mon, 10 Aug 2026 15:42:43 +0800 Subject: [PATCH 6/6] fix(database): refresh workspace data consistently --- .../Application/DatabaseFeatureModel.swift | 250 +++++++++++++---- .../Application/DatabaseSQLSupport.swift | 132 +++++++-- .../Lithe/Views/DatabaseLocalization.swift | 1 + .../Views/DatabaseSQLWorkspaceView.swift | 177 +++++++++--- Sources/Lithe/Views/DatabaseSidebarView.swift | 22 +- .../DatabaseSpecializedWorkspaceViews.swift | 27 +- Sources/Lithe/Views/DatabaseTableView.swift | 21 ++ Tests/LitheTests/LitheCoreLogicTests.swift | 251 ++++++++++++++++++ 8 files changed, 757 insertions(+), 124 deletions(-) diff --git a/Sources/Lithe/Application/DatabaseFeatureModel.swift b/Sources/Lithe/Application/DatabaseFeatureModel.swift index d2218984a7..425190758e 100644 --- a/Sources/Lithe/Application/DatabaseFeatureModel.swift +++ b/Sources/Lithe/Application/DatabaseFeatureModel.swift @@ -1,6 +1,15 @@ import Combine import Foundation +private struct DatabaseSQLBatchError: LocalizedError { + let statementIndex: Int + let message: String + + var errorDescription: String? { + "Statement \(statementIndex) failed: \(message) Batch stopped; earlier statements may have been applied." + } +} + enum DatabaseConnectionStatus: Equatable, Sendable { case idle case connecting @@ -66,13 +75,20 @@ final class DatabaseFeatureModel: ObservableObject { private let recoveryStore: DatabaseRecoveryStore private var backupTimer: Timer? private var profileGeneration: UInt64 = 0 + private var tableListRequestID: UUID? + private var databaseListRequestID: UUID? private var tableRequestID: UUID? private var redisScanRequestID: UUID? private var redisDetailRequestID: UUID? + private var redisScanPattern = "*" private var nacosConfigListRequestID: UUID? private var nacosConfigDetailRequestID: UUID? private var nacosServiceListRequestID: UUID? private var nacosInstanceRequestID: UUID? + private var nacosConfigSearchDataID = "" + private var nacosConfigSearchGroup = "" + private var nacosSelectedServiceName: String? + private var nacosSelectedServiceGroup: String? // Keep the unmasked page separate so primary-key mutations and exports never // accidentally persist the display placeholder. private var sourceRows: [DatabaseRow] = [] @@ -368,8 +384,16 @@ final class DatabaseFeatureModel: ObservableObject { return } let generation = profileGeneration + let requestID = UUID() + let tableToRefresh = selectedTable + tableListRequestID = requestID + let databaseRequestID: UUID? = profile.kind == .mysql || profile.kind == .mariadb ? requestID : nil + databaseListRequestID = databaseRequestID isLoading = true; errorMessage = nil tables = []; objects = [:] + if tableToRefresh != nil { + rows = []; sourceRows = []; totalRows = 0; currentOffset = 0 + } setConnectionStatus(.connecting, for: profile.id) do { let connection = connection(profile) @@ -377,30 +401,48 @@ final class DatabaseFeatureModel: ObservableObject { let databaseRows = try await Task.detached { [operations] in try operations.listDatabases(connection: connection) }.value - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), tableListRequestID == requestID, databaseListRequestID == databaseRequestID else { return } databaseOptions = databaseRows } else { databaseOptions = [] } let result = try await Task.detached { [operations] in try operations.listTables(connection: connection, schema: "") }.value - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), tableListRequestID == requestID, databaseListRequestID == databaseRequestID else { return } setConnectionStatus(.connected, for: profile.id) tables = result.compactMap { row in row["table_name"]?.text ?? row["TABLE_NAME"]?.text ?? row["name"]?.text } - if profile.kind.isSQLDatabase { await refreshObjects(profileID: profile.id, generation: generation) } + if profile.kind.isSQLDatabase { + await refreshObjects(profileID: profile.id, generation: generation, tableRequestID: requestID, databaseRequestID: databaseRequestID) + } + guard isCurrent(profileID: profile.id, generation: generation), tableListRequestID == requestID, databaseListRequestID == databaseRequestID else { return } + if let tableToRefresh, selectedTable == tableToRefresh { + if tables.contains(tableToRefresh) { + await openTable(tableToRefresh) + } else { + openTableTabs.removeAll { !tables.contains($0) } + selectedTable = openTableTabs.last + rows = []; sourceRows = []; columns = []; columnTypes = [:] + primaryKeyColumns = []; indexes = []; foreignKeys = []; totalRows = 0; currentOffset = 0 + if let replacement = selectedTable { + await openTable(replacement) + } + } + } } catch { - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), tableListRequestID == requestID, databaseListRequestID == databaseRequestID else { return } tables = []; objects = [:]; databaseOptions = [] errorMessage = executionError(error) setConnectionStatus(.failed, for: profile.id) } - if isCurrent(profileID: profile.id, generation: generation) { isLoading = false } + if isCurrent(profileID: profile.id, generation: generation), tableListRequestID == requestID, databaseListRequestID == databaseRequestID { isLoading = false } } func refreshDatabases() async { guard let profile = selectedProfile, profile.kind == .mysql || profile.kind == .mariadb else { return } let generation = profileGeneration + let requestID = UUID() + databaseListRequestID = requestID isLoading = true errorMessage = nil setConnectionStatus(.connecting, for: profile.id) @@ -409,12 +451,12 @@ final class DatabaseFeatureModel: ObservableObject { let rows = try await Task.detached { [operations] in try operations.listDatabases(connection: connection) }.value - guard isCurrent(profileID: profile.id, generation: generation) else { return } + guard isCurrent(profileID: profile.id, generation: generation), databaseListRequestID == requestID else { return } databaseOptions = rows setConnectionStatus(.connected, for: profile.id) isLoading = false } catch { - if isCurrent(profileID: profile.id, generation: generation) { + if isCurrent(profileID: profile.id, generation: generation), databaseListRequestID == requestID { databaseOptions = [] errorMessage = executionError(error) setConnectionStatus(.failed, for: profile.id) @@ -442,8 +484,10 @@ final class DatabaseFeatureModel: ObservableObject { } } - private func refreshObjects(profileID: UUID, generation: UInt64) async { + private func refreshObjects(profileID: UUID, generation: UInt64, tableRequestID: UUID, databaseRequestID: UUID?) async { guard isCurrent(profileID: profileID, generation: generation), + self.tableListRequestID == tableRequestID, + self.databaseListRequestID == databaseRequestID, let profile = profiles.first(where: { $0.id == profileID }) else { return } let connection = connection(profile) do { @@ -457,10 +501,10 @@ final class DatabaseFeatureModel: ObservableObject { for try await (kind, rows) in group { result[kind] = rows } return result } - guard isCurrent(profileID: profileID, generation: generation) else { return } + guard isCurrent(profileID: profileID, generation: generation), self.tableListRequestID == tableRequestID, self.databaseListRequestID == databaseRequestID else { return } objects = loaded } catch { - if isCurrent(profileID: profileID, generation: generation) { + if isCurrent(profileID: profileID, generation: generation), self.tableListRequestID == tableRequestID, self.databaseListRequestID == databaseRequestID { objects = [:] errorMessage = executionError(error) } @@ -737,6 +781,7 @@ final class DatabaseFeatureModel: ObservableObject { } catch { if isCurrent(profileID: profile.id, generation: generation), selectedTable == table, tableRequestID == requestID { errorMessage = executionError(error) + rows = []; sourceRows = []; totalRows = 0 } } if isCurrent(profileID: profile.id, generation: generation), tableRequestID == requestID { isLoading = false } @@ -935,8 +980,17 @@ final class DatabaseFeatureModel: ObservableObject { updateSQL(DatabaseSQLFormatter.format(tab.sql), in: tabID) } - func analysis(forSQLTab tabID: UUID) -> DatabaseSQLAnalysis { - DatabaseSQLAnalyzer.analyze(sqlTabs.first(where: { $0.id == tabID })?.sql ?? "") + func analysis(forSQLTab tabID: UUID, scope: DatabaseSQLExecutionScope = .all) -> DatabaseSQLAnalysis { + DatabaseSQLAnalyzer.analyze(sql(for: tabID, scope: scope)) + } + + private func sql(for tabID: UUID, scope: DatabaseSQLExecutionScope) -> String { + switch scope { + case .all: + return sqlTabs.first(where: { $0.id == tabID })?.sql ?? "" + case let .selection(selection): + return selection + } } func restoreSQLHistory(_ entry: DatabaseSQLHistoryEntry) { @@ -947,12 +1001,13 @@ final class DatabaseFeatureModel: ObservableObject { } } - func runSQL(in tabID: UUID, confirmedRisk: Bool = false) async { - guard let profile = selectedProfile, let tab = sqlTabs.first(where: { $0.id == tabID }) else { + func runSQL(in tabID: UUID, scope: DatabaseSQLExecutionScope = .all, confirmedRisk: Bool = false) async { + guard let profile = selectedProfile, sqlTabs.contains(where: { $0.id == tabID }) else { errorMessage = "Select a database connection first." return } - let analysis = DatabaseSQLAnalyzer.analyze(tab.sql) + let sql = sql(for: tabID, scope: scope).trimmingCharacters(in: .whitespacesAndNewlines) + let analysis = DatabaseSQLAnalyzer.analyze(sql) updateSQLTab(tabID) { tab in tab.errorMessage = nil tab.result = nil @@ -969,56 +1024,76 @@ final class DatabaseFeatureModel: ObservableObject { return } - let sql = tab.sql.trimmingCharacters(in: .whitespacesAndNewlines) let connection = connection(profile) let generation = profileGeneration let startedAt = Date() + var recoveryPointID: UUID? + var totalRowsAffected: UInt64 = 0 + var hasRowsAffected = false + var lastQueryResult: DatabaseQueryResult? updateSQLTab(tabID) { tab in tab.isRunning = true; tab.errorMessage = nil; tab.result = nil; tab.resultColumns = []; tab.rowsAffected = nil; tab.execution = nil } do { - let recoveryPoint: DatabaseRecoveryPoint? = analysis.kind.usesQueryEndpoint ? nil : try await createRecoveryPoint(profile: profile, reason: "Before SQL execution") + let hasMutation = analysis.statements.contains { + !DatabaseSQLAnalyzer.analyze($0).kind.usesQueryEndpoint + } + let recoveryPoint: DatabaseRecoveryPoint? = hasMutation ? try await createRecoveryPoint(profile: profile, reason: "Before SQL execution") : nil + recoveryPointID = recoveryPoint?.id guard isCurrent(profileID: profile.id, generation: generation) else { return } - if analysis.kind.usesQueryEndpoint { - let result = try await Task.detached { [operations] in - try operations.query(connection: connection, sql: sql, values: [], limit: 10_000) - }.value - let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) - let columns = result.columns ?? result.rows.reduce(into: [String]()) { result, row in - for key in row.keys where !result.contains(key) { result.append(key) } - } - let execution = DatabaseSQLExecution(startedAt: startedAt, durationMilliseconds: duration, rowsReturned: result.rows.count, rowsAffected: nil, truncated: result.truncated) - guard isCurrent(profileID: profile.id, generation: generation) else { return } - updateSQLTab(tabID) { tab in - tab.result = masked(result); tab.resultColumns = columns; tab.execution = execution; tab.isRunning = false - } - recordSQLHistory(profileID: profile.id, sql: sql, analysis: analysis, execution: execution) - appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: analysis.kind.rawValue, startedAt: startedAt, durationMilliseconds: execution.durationMilliseconds, status: .succeeded, rowsReturned: execution.rowsReturned, rowsAffected: execution.rowsAffected, errorMessage: nil)) - if let recoveryPoint { appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "Executed \(analysis.kind.rawValue) statement", createdAt: startedAt, recoveryPointID: recoveryPoint.id, rowsAffected: execution.rowsAffected, succeeded: true, errorMessage: nil)) } - } else { - let result = try await Task.detached { [operations] in - try operations.execute(connection: connection, sql: sql, values: [], confirmed: confirmedRisk, allowWrite: false) - }.value - let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) - let execution = DatabaseSQLExecution(startedAt: startedAt, durationMilliseconds: duration, rowsReturned: nil, rowsAffected: result.rowsAffected, truncated: false) - guard isCurrent(profileID: profile.id, generation: generation) else { return } - updateSQLTab(tabID) { tab in - tab.rowsAffected = result.rowsAffected; tab.execution = execution; tab.isRunning = false + for (index, statement) in analysis.statements.enumerated() { + let statementAnalysis = DatabaseSQLAnalyzer.analyze(statement) + do { + if statementAnalysis.kind.usesQueryEndpoint { + lastQueryResult = try await Task.detached { [operations] in + try operations.query(connection: connection, sql: statement.trimmingCharacters(in: .whitespacesAndNewlines), values: [], limit: 10_000) + }.value + } else { + let result = try await Task.detached { [operations] in + try operations.execute(connection: connection, sql: statement.trimmingCharacters(in: .whitespacesAndNewlines), values: [], confirmed: confirmedRisk, allowWrite: false) + }.value + totalRowsAffected += result.rowsAffected + hasRowsAffected = true + } + } catch { + throw DatabaseSQLBatchError(statementIndex: index + 1, message: executionError(error)) } - recordSQLHistory(profileID: profile.id, sql: sql, analysis: analysis, execution: execution) - appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: analysis.kind.rawValue, startedAt: startedAt, durationMilliseconds: execution.durationMilliseconds, status: .succeeded, rowsReturned: execution.rowsReturned, rowsAffected: execution.rowsAffected, errorMessage: nil)) - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "Executed \(analysis.kind.rawValue) statement", createdAt: startedAt, recoveryPointID: recoveryPoint?.id, rowsAffected: execution.rowsAffected, succeeded: true, errorMessage: nil)) - await refreshTables() } + + let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) + let columns = lastQueryResult?.columns ?? lastQueryResult?.rows.reduce(into: [String]()) { result, row in + for key in row.keys where !result.contains(key) { result.append(key) } + } ?? [] + let execution = DatabaseSQLExecution( + startedAt: startedAt, + durationMilliseconds: duration, + rowsReturned: lastQueryResult?.rows.count, + rowsAffected: hasRowsAffected ? totalRowsAffected : nil, + truncated: lastQueryResult?.truncated ?? false + ) + guard isCurrent(profileID: profile.id, generation: generation) else { return } + updateSQLTab(tabID) { tab in + tab.result = lastQueryResult.map(masked) + tab.resultColumns = columns + tab.rowsAffected = hasRowsAffected ? totalRowsAffected : nil + tab.execution = execution + tab.isRunning = false + } + recordSQLHistory(profileID: profile.id, sql: sql, analysis: analysis, execution: execution) + let operation = analysis.statementCount > 1 ? "batch" : analysis.kind.rawValue + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: operation, startedAt: startedAt, durationMilliseconds: execution.durationMilliseconds, status: .succeeded, rowsReturned: execution.rowsReturned, rowsAffected: execution.rowsAffected, errorMessage: nil)) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "Executed \(analysis.statementCount) SQL statement\(analysis.statementCount == 1 ? "" : "s")", createdAt: startedAt, recoveryPointID: recoveryPointID, rowsAffected: execution.rowsAffected, succeeded: true, errorMessage: nil)) + if hasMutation { await refreshTables() } } catch { guard isCurrent(profileID: profile.id, generation: generation) else { return } let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) - appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: analysis.kind.rawValue, startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) - appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "SQL execution failed", createdAt: startedAt, recoveryPointID: nil, rowsAffected: nil, succeeded: false, errorMessage: sanitizedError)) + let operation = analysis.statementCount > 1 ? "batch" : analysis.kind.rawValue + appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .sql, operation: operation, startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: hasRowsAffected ? totalRowsAffected : nil, errorMessage: sanitizedError)) + appendAudit(DatabaseAuditEntry(id: UUID(), profileID: profile.id, action: "sql", summary: "SQL execution failed", createdAt: startedAt, recoveryPointID: recoveryPointID, rowsAffected: hasRowsAffected ? totalRowsAffected : nil, succeeded: false, errorMessage: sanitizedError)) updateSQLTab(tabID) { tab in - tab.isRunning = false; tab.errorMessage = sanitizedError; tab.execution = nil; tab.rowsAffected = nil; tab.result = nil; tab.resultColumns = [] + tab.isRunning = false; tab.errorMessage = sanitizedError; tab.execution = nil; tab.rowsAffected = hasRowsAffected ? totalRowsAffected : nil; tab.result = nil; tab.resultColumns = [] } } } @@ -1125,6 +1200,7 @@ final class DatabaseFeatureModel: ObservableObject { func loadRedisKeys(pattern: String, reset: Bool = true) async { guard let profile = selectedProfile, profile.kind == .redis else { return } let generation = profileGeneration + redisScanPattern = pattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "*" : pattern let cursor = reset ? "0" : redisNextCursor if !reset && cursor == "0" { return } let requestID = UUID() @@ -1152,6 +1228,12 @@ final class DatabaseFeatureModel: ObservableObject { redisKeys = reset ? result.keys : Array(Dictionary(grouping: redisKeys + result.keys, by: \.key).compactMap { $0.value.first }) redisNextCursor = result.nextCursor } catch { + if Task.isCancelled { + if isCurrent(profileID: profile.id, generation: generation), redisScanRequestID == requestID { + isLoading = false + } + return + } let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "SCAN", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) @@ -1182,6 +1264,12 @@ final class DatabaseFeatureModel: ObservableObject { setConnectionStatus(.connected, for: profile.id) redisSelectedKey = detail } catch { + if Task.isCancelled { + if isCurrent(profileID: profile.id, generation: generation), redisDetailRequestID == requestID { + isLoading = false + } + return + } let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: "GET \(key)", startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) @@ -1196,7 +1284,7 @@ final class DatabaseFeatureModel: ObservableObject { await performRedisWrite(summary: "Updated Redis string \(key)", confirmed: confirmed) { connection, operations in try operations.redisSetString(connection: connection, key: key, value: value, ttl: ttl, confirmed: confirmed, allowWrite: false) } afterSuccess: { - await self.loadRedisKey(key) + await self.refreshRedisAfterMutation(selectedKey: key) } } @@ -1204,7 +1292,7 @@ final class DatabaseFeatureModel: ObservableObject { await performRedisWrite(summary: "Updated Redis hash \(key)", confirmed: confirmed) { connection, operations in try operations.redisReplaceHash(connection: connection, key: key, entries: entries, confirmed: confirmed, allowWrite: false) } afterSuccess: { - await self.loadRedisKey(key) + await self.refreshRedisAfterMutation(selectedKey: key) } } @@ -1212,7 +1300,7 @@ final class DatabaseFeatureModel: ObservableObject { await performRedisWrite(summary: "Changed Redis TTL for \(key)", confirmed: confirmed) { connection, operations in try operations.redisSetTTL(connection: connection, key: key, ttl: ttl, confirmed: confirmed, allowWrite: false) } afterSuccess: { - await self.loadRedisKey(key) + await self.refreshRedisAfterMutation(selectedKey: key) } } @@ -1220,7 +1308,7 @@ final class DatabaseFeatureModel: ObservableObject { await performRedisWrite(summary: "Renamed Redis key \(key)", confirmed: confirmed) { connection, operations in try operations.redisRenameKey(connection: connection, key: key, newKey: newKey, confirmed: confirmed, allowWrite: false) } afterSuccess: { - await self.loadRedisKey(newKey) + await self.refreshRedisAfterMutation(selectedKey: newKey) } } @@ -1228,8 +1316,7 @@ final class DatabaseFeatureModel: ObservableObject { await performRedisWrite(summary: "Deleted Redis key \(key)", confirmed: confirmed) { connection, operations in try operations.redisDeleteKey(connection: connection, key: key, confirmed: confirmed, allowWrite: false) } afterSuccess: { - self.redisSelectedKey = nil - self.redisKeys.removeAll { $0.key == key } + await self.refreshRedisAfterMutation() } } @@ -1237,9 +1324,14 @@ final class DatabaseFeatureModel: ObservableObject { await performRedisWrite(summary: "Cleared Redis database", confirmed: confirmed) { connection, operations in try operations.redisFlushDatabase(connection: connection, confirmed: confirmed, allowWrite: false) } afterSuccess: { - self.redisKeys = [] - self.redisNextCursor = "0" - self.redisSelectedKey = nil + await self.refreshRedisAfterMutation() + } + } + + private func refreshRedisAfterMutation(selectedKey: String? = nil) async { + await loadRedisKeys(pattern: redisScanPattern) + if let selectedKey { + await loadRedisKey(selectedKey) } } @@ -1266,6 +1358,12 @@ final class DatabaseFeatureModel: ObservableObject { isLoading = false return true } catch { + if Task.isCancelled { + if isCurrent(profileID: profile.id, generation: generation) { + isLoading = false + } + return false + } let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) appendExecutionEvent(DatabaseExecutionEvent(id: UUID(), profileID: profile.id, profileName: profile.name, source: .redis, operation: summary, startedAt: startedAt, durationMilliseconds: duration, status: .failed, rowsReturned: nil, rowsAffected: nil, errorMessage: sanitizedError)) @@ -1284,6 +1382,13 @@ final class DatabaseFeatureModel: ObservableObject { func loadNacosConfigs(dataId: String, group: String, page: Int = 1) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } let generation = profileGeneration + let selectedConfigToRefresh = page == 1 ? nacosSelectedConfig.map { ($0.dataId, $0.group) } : nil + if page == 1 { + nacosConfigSearchDataID = dataId + nacosConfigSearchGroup = group + nacosConfigDetailRequestID = nil + nacosSelectedConfig = nil + } let requestID = UUID() nacosConfigListRequestID = requestID let startedAt = Date() @@ -1305,6 +1410,10 @@ final class DatabaseFeatureModel: ObservableObject { setConnectionStatus(.connected, for: profile.id) nacosConfigs = result.items nacosConfigTotalCount = result.totalCount + if let selectedConfigToRefresh, + result.items.contains(where: { $0.dataId == selectedConfigToRefresh.0 && $0.group == selectedConfigToRefresh.1 }) { + await loadNacosConfig(dataId: selectedConfigToRefresh.0, group: selectedConfigToRefresh.1) + } } catch { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) @@ -1352,6 +1461,7 @@ final class DatabaseFeatureModel: ObservableObject { return await performNacosWrite(profile: profile, summary: summary) { connection, operations in try operations.nacosPublishConfig(connection: connection, dataId: dataId, group: group, content: content, type: type, confirmed: confirmed, allowWrite: false) } afterSuccess: { + await self.loadNacosConfigs(dataId: self.nacosConfigSearchDataID, group: self.nacosConfigSearchGroup) await self.loadNacosConfig(dataId: dataId, group: group) } } @@ -1362,8 +1472,8 @@ final class DatabaseFeatureModel: ObservableObject { return await performNacosWrite(profile: profile, summary: summary) { connection, operations in try operations.nacosDeleteConfig(connection: connection, dataId: dataId, group: group, confirmed: confirmed, allowWrite: false) } afterSuccess: { + await self.loadNacosConfigs(dataId: self.nacosConfigSearchDataID, group: self.nacosConfigSearchGroup) self.nacosSelectedConfig = nil - self.nacosConfigs.removeAll { $0.dataId == dataId && $0.group == group } } } @@ -1378,6 +1488,8 @@ final class DatabaseFeatureModel: ObservableObject { if page == 1 { nacosServices = [] nacosServiceTotalCount = 0 + nacosInstances = [] + nacosInstanceRequestID = nil } setConnectionStatus(.connecting, for: profile.id) do { @@ -1391,6 +1503,15 @@ final class DatabaseFeatureModel: ObservableObject { setConnectionStatus(.connected, for: profile.id) nacosServices = result.items nacosServiceTotalCount = result.totalCount + if let selectedName = nacosSelectedServiceName, let selectedGroup = nacosSelectedServiceGroup { + if result.items.contains(where: { $0.name == selectedName && $0.group == selectedGroup }) { + await loadNacosInstances(serviceName: selectedName, group: selectedGroup) + } else { + nacosSelectedServiceName = nil + nacosSelectedServiceGroup = nil + nacosInstances = [] + } + } } catch { let sanitizedError = executionError(error) let duration = max(0, Int(Date().timeIntervalSince(startedAt) * 1_000)) @@ -1405,6 +1526,8 @@ final class DatabaseFeatureModel: ObservableObject { func loadNacosInstances(serviceName: String, group: String) async { guard let profile = selectedProfile, profile.kind == .nacos else { return } let generation = profileGeneration + nacosSelectedServiceName = serviceName + nacosSelectedServiceGroup = group let requestID = UUID() nacosInstanceRequestID = requestID let startedAt = Date() @@ -1471,12 +1594,17 @@ final class DatabaseFeatureModel: ObservableObject { redisKeys = [] redisNextCursor = "0" redisSelectedKey = nil + redisScanPattern = "*" nacosConfigs = [] nacosConfigTotalCount = 0 nacosSelectedConfig = nil + nacosConfigSearchDataID = "" + nacosConfigSearchGroup = "" nacosServices = [] nacosServiceTotalCount = 0 nacosInstances = [] + nacosSelectedServiceName = nil + nacosSelectedServiceGroup = nil } private func migrateLegacyGroupsIfNeeded() { @@ -1574,6 +1702,8 @@ final class DatabaseFeatureModel: ObservableObject { private func activateProfile(_ profile: DatabaseProfile) { profileGeneration &+= 1 + tableListRequestID = nil + databaseListRequestID = nil tableRequestID = nil redisScanRequestID = nil redisDetailRequestID = nil @@ -1609,6 +1739,8 @@ final class DatabaseFeatureModel: ObservableObject { private func clearProfileScopedState() { profileGeneration &+= 1 + tableListRequestID = nil + databaseListRequestID = nil tableRequestID = nil redisScanRequestID = nil redisDetailRequestID = nil diff --git a/Sources/Lithe/Application/DatabaseSQLSupport.swift b/Sources/Lithe/Application/DatabaseSQLSupport.swift index 0dd1f59efd..43ea03b050 100644 --- a/Sources/Lithe/Application/DatabaseSQLSupport.swift +++ b/Sources/Lithe/Application/DatabaseSQLSupport.swift @@ -26,6 +26,7 @@ enum DatabaseSQLStatementKind: String, Codable, Equatable, Sendable { case mutation case definition case transaction + case batch case unknown var usesQueryEndpoint: Bool { @@ -38,8 +39,28 @@ struct DatabaseSQLAnalysis: Equatable, Sendable { let statementCount: Int let requiresConfirmation: Bool let warning: String? + let statements: [String] - var canExecute: Bool { statementCount == 1 } + var canExecute: Bool { !statements.isEmpty || statementCount == 1 } + + init( + kind: DatabaseSQLStatementKind, + statementCount: Int, + requiresConfirmation: Bool, + warning: String?, + statements: [String] = [] + ) { + self.kind = kind + self.statementCount = statementCount + self.requiresConfirmation = requiresConfirmation + self.warning = warning + self.statements = statements + } +} + +enum DatabaseSQLExecutionScope: Equatable, Sendable { + case all + case selection(String) } struct DatabaseSQLTab: Identifiable, Equatable, Sendable { @@ -111,18 +132,37 @@ struct DatabaseSQLHistoryEntry: Codable, Equatable, Identifiable, Sendable { enum DatabaseSQLAnalyzer { static func analyze(_ sql: String) -> DatabaseSQLAnalysis { let statements = DatabaseSQLLexing.statements(in: sql) - guard statements.count == 1, let statement = statements.first else { + guard !statements.isEmpty else { return DatabaseSQLAnalysis( kind: .unknown, statementCount: statements.count, requiresConfirmation: false, - warning: statements.isEmpty ? "Enter a SQL statement." : "Run one SQL statement at a time." + warning: "Enter a SQL statement.", + statements: statements ) } + let analyses = statements.map(analyzeSingle) + let kinds = analyses.map(\.kind) + let kind = statements.count > 1 ? .batch : kinds[0] + return DatabaseSQLAnalysis( + kind: kind, + statementCount: statements.count, + requiresConfirmation: analyses.contains(where: \.requiresConfirmation), + warning: warning(for: analyses), + statements: statements + ) + } + + private static func warning(for analyses: [DatabaseSQLAnalysis]) -> String? { + let warnings = analyses.compactMap(\.warning) + return warnings.first(where: { !$0.contains("not recognized") }) ?? warnings.first + } + + private static func analyzeSingle(_ statement: String) -> DatabaseSQLAnalysis { let tokens = DatabaseSQLLexing.keywords(in: statement) guard let first = tokens.first else { - return DatabaseSQLAnalysis(kind: .unknown, statementCount: 0, requiresConfirmation: false, warning: "Enter a SQL statement.") + return DatabaseSQLAnalysis(kind: .unknown, statementCount: 0, requiresConfirmation: false, warning: "Enter a SQL statement.", statements: []) } let kind: DatabaseSQLStatementKind @@ -151,7 +191,7 @@ enum DatabaseSQLAnalyzer { } else { warning = nil } - return DatabaseSQLAnalysis(kind: kind, statementCount: 1, requiresConfirmation: requiresConfirmation, warning: warning) + return DatabaseSQLAnalysis(kind: kind, statementCount: 1, requiresConfirmation: requiresConfirmation, warning: warning, statements: [statement]) } } @@ -287,41 +327,99 @@ private enum DatabaseSQLLexing { var lineComment = false var blockComment = false + func appendCurrentStatement() { + guard !sanitized(current).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + statements.append(current) + } + while index < characters.count { let character = characters[index] let next = index + 1 < characters.count ? characters[index + 1] : nil if lineComment { - if character == "\n" { lineComment = false; current.append(" ") } - index += 1; continue + current.append(character) + if character == "\n" { lineComment = false } + index += 1 + continue } if blockComment { - if character == "*", next == "/" { blockComment = false; index += 2; current.append(" ") } - else { index += 1 } + current.append(character) + if character == "*", next == "/" { + current.append("/") + blockComment = false + index += 2 + } else { + index += 1 + } continue } if let activeQuote = quote { - current.append(" ") + current.append(character) + if character == "\\", next != nil { + current.append(next!) + index += 2 + continue + } if character == activeQuote { - if next == activeQuote { index += 1; current.append(" ") } + if next == activeQuote { index += 1; current.append(activeQuote) } else { quote = nil } } index += 1; continue } - if character == "-", next == "-" { lineComment = true; index += 2; current.append(" "); continue } - if character == "/", next == "*" { blockComment = true; index += 2; current.append(" "); continue } - if character == "'" || character == "\"" || character == "`" { quote = character; current.append(" "); index += 1; continue } + if character == "-", next == "-" { lineComment = true; current.append(character); current.append(next!); index += 2; continue } + if character == "/", next == "*" { blockComment = true; current.append(character); current.append(next!); index += 2; continue } + if character == "'" || character == "\"" || character == "`" { quote = character; current.append(character); index += 1; continue } if character == ";" { - if !current.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { statements.append(current) } + appendCurrentStatement() current = ""; index += 1; continue } current.append(character) index += 1 } - if !current.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { statements.append(current) } + appendCurrentStatement() return statements } private static func sanitized(_ sql: String) -> String { - statements(in: sql).joined(separator: " ") + let characters = Array(sql) + var output = "" + var index = 0 + var quote: Character? + var lineComment = false + var blockComment = false + while index < characters.count { + let character = characters[index] + let next = index + 1 < characters.count ? characters[index + 1] : nil + if lineComment { + if character == "\n" { lineComment = false; output.append(" ") } + index += 1 + continue + } + if blockComment { + if character == "*", next == "/" { blockComment = false; index += 2; output.append(" ") } + else { index += 1 } + continue + } + if let activeQuote = quote { + if character == "\\", next != nil { + output.append(" ") + index += 2 + continue + } + if character == activeQuote { + if next == activeQuote { index += 2 } + else { quote = nil; index += 1 } + } else { + index += 1 + } + output.append(" ") + continue + } + if character == "-", next == "-" { lineComment = true; index += 2; output.append(" "); continue } + if character == "/", next == "*" { blockComment = true; index += 2; output.append(" "); continue } + if character == "'" || character == "\"" || character == "`" { quote = character; index += 1; output.append(" "); continue } + output.append(character) + index += 1 + } + return output } } diff --git a/Sources/Lithe/Views/DatabaseLocalization.swift b/Sources/Lithe/Views/DatabaseLocalization.swift index 7e050e091d..494c10986e 100644 --- a/Sources/Lithe/Views/DatabaseLocalization.swift +++ b/Sources/Lithe/Views/DatabaseLocalization.swift @@ -54,6 +54,7 @@ enum DatabaseLocalization { case .mutation: Text("Data change") case .definition: Text("Schema change") case .transaction: Text("Transaction") + case .batch: Text("Batch") case .unknown: Text("Unknown") case nil: Text("None") } diff --git a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift index 52867cb053..83a254e949 100644 --- a/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift +++ b/Sources/Lithe/Views/DatabaseSQLWorkspaceView.swift @@ -12,8 +12,11 @@ struct DatabaseWorkspaceView: View { Task { await model.databaseFeature.select(profile) } }, onNewQuery: { profile in - Task { await model.databaseFeature.select(profile) } - model.databaseFeature.workspaceSection = .sql + Task { + await model.databaseFeature.select(profile) + guard model.databaseFeature.selectedProfileID == profile.id else { return } + model.databaseFeature.workspaceSection = .sql + } } ) } else if model.databaseFeature.selectedProfile?.kind == .redis { @@ -108,6 +111,7 @@ private struct DatabaseDashboardView: View { let onNewQuery: (DatabaseProfile) -> Void private var profiles: [DatabaseProfile] { model.databaseFeature.profiles } + private var sqlProfiles: [DatabaseProfile] { profiles.filter { $0.kind.isSQLDatabase } } private var databaseTypeCount: Int { Set(profiles.map(\.kind)).count } private var connectedCount: Int { model.databaseFeature.connectedProfileCount } private let dashboardColumns = [ @@ -134,8 +138,8 @@ private struct DatabaseDashboardView: View { dashboardSection(title: "Common Actions", symbol: "wand.and.stars") { LazyVGrid(columns: dashboardColumns, spacing: 1) { dashboardAction("New Connection", symbol: "plus") { showsConnectionEditor = true } - dashboardAction("New Query", symbol: "doc.badge.plus", isEnabled: !profiles.isEmpty) { - if let first = profiles.first { onNewQuery(first) } + dashboardAction("New Query", symbol: "doc.badge.plus", isEnabled: !sqlProfiles.isEmpty) { + if let first = sqlProfiles.first { onNewQuery(first) } } dashboardAction("Browse Database", symbol: "tablecells", isEnabled: !profiles.isEmpty) { if let first = profiles.first { onOpenConnection(first) } @@ -152,25 +156,31 @@ private struct DatabaseDashboardView: View { dashboardSection( title: "Recent SQL", symbol: "clock.arrow.circlepath", - minHeight: max(160, geometry.size.height - 288) + minHeight: max(160, min(320, geometry.size.height - 288)) ) { if model.databaseFeature.sqlHistory.isEmpty { dashboardEmpty("No SQL history yet.") } else { ForEach(Array(model.databaseFeature.sqlHistory.prefix(8))) { entry in - HStack(spacing: 10) { - Image(systemName: "terminal") - .foregroundStyle(LitheTheme.accent) - Text(entry.sql.replacingOccurrences(of: "\n", with: " ")) - .font(.system(size: 10.5, design: .monospaced)) - .lineLimit(1) - Spacer() - Text(entry.executedAt, style: .relative) - .font(.system(size: 9.5)) - .foregroundStyle(LitheTheme.tertiaryText) + Button { openHistoryEntry(entry) } label: { + HStack(spacing: 10) { + Image(systemName: "terminal") + .foregroundStyle(LitheTheme.accent) + Text(entry.sql.replacingOccurrences(of: "\n", with: " ")) + .font(.system(size: 10.5, design: .monospaced)) + .lineLimit(1) + Spacer() + Text(entry.executedAt, style: .relative) + .font(.system(size: 9.5)) + .foregroundStyle(LitheTheme.tertiaryText) + } + .padding(.horizontal, 12) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: 36) } - .padding(.horizontal, 12) - .frame(height: 36) + .buttonStyle(.plain) + .disabled(profiles.first(where: { $0.id == entry.profileID })?.kind.isSQLDatabase != true) + .litheRowHover(cornerRadius: 0) } } } @@ -217,7 +227,7 @@ private struct DatabaseDashboardView: View { .frame(maxWidth: .infinity) .frame(height: 97) } else { - let quickProfiles = Array(profiles.prefix(2)) + let quickProfiles = profiles ForEach(quickProfiles) { profile in quickStartRow(profile) if profile.id != quickProfiles.last?.id || quickProfiles.count == 1 { @@ -269,23 +279,35 @@ private struct DatabaseDashboardView: View { } .buttonStyle(.plain) - Button { onNewQuery(profile) } label: { - Image(systemName: "doc.badge.plus") - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(LitheTheme.secondaryText) - .frame(width: 40, height: 40) - .contentShape(Rectangle()) + if profile.kind.isSQLDatabase { + Button { onNewQuery(profile) } label: { + Image(systemName: "doc.badge.plus") + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(LitheTheme.secondaryText) + .frame(width: 40, height: 40) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .lithePointer() + .help("New Query") + .accessibilityLabel("New Query") + .padding(.trailing, 6) } - .buttonStyle(.plain) - .lithePointer() - .help("New Query") - .accessibilityLabel("New Query") - .padding(.trailing, 6) } .lithePointer() .litheRowHover(cornerRadius: 0) } + private func openHistoryEntry(_ entry: DatabaseSQLHistoryEntry) { + guard let profile = profiles.first(where: { $0.id == entry.profileID }), profile.kind.isSQLDatabase else { return } + Task { + await model.databaseFeature.select(profile) + guard model.databaseFeature.selectedProfileID == profile.id else { return } + model.databaseFeature.workspaceSection = .sql + model.databaseFeature.restoreSQLHistory(entry) + } + } + private func metricCard(title: LocalizedStringKey, value: Int, symbol: String) -> some View { VStack(alignment: .leading, spacing: 12) { Label(title, systemImage: symbol) @@ -470,7 +492,10 @@ private extension DatabaseKind { struct DatabaseSQLWorkspaceView: View { @EnvironmentObject private var model: AppModel @State private var pendingRisk: DatabaseSQLAnalysis? + @State private var pendingScope: DatabaseSQLExecutionScope = .all + @State private var pendingTabID: UUID? @State private var showsRiskConfirmation = false + @State private var sqlSelection = "" var body: some View { VStack(spacing: 0) { @@ -484,16 +509,23 @@ struct DatabaseSQLWorkspaceView: View { } .background(LitheTheme.editor) .alert("Confirm database change", isPresented: $showsRiskConfirmation, presenting: pendingRisk) { analysis in - Button("Cancel", role: .cancel) { pendingRisk = nil } - Button("Run statement", role: .destructive) { - if let tabID = model.databaseFeature.selectedSQLTabID { - Task { await model.databaseFeature.runSQL(in: tabID, confirmedRisk: true) } + Button("Cancel", role: .cancel) { + pendingRisk = nil + pendingTabID = nil + } + Button(analysis.statementCount > 1 ? "Run batch" : "Run statement", role: .destructive) { + if let tabID = pendingTabID { + Task { await model.databaseFeature.runSQL(in: tabID, scope: pendingScope, confirmedRisk: true) } } pendingRisk = nil + pendingTabID = nil } } message: { analysis in DatabaseLocalization.text(analysis.warning ?? "This statement can change the database.") } + .onChange(of: model.databaseFeature.selectedSQLTabID) { _, _ in + sqlSelection = "" + } } private var queryTabs: some View { @@ -550,7 +582,24 @@ struct DatabaseSQLWorkspaceView: View { .buttonStyle(.borderedProminent) .controlSize(.small) .disabled(model.databaseFeature.selectedSQLTab?.isRunning == true || model.databaseFeature.selectedProfile == nil) - .help("Run SQL (Command-Return)") + .help(hasSQLSelection ? "Run selected SQL (Command-Return)" : "Run all SQL (Command-Return)") + + Menu { + Button { runAllQuery() } label: { + Label("Run All", systemImage: "play.fill") + } + Button { runSelectionQuery() } label: { + Label("Run Selection", systemImage: "text.cursor") + } + .disabled(!hasSQLSelection) + } label: { + Image(systemName: "chevron.down") + .font(.system(size: 9, weight: .semibold)) + } + .menuStyle(.borderlessButton) + .frame(width: 18) + .disabled(model.databaseFeature.selectedSQLTab?.isRunning == true || model.databaseFeature.selectedProfile == nil) + .help("Choose SQL execution scope") Button { if let id = model.databaseFeature.selectedSQLTabID { model.databaseFeature.formatSQL(in: id) } } label: { Image(systemName: "text.alignleft") @@ -605,8 +654,10 @@ struct DatabaseSQLWorkspaceView: View { set: { model.databaseFeature.updateSQL($0, in: tab.id) } ), completions: model.databaseFeature.sqlCompletionItems, - onRun: runSelectedQuery + onRun: runSelectedQuery, + onSelectionChange: { sqlSelection = $0 } ) + .id(tab.id) .frame(minHeight: 180, idealHeight: 240, maxHeight: 320) .overlay(alignment: .bottomLeading) { if let error = tab.errorMessage { @@ -642,7 +693,8 @@ struct DatabaseSQLWorkspaceView: View { } } } else if let affected = model.databaseFeature.selectedSQLTab?.rowsAffected { - ContentUnavailableView("Statement completed", systemImage: "checkmark.circle", description: Text("Rows affected: \(affected)")) + let count = model.databaseFeature.selectedSQLTab.map { model.databaseFeature.analysis(forSQLTab: $0.id).statementCount } ?? 1 + ContentUnavailableView(count > 1 ? "Statements completed" : "Statement completed", systemImage: "checkmark.circle", description: Text("Rows affected: \(affected)")) .foregroundStyle(LitheTheme.secondaryText) } else { ContentUnavailableView("Query Results", systemImage: "tablecells", description: Text("Run a SELECT, SHOW, DESCRIBE, or EXPLAIN statement to inspect results.")) @@ -656,17 +708,43 @@ struct DatabaseSQLWorkspaceView: View { } private func runSelectedQuery() { + if hasSQLSelection { + run(scope: .selection(sqlSelection)) + } else { + runAllQuery() + } + } + + private func runAllQuery() { + run(scope: .all) + } + + private func runSelectionQuery() { + guard hasSQLSelection else { return } + run(scope: .selection(sqlSelection)) + } + + private func run(scope: DatabaseSQLExecutionScope) { guard let tabID = model.databaseFeature.selectedSQLTabID else { return } - let analysis = model.databaseFeature.analysis(forSQLTab: tabID) + let analysis = model.databaseFeature.analysis(forSQLTab: tabID, scope: scope) if analysis.requiresConfirmation { pendingRisk = analysis + pendingScope = scope + pendingTabID = tabID showsRiskConfirmation = true } else { - Task { await model.databaseFeature.runSQL(in: tabID) } + Task { await model.databaseFeature.runSQL(in: tabID, scope: scope) } } } + private var hasSQLSelection: Bool { + !sqlSelection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + private func executionLabel(_ execution: DatabaseSQLExecution) -> Text { + if let rows = execution.rowsReturned, let affected = execution.rowsAffected { + return Text("\(rows) rows, \(affected) affected \(execution.durationMilliseconds) ms") + } if let rows = execution.rowsReturned { return Text("\(rows) rows \(execution.durationMilliseconds) ms") } if let affected = execution.rowsAffected { return Text("\(affected) affected \(execution.durationMilliseconds) ms") } return Text("\(execution.durationMilliseconds) ms") @@ -1177,8 +1255,9 @@ private struct SQLSyntaxEditor: NSViewRepresentable { @Binding var text: String let completions: [String] let onRun: () -> Void + let onSelectionChange: (String) -> Void - func makeCoordinator() -> Coordinator { Coordinator(text: $text, completions: completions, onRun: onRun) } + func makeCoordinator() -> Coordinator { Coordinator(text: $text, completions: completions, onRun: onRun, onSelectionChange: onSelectionChange) } func makeNSView(context: Context) -> NSScrollView { let scrollView = NSScrollView() @@ -1211,6 +1290,7 @@ private struct SQLSyntaxEditor: NSViewRepresentable { textView.textContainer?.widthTracksTextView = false textView.completionItems = completions textView.onRun = onRun + context.coordinator.onSelectionChange = onSelectionChange context.coordinator.textView = textView context.coordinator.highlight() scrollView.documentView = textView @@ -1220,12 +1300,15 @@ private struct SQLSyntaxEditor: NSViewRepresentable { func updateNSView(_ scrollView: NSScrollView, context: Context) { guard let textView = scrollView.documentView as? SQLTextView else { return } context.coordinator.completions = completions + context.coordinator.onSelectionChange = onSelectionChange textView.completionItems = completions textView.onRun = onRun if textView.string != text, !textView.hasMarkedText(), !context.coordinator.isApplyingChange { let selection = textView.selectedRange() textView.string = text - textView.setSelectedRange(NSRange(location: min(selection.location, text.utf16.count), length: 0)) + let location = min(selection.location, text.utf16.count) + let length = min(selection.length, text.utf16.count - location) + textView.setSelectedRange(NSRange(location: location, length: length)) context.coordinator.highlight() } } @@ -1235,13 +1318,15 @@ private struct SQLSyntaxEditor: NSViewRepresentable { private var text: Binding var completions: [String] let onRun: () -> Void + var onSelectionChange: (String) -> Void weak var textView: SQLTextView? var isApplyingChange = false - init(text: Binding, completions: [String], onRun: @escaping () -> Void) { + init(text: Binding, completions: [String], onRun: @escaping () -> Void, onSelectionChange: @escaping (String) -> Void) { self.text = text self.completions = completions self.onRun = onRun + self.onSelectionChange = onSelectionChange } func textDidChange(_ notification: Notification) { @@ -1252,6 +1337,16 @@ private struct SQLSyntaxEditor: NSViewRepresentable { isApplyingChange = false } + func textViewDidChangeSelection(_ notification: Notification) { + guard let textView else { return } + let range = textView.selectedRange() + guard range.length > 0, range.location + range.length <= textView.string.utf16.count else { + onSelectionChange("") + return + } + onSelectionChange((textView.string as NSString).substring(with: range)) + } + func textView( _ textView: NSTextView, completions words: [String], diff --git a/Sources/Lithe/Views/DatabaseSidebarView.swift b/Sources/Lithe/Views/DatabaseSidebarView.swift index f17b6617bc..d89d9d24b6 100644 --- a/Sources/Lithe/Views/DatabaseSidebarView.swift +++ b/Sources/Lithe/Views/DatabaseSidebarView.swift @@ -1736,7 +1736,7 @@ struct DatabaseConnectionEditor: View { Rectangle().fill(LitheTheme.divider).frame(height: 1) Form { TextField("Name", text: $name) - Picker("Database", selection: $kind) { + Picker("Engine", selection: $kind) { Text("MySQL").tag(DatabaseKind.mysql) Text("MariaDB").tag(DatabaseKind.mariadb) Text("PostgreSQL").tag(DatabaseKind.postgresql) @@ -1779,7 +1779,7 @@ struct DatabaseConnectionEditor: View { .font(.system(size: 10.5)) .foregroundStyle(LitheTheme.secondaryText) } else { - TextField("Database", text: $database) + TextField("Database name", text: $database) } Toggle("Use TLS", isOn: $ssl) } @@ -1823,9 +1823,16 @@ struct DatabaseConnectionEditor: View { Rectangle().fill(LitheTheme.divider).frame(height: 1) HStack(spacing: 8) { Spacer() - Button("Cancel") { isPresented = false } + Button("Cancel") { cancel() } .buttonStyle(LitheSecondaryButtonStyle()) - Button("Connect") { connect() } + Button { + connect() + } label: { + HStack(spacing: 6) { + if model.databaseFeature.isLoading { ProgressView().controlSize(.small) } + Text(model.databaseFeature.isLoading ? "Connecting…" : "Connect") + } + } .buttonStyle(LithePrimaryButtonStyle()) .disabled(name.isEmpty || (kind == .sqlite ? path.isEmpty : host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) || redisDatabaseValidationMessage != nil || model.databaseFeature.isLoading) } @@ -1847,13 +1854,20 @@ struct DatabaseConnectionEditor: View { } } .onAppear { + model.databaseFeature.errorMessage = nil if let profile { hasSavedPassword = model.databaseFeature.hasSavedPassword(for: profile) } } + .onDisappear { model.databaseFeature.errorMessage = nil } .frame(width: 500, height: kind == .sqlite ? 640 : (kind.supportsDataGrid ? 750 : 710)).background(LitheTheme.raised) } + private func cancel() { + model.databaseFeature.errorMessage = nil + isPresented = false + } + private func connect() { if let redisDatabaseValidationMessage { model.databaseFeature.errorMessage = redisDatabaseValidationMessage diff --git a/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift b/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift index e9aa4392cc..439632f764 100644 --- a/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift +++ b/Sources/Lithe/Views/DatabaseSpecializedWorkspaceViews.swift @@ -111,6 +111,7 @@ struct RedisWorkspaceView: View { .onSubmit { Task { await feature.loadRedisKeys(pattern: pattern) } } Button { Task { await feature.loadRedisKeys(pattern: pattern) } } label: { Image(systemName: "magnifyingglass") } .litheIconButton().help("Search keys with SCAN") + .disabled(feature.isLoading || profile == nil) } .padding(10) Rectangle().fill(LitheTheme.divider).frame(height: 1) @@ -121,8 +122,22 @@ struct RedisWorkspaceView: View { } } - if feature.redisKeys.isEmpty && !feature.isLoading { - specializedEmptyState(symbol: "magnifyingglass", title: "No keys loaded", detail: "Search with a Redis pattern to scan this database incrementally.") + if feature.redisKeys.isEmpty && feature.isLoading { + VStack(spacing: 9) { + ProgressView().controlSize(.small) + Text("Scanning keys…") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(LitheTheme.secondaryText) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if feature.redisKeys.isEmpty { + specializedEmptyState( + symbol: "magnifyingglass", + title: feature.errorMessage == nil ? "No matching keys" : "No keys loaded", + detail: feature.errorMessage == nil + ? "No keys matched this pattern. Try a broader pattern to search again." + : "Retry the scan after fixing the connection or authentication settings." + ) } else { ScrollView { LazyVStack(alignment: .leading, spacing: 2) { @@ -380,7 +395,13 @@ struct NacosWorkspaceView: View { await feature.loadNacosServices(serviceName: serviceSearch, group: serviceGroupSearch) } .onChange(of: feature.nacosSelectedConfig) { _, detail in - guard let detail else { return } + guard let detail else { + draftDataID = "" + draftGroup = "DEFAULT_GROUP" + draftType = "" + draftContent = "" + return + } draftDataID = detail.dataId; draftGroup = detail.group; draftType = detail.type ?? ""; draftContent = detail.content } .alert("Confirm Nacos configuration change", isPresented: $showsWriteConfirmation, presenting: pendingAction) { _ in diff --git a/Sources/Lithe/Views/DatabaseTableView.swift b/Sources/Lithe/Views/DatabaseTableView.swift index 320d977e1a..dfd034f95b 100644 --- a/Sources/Lithe/Views/DatabaseTableView.swift +++ b/Sources/Lithe/Views/DatabaseTableView.swift @@ -42,6 +42,18 @@ struct DatabaseTableView: View { queryClauseBar dataActionBar } + if let error = model.databaseFeature.errorMessage, model.databaseFeature.selectedTable != nil { + Label { + DatabaseLocalization.error(error) + } icon: { + Image(systemName: "exclamationmark.triangle.fill") + } + .font(.system(size: 10.5)) + .foregroundStyle(LitheTheme.error) + .padding(.horizontal, 12) + .frame(maxWidth: .infinity, minHeight: 28, alignment: .leading) + .background(LitheTheme.toolHeader) + } Rectangle().fill(LitheTheme.divider).frame(height: 1) if model.databaseFeature.selectedTable == nil { DatabaseTableEmptyState(hasConnection: model.databaseFeature.selectedProfile != nil) @@ -256,6 +268,15 @@ struct DatabaseTableView: View { Button("Paste TSV from Clipboard") { pasteFromClipboard() } } label: { Text("TSV") } .menuStyle(.borderlessButton).frame(width: 52) + Button { + rowDetailsIndex = selectedRows.first + } label: { + Image(systemName: "list.bullet.rectangle") + } + .litheIconButton() + .help("Row details") + .accessibilityLabel("Row details") + .disabled(selectedRows.count != 1) Button { insertedRows.append([:]) } label: { Label("Add Row", systemImage: "plus") } .buttonStyle(.plain).font(.system(size: 10.5, weight: .medium)) .disabled(model.databaseFeature.selectedProfile?.readOnly == true) diff --git a/Tests/LitheTests/LitheCoreLogicTests.swift b/Tests/LitheTests/LitheCoreLogicTests.swift index d337c1a01e..14b39dc144 100644 --- a/Tests/LitheTests/LitheCoreLogicTests.swift +++ b/Tests/LitheTests/LitheCoreLogicTests.swift @@ -487,6 +487,51 @@ struct LitheCoreLogicTests { #expect(store.load().first?.database == "beta") } + @Test + @MainActor + func databaseRefreshingTablesReloadsTheCurrentlyOpenTable() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "SQLite", kind: .sqlite, path: "/tmp/lithe-refresh.sqlite") + try store.save([profile]) + let pageCounter = TestCounter() + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let result: String + switch method { + case "listTables": + result = #"[{"table_name":"items"}]"# + case "describeTable": + result = #"[{"column_name":"id","data_type":"integer","column_key":"PRI"}]"# + case "pageTable": + pageCounter.value += 1 + result = #"{"columns":["id"],"rows":[{"id":\#(pageCounter.value)}],"truncated":false,"totalRows":1}"# + default: + result = "[]" + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":\#(result)}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + await feature.openTable("items") + #expect(feature.errorMessage == nil) + #expect(feature.rows.first?["id"] == DatabaseValue.integer(1)) + + await feature.refreshTables() + + #expect(feature.tables == ["items"]) + #expect(feature.selectedTable == "items") + #expect(feature.rows.first?["id"] == DatabaseValue.integer(2)) + #expect(pageCounter.value == 2) + } + @Test @MainActor func databaseInvalidSQLClearsPreviousExecutionState() async throws { @@ -589,6 +634,90 @@ struct LitheCoreLogicTests { #expect(feature.connectionStatus(for: profile) == .failed) } + @Test + @MainActor + func databaseRedisWriteRefreshesKeySummaryAndDetail() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "Redis", kind: .redis, host: "127.0.0.1", port: 6379, database: "0") + try store.save([profile]) + let scanCount = TestCounter() + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + switch method { + case "redisScan": + scanCount.value += 1 + let key = scanCount.value == 1 ? "session:old" : "session:new" + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"keys":[{"key":"\#(key)","type":"string","ttl":60,"size":9}],"nextCursor":"0"}}"#, exitCode: 0) + case "redisSetString": + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{}}"#, exitCode: 0) + case "redisGetKey": + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"key":"session:new","type":"string","ttl":120,"size":12,"stringValue":"updated","hashEntries":[]}}"#, exitCode: 0) + default: + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{}}"#, exitCode: 0) + } + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + await feature.loadRedisKeys(pattern: "session:*") + #expect(feature.redisKeys.first?.key == "session:old") + + #expect(await feature.saveRedisString(key: "session:new", value: "updated", ttl: 120, confirmed: true)) + #expect(feature.redisKeys.first?.key == "session:new") + #expect(feature.redisSelectedKey?.key == "session:new") + #expect(feature.redisSelectedKey?.ttl == 120) + #expect(scanCount.value == 2) + } + + @Test + @MainActor + func databaseNacosPublishRefreshesConfigListAndDetail() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "Nacos", kind: .nacos, host: "127.0.0.1", port: 8848, database: "public") + try store.save([profile]) + let listCount = TestCounter() + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + switch method { + case "nacosListConfigs": + listCount.value += 1 + let dataID = listCount.value == 1 ? "old.yaml" : "new.yaml" + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"items":[{"dataId":"\#(dataID)","group":"DEFAULT_GROUP","namespace":"public","type":"yaml","md5":"abc"}],"totalCount":1}}"#, exitCode: 0) + case "nacosPublishConfig": + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{}}"#, exitCode: 0) + case "nacosGetConfig": + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"dataId":"new.yaml","group":"DEFAULT_GROUP","namespace":"public","type":"yaml","md5":"def","content":"updated"}}"#, exitCode: 0) + default: + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{}}"#, exitCode: 0) + } + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + await feature.loadNacosConfigs(dataId: "", group: "") + #expect(feature.nacosConfigs.first?.dataId == "old.yaml") + + #expect(await feature.publishNacosConfig(dataId: "new.yaml", group: "DEFAULT_GROUP", content: "updated", type: "yaml", confirmed: true)) + #expect(feature.nacosConfigs.first?.dataId == "new.yaml") + #expect(feature.nacosSelectedConfig?.dataId == "new.yaml") + #expect(feature.nacosSelectedConfig?.content == "updated") + #expect(listCount.value == 2) + } + @Test @MainActor func databaseConnectionStatusTracksSuccessfulConnection() async throws { @@ -710,6 +839,128 @@ struct LitheCoreLogicTests { #expect(invalid.warning?.contains("not recognized") == true) } + @Test + func databaseSQLAnalyzerSplitsBatchesWithoutBreakingQuotedSemicolons() { + let analysis = DatabaseSQLAnalyzer.analyze("SELECT ';' AS marker; -- keep this comment\nSELECT 2;") + + #expect(analysis.canExecute) + #expect(analysis.statementCount == 2) + #expect(analysis.kind == .batch) + #expect(analysis.statements.first?.contains("';'") == true) + #expect(analysis.statements.last?.contains("SELECT 2") == true) + + let escapedQuote = DatabaseSQLAnalyzer.analyze(#"SELECT 'a\';b'; SELECT 2"#) + #expect(escapedQuote.statementCount == 2) + + let commentsOnly = DatabaseSQLAnalyzer.analyze("-- review later\n/* no statement */") + #expect(!commentsOnly.canExecute) + #expect(commentsOnly.statementCount == 0) + } + + @Test + @MainActor + func databaseSQLBatchRunsInOrderAndAggregatesResults() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "SQLite", kind: .sqlite, path: "/tmp/lithe-batch.sqlite") + try store.save([profile]) + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let params = object["params"] as? [String: Any] + let sql = params?["sql"] as? String ?? "" + switch method { + case "exportSqlToFile": + if let path = params?["outputPath"] as? String { + try? Data().write(to: URL(fileURLWithPath: path)) + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"path":"/tmp/backup.sql","byteCount":0,"sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}}"#, exitCode: 0) + case "query": + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"rows":[{"value":1}],"columns":["value"],"truncated":false}}"#, exitCode: 0) + case "execute": + let affected = sql.contains("UPDATE") ? 3 : 2 + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"rowsAffected":\#(affected)}}"#, exitCode: 0) + default: + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":[]}"#, exitCode: 0) + } + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + feature.addSQLTab(sql: "INSERT INTO items VALUES (1); SELECT 1; UPDATE items SET value = 2 WHERE id = 1;") + let tabID = try #require(feature.selectedSQLTabID) + await feature.runSQL(in: tabID) + + let sqlRequests = runner.requests.compactMap { request -> (String, String)? in + guard let input = request.standardInput, + let object = try? JSONSerialization.jsonObject(with: input) as? [String: Any], + let method = object["method"] as? String, + method == "query" || method == "execute", + let params = object["params"] as? [String: Any], + let sql = params["sql"] as? String else { return nil } + return (method, sql) + } + #expect(sqlRequests.map(\.0) == ["execute", "query", "execute"]) + #expect(sqlRequests.map(\.1) == [ + "INSERT INTO items VALUES (1)", + "SELECT 1", + "UPDATE items SET value = 2 WHERE id = 1" + ]) + #expect(feature.selectedSQLTab?.result?.rows.count == 1) + #expect(feature.selectedSQLTab?.rowsAffected == 5) + #expect(feature.selectedSQLTab?.execution?.rowsReturned == 1) + #expect(feature.sqlHistory.first?.sql.contains("SELECT 1") == true) + } + + @Test + @MainActor + func databaseSQLBatchStopsAfterTheFirstFailedStatement() async throws { + let preferences = DatabaseTestKeyValueStore() + let store = DatabaseConnectionStore(store: preferences, secureStore: DatabaseTestSecureStore()) + let profile = DatabaseProfile(name: "SQLite", kind: .sqlite, path: "/tmp/lithe-batch-failure.sqlite") + try store.save([profile]) + let runner = RecordingProcessRunner { request in + let input = try! #require(request.standardInput) + let object = try! JSONSerialization.jsonObject(with: input) as! [String: Any] + let id = object["id"] as! String + let method = object["method"] as! String + let params = object["params"] as? [String: Any] + let sql = params?["sql"] as? String ?? "" + if method == "query", sql.contains("bad") { + return ProcessResult(output: #"{"id":"\#(id)","ok":false,"error":{"code":"syntax_error","message":"near bad"}}"#, exitCode: 0) + } + if method == "query" { + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":{"rows":[{"value":1}],"columns":["value"],"truncated":false}}"#, exitCode: 0) + } + return ProcessResult(output: #"{"id":"\#(id)","ok":true,"result":[]}"#, exitCode: 0) + } + let feature = DatabaseFeatureModel( + operations: DatabaseSidecarService(processRunner: runner, executableURL: URL(fileURLWithPath: "/tmp/lithe-db-sidecar")), + connectionStore: store + ) + + await feature.select(profile) + feature.addSQLTab(sql: "SELECT 1; SELECT bad; SELECT 3;") + let tabID = try #require(feature.selectedSQLTabID) + await feature.runSQL(in: tabID) + + let querySQL = runner.requests.compactMap { request -> String? in + guard let input = request.standardInput, + let object = try? JSONSerialization.jsonObject(with: input) as? [String: Any], + object["method"] as? String == "query", + let params = object["params"] as? [String: Any] else { return nil } + return params["sql"] as? String + } + #expect(querySQL == ["SELECT 1", "SELECT bad"]) + #expect(feature.selectedSQLTab?.errorMessage?.contains("Statement 2 failed") == true) + #expect(feature.sqlHistory.isEmpty) + } + @Test func databaseQueryResultPreservesProtocolColumnOrder() throws { let data = Data(#"{"columns":["z_col","a_col"],"rows":[{"z_col":1,"a_col":2}],"truncated":false}"#.utf8)