Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

fix(redis): scope query tabs and command sequences

Tobifbb93d240aa7
diff --git a/macos/App/State/AppState.swift b/macos/App/State/AppState.swift
index 0b04b27..a6ddcfd 100644
--- a/macos/App/State/AppState.swift
+++ b/macos/App/State/AppState.swift
@@ -120,6 +120,12 @@ final class AppState: ObservableObject {
let databaseSize: Int?
}
+ struct RedisCLIStatementExecution {
+ let statement: String
+ let result: Result<QueryResult, Error>
+ let duration: TimeInterval
+ }
+
private(set) var redisSessionID: UUID?
private(set) var redisDatabaseRevision: UInt64 = 0
@@ -713,9 +719,12 @@ final class AppState: ObservableObject {
do {
let result = try await execute(adapter, command)
+ let outcome: RedisDatabaseTransitionOutcome = Self.redisSelectSucceeded(in: result)
+ ? .success(databaseName: databaseName)
+ : .failure
let ownsPublication = finishRedisDatabaseTransition(
token,
- outcome: .success(databaseName: databaseName)
+ outcome: outcome
)
guard ownsPublication, !Task.isCancelled else { return nil }
return Result<QueryResult, Error>.success(result)
@@ -738,6 +747,94 @@ final class AppState: ObservableObject {
}
}
+ func performRedisCLIStatements(
+ _ statements: [String],
+ from context: RedisTabContext
+ ) async -> [RedisCLIStatementExecution]? {
+ await performRedisCLIStatements(statements, from: context) { adapter, command in
+ try await adapter.executeRaw(sql: command)
+ }
+ }
+
+ func performRedisCLIStatements(
+ _ statements: [String],
+ from context: RedisTabContext,
+ execute: (RedisAdapter, String) async throws -> QueryResult
+ ) async -> [RedisCLIStatementExecution]? {
+ let commands = statements
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ guard !commands.isEmpty else { return [] }
+
+ if !commands.contains(where: { Self.redisDatabaseNameSelected(by: $0) != nil }) {
+ let ownedResult = await performRedisOperation(for: context) { adapter in
+ await Self.executeRedisCLICommands(
+ commands,
+ using: adapter,
+ execute: execute
+ )
+ }
+ guard case .success(let executions)? = ownedResult else { return nil }
+ return executions
+ }
+
+ let leaseRun = await withRedisOperationLease {
+ guard currentRedisContext == context, !Task.isCancelled else {
+ return Optional<[RedisCLIStatementExecution]>.none
+ }
+
+ var executions: [RedisCLIStatementExecution] = []
+ for command in commands {
+ let start = Date()
+ guard let result = await performRedisCLIStatement(command, execute: execute) else {
+ return nil
+ }
+ executions.append(
+ RedisCLIStatementExecution(
+ statement: command,
+ result: result,
+ duration: Date().timeIntervalSince(start)
+ )
+ )
+ if case .failure = result { break }
+ }
+ return executions
+ }
+
+ switch leaseRun {
+ case .completed(let executions):
+ return executions
+ case .cancelled:
+ return nil
+ }
+ }
+
+ private static func executeRedisCLICommands(
+ _ commands: [String],
+ using adapter: RedisAdapter,
+ execute: (RedisAdapter, String) async throws -> QueryResult
+ ) async -> [RedisCLIStatementExecution] {
+ var executions: [RedisCLIStatementExecution] = []
+ for command in commands {
+ let start = Date()
+ let result: Result<QueryResult, Error>
+ do {
+ result = .success(try await execute(adapter, command))
+ } catch {
+ result = .failure(error)
+ }
+ executions.append(
+ RedisCLIStatementExecution(
+ statement: command,
+ result: result,
+ duration: Date().timeIntervalSince(start)
+ )
+ )
+ if case .failure = result { break }
+ }
+ return executions
+ }
+
static func redisDatabaseNameSelected(by statement: String) -> String? {
let components = statement.split(whereSeparator: { $0.isWhitespace })
guard components.count == 2,
@@ -750,6 +847,15 @@ final class AppState: ObservableObject {
return "db\(index)"
}
+ private static func redisSelectSucceeded(in result: QueryResult) -> Bool {
+ guard result.columns.count == 1,
+ result.columns[0].name.caseInsensitiveCompare("result") == .orderedSame,
+ result.rows.count == 1,
+ result.rows[0].count == 1,
+ case .string(let value) = result.rows[0][0] else { return false }
+ return value.caseInsensitiveCompare("OK") == .orderedSame
+ }
+
@discardableResult
func loadRedisConnectionMetadata(
for token: RedisSessionRevisionToken,
@@ -1136,13 +1242,32 @@ final class AppState: ObservableObject {
}
func openNewQueryTab() {
+ if activeAdapter is RedisAdapter, currentRedisContext == nil { return }
+
let number = tabs.filter { $0.type == .queryEditor }.count + 1
- let tab = ContentTab(id: UUID(), type: .queryEditor, title: "Query \(number)", tableName: nil, schema: nil, databaseName: currentDatabaseName)
+ let tab = ContentTab(
+ id: UUID(),
+ type: .queryEditor,
+ title: "Query \(number)",
+ tableName: nil,
+ schema: nil,
+ databaseName: currentDatabaseName,
+ redisContext: currentRedisContext
+ )
tabs.append(tab)
activeTabId = tab.id
if let db = currentDatabaseName { ensureTabGroup(for: db) }
}
+ func rebindRedisQueryTab(id: UUID, to context: RedisTabContext) {
+ guard let index = tabs.firstIndex(where: {
+ $0.id == id && $0.type == .queryEditor && $0.redisContext != nil
+ }) else { return }
+ tabs[index].databaseName = context.databaseName
+ tabs[index].redisContext = context
+ ensureTabGroup(for: context.databaseName)
+ }
+
func closeTab(id: UUID) {
tabs.removeAll { $0.id == id }
if let state = dataGridCache.removeValue(forKey: id) {
diff --git a/macos/Presentation/Views/Main/MainView.swift b/macos/Presentation/Views/Main/MainView.swift
index 290adc5..04814a0 100644
--- a/macos/Presentation/Views/Main/MainView.swift
+++ b/macos/Presentation/Views/Main/MainView.swift
@@ -1237,7 +1237,15 @@ struct WorkspaceView: View {
)
}
case .queryEditor:
- QueryEditorView(tabId: tab.id)
+ if let context = tab.redisContext {
+ if appState.activeRedisAdapter(for: context) != nil {
+ QueryEditorView(tabId: tab.id)
+ } else {
+ redisContextMismatchView
+ }
+ } else {
+ QueryEditorView(tabId: tab.id)
+ }
case .tableStructure:
if let tableName = tab.tableName {
TableStructureView(tableName: tableName, schema: tab.schema)
diff --git a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
index 069d996..57c86e6 100644
--- a/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
+++ b/macos/Presentation/Views/QueryEditor/QueryEditorView.swift
@@ -260,6 +260,19 @@ struct QueryEditorView: View {
errorMessage = nil
statusMessage = nil
+ if adapter.databaseType == .redis {
+ guard let redisContext = appState.tabs.first(where: { $0.id == tabId })?.redisContext,
+ appState.activeRedisAdapter(for: redisContext) != nil else {
+ errorMessage = "This Redis query belongs to another connection or database."
+ isExecuting = false
+ return
+ }
+ Task {
+ await executeRedisStatements(toRun, from: redisContext)
+ }
+ return
+ }
+
// For MSSQL multi-batch scripts, use a dedicated connection so that
// USE statements persist across batches.
let isMultiBatchMSSQL = adapter.databaseType == .mssql && toRun.count > 1
@@ -281,16 +294,7 @@ struct QueryEditorView: View {
for stmt in toRun {
let start = Date()
do {
- let result: QueryResult
- if adapter.databaseType == .redis {
- guard let ownedResult = await appState.performRedisCLIStatement(stmt) else {
- isExecuting = false
- return
- }
- result = try ownedResult.get()
- } else {
- result = try await adapter.executeRaw(sql: stmt)
- }
+ let result = try await adapter.executeRaw(sql: stmt)
let duration = Date().timeIntervalSince(start)
appState.logQuery(sql: stmt, duration: duration)
appState.recordQueryHistory(sql: stmt, duration: duration, rowCount: result.rowCount)
@@ -348,6 +352,68 @@ struct QueryEditorView: View {
}
}
+ private func executeRedisStatements(
+ _ statements: [String],
+ from context: AppState.RedisTabContext
+ ) async {
+ let overallStart = Date()
+ guard let executions = await appState.performRedisCLIStatements(
+ statements,
+ from: context
+ ) else {
+ isExecuting = false
+ return
+ }
+
+ let containsDatabaseSelection = statements.contains {
+ AppState.redisDatabaseNameSelected(by: $0) != nil
+ }
+ if containsDatabaseSelection, let currentContext = appState.currentRedisContext {
+ appState.rebindRedisQueryTab(id: tabId, to: currentContext)
+ }
+
+ var lastResult: QueryResult?
+ var totalRowsAffected = 0
+ for execution in executions {
+ switch execution.result {
+ case .success(let result):
+ appState.logQuery(sql: execution.statement, duration: execution.duration)
+ appState.recordQueryHistory(
+ sql: execution.statement,
+ duration: execution.duration,
+ rowCount: result.rowCount
+ )
+ if !result.columns.isEmpty {
+ lastResult = result
+ }
+ totalRowsAffected += result.rowsAffected
+ case .failure(let error):
+ appState.logQuery(sql: execution.statement, duration: execution.duration)
+ appState.recordQueryHistory(
+ sql: execution.statement,
+ duration: execution.duration,
+ error: error.localizedDescription
+ )
+ errorMessage = error.localizedDescription
+ appState.refreshSidebar()
+ isExecuting = false
+ return
+ }
+ }
+
+ if let result = lastResult {
+ applyResult(result)
+ appState.statusRowCount = result.rowCount
+ appState.statusQueryTime = result.executionTime
+ } else if statements.count > 1 {
+ let totalDuration = Date().timeIntervalSince(overallStart)
+ statusMessage = "\(statements.count) statement(s) executed · \(totalRowsAffected) row(s) affected · \(String(format: "%.2fs", totalDuration))"
+ }
+
+ appState.refreshSidebar()
+ isExecuting = false
+ }
+
/// Split a SQL script into individual statements/batches. SQL Server uses
/// `GO` on its own line as a batch separator; other databases use `;`.
private func splitIntoBatches(_ script: String, databaseType: DatabaseType) -> [String] {