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(postgres): harden sidebar reload lifecycle (#80)

Tobi1271e6ea0ab8
diff --git a/macos/App/State/AppState.swift b/macos/App/State/AppState.swift
index d18a106..da009b7 100644
--- a/macos/App/State/AppState.swift
+++ b/macos/App/State/AppState.swift
@@ -49,6 +49,7 @@ final class AppState: ObservableObject {
@Published var showNewTableSheet = false
@Published var selectedDBType: DatabaseType?
@Published var selectedSidebarItem: SidebarItemType?
+ @Published private(set) var selectedSidebarItemSchema: String?
// MARK: - Home State
@@ -73,7 +74,34 @@ final class AppState: ObservableObject {
@Published var connectionError: String?
@Published var serverVersion: String?
@Published var sslInfo: String?
+ // A single token covers schema discovery and item loading. The published
+ // snapshot stays coherent until the complete replacement is ready.
private var sidebarLoadGeneration = 0
+ private var pendingSidebarReload: SidebarReload?
+ private var publishedSidebarContext: SidebarConnectionContext?
+ private var publishedSidebarSnapshot: SidebarSnapshot?
+
+ private struct SidebarConnectionContext: Equatable {
+ let config: ConnectionConfig
+ let adapterID: ObjectIdentifier
+ }
+
+ private struct SidebarSnapshot {
+ let schemas: [String]
+ let selectedSchema: String?
+ let items: [SidebarItem]
+
+ static let empty = SidebarSnapshot(schemas: [], selectedSchema: nil, items: [])
+ }
+
+ private struct SidebarReload {
+ let generation: Int
+ let connection: SidebarConnectionContext
+ let requestedSchema: String?
+ let previous: SidebarSnapshot
+ var schemas: [String]
+ var schema: String?
+ }
// MARK: - Tab State
@@ -168,6 +196,7 @@ final class AppState: ObservableObject {
let schema: String?
var databaseName: String?
var initialViewMode: String? // "data" or "structure"
+ var sidebarItemType: SidebarItemType? = nil
}
struct TabGroup: Identifiable {
@@ -277,12 +306,7 @@ final class AppState: ObservableObject {
isConnecting = false
// Load sidebar immediately (most important for user)
- await loadSidebarSchemas(config: config, adapter: connection.adapter)
- await loadSidebar(
- config: config,
- adapter: connection.adapter,
- schema: selectedSidebarSchema
- )
+ await reloadSidebar(config: config, adapter: connection.adapter)
// Fetch metadata in background — all parallel
Task { [weak self] in
@@ -345,38 +369,135 @@ final class AppState: ObservableObject {
}
}
- func loadSidebarSchemas(config: ConnectionConfig, adapter: any DatabaseAdapter) async {
- guard config.databaseType == .postgresql else {
- sidebarSchemas = []
- selectedSidebarSchema = nil
+ func loadSidebarSchemas(
+ config: ConnectionConfig,
+ adapter: any DatabaseAdapter,
+ preferredSchema: String? = nil
+ ) async {
+ _ = await prepareSidebarReload(
+ config: config,
+ adapter: adapter,
+ preferredSchema: preferredSchema
+ )
+ }
+
+ func loadSidebar(
+ config: ConnectionConfig,
+ adapter: any DatabaseAdapter,
+ schema: String? = nil
+ ) async {
+ let connection = sidebarConnectionContext(config: config, adapter: adapter)
+ if let pendingSidebarReload,
+ pendingSidebarReload.connection == connection,
+ isCurrentSidebarReload(pendingSidebarReload) {
+ await loadSidebarItems(using: pendingSidebarReload, adapter: adapter)
return
}
+ guard var reload = beginSidebarReload(
+ config: config,
+ adapter: adapter,
+ preferredSchema: schema
+ ) else { return }
+ reload.schemas = sidebarSchemas
+ reload.schema = schema
+ await loadSidebarItems(using: reload, adapter: adapter)
+ }
+
+ private func reloadSidebar(
+ config: ConnectionConfig,
+ adapter: any DatabaseAdapter,
+ preferredSchema: String? = nil
+ ) async {
+ guard let reload = await prepareSidebarReload(
+ config: config,
+ adapter: adapter,
+ preferredSchema: preferredSchema
+ ) else { return }
+ await loadSidebarItems(using: reload, adapter: adapter)
+ }
+
+ private func prepareSidebarReload(
+ config: ConnectionConfig,
+ adapter: any DatabaseAdapter,
+ preferredSchema: String?
+ ) async -> SidebarReload? {
+ guard var reload = beginSidebarReload(
+ config: config,
+ adapter: adapter,
+ preferredSchema: preferredSchema
+ ) else { return nil }
+
do {
- let schemas = try await adapter.listSchemas(database: config.database)
- sidebarSchemas = Array(Set(schemas)).sorted()
- selectedSidebarSchema = SidebarSchemaSelection.resolve(
- previous: selectedSidebarSchema,
+ let schemas: [String]
+ if config.databaseType == .postgresql {
+ schemas = Array(Set(try await adapter.listSchemas(database: config.database))).sorted()
+ } else {
+ schemas = []
+ }
+
+ guard isCurrentSidebarReload(reload) else { return nil }
+ reload.schemas = schemas
+ reload.schema = SidebarSchemaSelection.resolve(
+ previous: reload.requestedSchema,
for: config.databaseType,
- schemas: sidebarSchemas
+ schemas: schemas
)
+ pendingSidebarReload = reload
+ return reload
} catch {
- sidebarSchemas = []
- selectedSidebarSchema = nil
+ guard isCurrentSidebarReload(reload) else { return nil }
+ publishSidebarSnapshot(reload.previous, using: reload)
+ pendingSidebarReload = nil
print("Sidebar schema load error: \(error)")
+ return nil
}
}
- func loadSidebar(
+ private func beginSidebarReload(
config: ConnectionConfig,
adapter: any DatabaseAdapter,
- schema: String? = nil
- ) async {
+ preferredSchema: String?
+ ) -> SidebarReload? {
+ let connection = sidebarConnectionContext(config: config, adapter: adapter)
+ guard isActiveSidebarConnection(connection) else { return nil }
+
+ let requestedSchema = preferredSchema ?? selectedSidebarSchema
+ let previous: SidebarSnapshot
+ if publishedSidebarContext == connection, let publishedSidebarSnapshot {
+ previous = publishedSidebarSnapshot
+ } else {
+ previous = .empty
+ }
+
+ let connectionChanged = publishedSidebarContext != connection
sidebarLoadGeneration &+= 1
- let loadGeneration = sidebarLoadGeneration
+ pendingSidebarReload = nil
+ let reload = SidebarReload(
+ generation: sidebarLoadGeneration,
+ connection: connection,
+ requestedSchema: requestedSchema,
+ previous: previous,
+ schemas: [],
+ schema: nil
+ )
+ guard isCurrentSidebarReload(reload) else { return nil }
+ if connectionChanged {
+ selectedSidebarItem = nil
+ selectedSidebarItemSchema = nil
+ }
+ guard publishSidebarSnapshot(previous, using: reload) else { return nil }
+ return reload
+ }
+
+ private func loadSidebarItems(
+ using reload: SidebarReload,
+ adapter: any DatabaseAdapter
+ ) async {
+ guard isCurrentSidebarReload(reload) else { return }
+ let schema = reload.schema
do {
- // Run all queries in parallel instead of sequential
async let tablesTask = adapter.listTables(schema: schema)
async let viewsTask = adapter.listViews(schema: schema)
async let functionsTask = adapter.listFunctions(schema: schema)
@@ -387,67 +508,138 @@ final class AppState: ObservableObject {
let functions = try await functionsTask
let procedures = (try? await proceduresTask) ?? []
- let tableItems = tables.map { t in
- SidebarItem(title: t.name, type: .table(t.name), schema: schema, iconName: "")
+ let tableItems = tables.map { table in
+ SidebarItem(title: table.name, type: .table(table.name), schema: schema, iconName: "")
}
- let viewItems = views.map { v in
- SidebarItem(title: v.name, type: .view(v.name), schema: schema, iconName: "")
+ let viewItems = views.map { view in
+ SidebarItem(title: view.name, type: .view(view.name), schema: schema, iconName: "")
}
- let functionItems = functions.map { f in
- SidebarItem(title: f, type: .function(f), schema: schema, iconName: "")
+ let functionItems = functions.map { function in
+ SidebarItem(title: function, type: .function(function), schema: schema, iconName: "")
}
- let procedureItems = procedures.map { p in
- SidebarItem(title: p, type: .procedure(p), schema: schema, iconName: "")
+ let procedureItems = procedures.map { procedure in
+ SidebarItem(title: procedure, type: .procedure(procedure), schema: schema, iconName: "")
}
var items: [SidebarItem] = []
-
if !functionItems.isEmpty {
items.append(SidebarItem(title: "Functions", type: .group("functions"), schema: schema, iconName: "", children: functionItems))
}
-
if !procedureItems.isEmpty {
items.append(SidebarItem(title: "Procedures", type: .group("procedures"), schema: schema, iconName: "", children: procedureItems))
}
-
items.append(SidebarItem(title: "Tables", type: .group("tables"), schema: schema, iconName: "", children: tableItems))
-
if !viewItems.isEmpty {
items.append(SidebarItem(title: "Views", type: .group("views"), schema: schema, iconName: "", children: viewItems))
}
- guard loadGeneration == sidebarLoadGeneration else { return }
- guard config.databaseType != .postgresql || schema == selectedSidebarSchema else { return }
- sidebarItems = items
+ guard isCurrentSidebarReload(reload) else { return }
+ publishSidebarSnapshot(
+ SidebarSnapshot(
+ schemas: reload.schemas,
+ selectedSchema: schema,
+ items: items
+ ),
+ using: reload
+ )
+ if pendingSidebarReload?.generation == reload.generation {
+ pendingSidebarReload = nil
+ }
} catch {
+ guard isCurrentSidebarReload(reload) else { return }
+ publishSidebarSnapshot(reload.previous, using: reload)
+ if pendingSidebarReload?.generation == reload.generation {
+ pendingSidebarReload = nil
+ }
print("Sidebar load error: \(error)")
}
}
+ private func sidebarConnectionContext(
+ config: ConnectionConfig,
+ adapter: any DatabaseAdapter
+ ) -> SidebarConnectionContext {
+ SidebarConnectionContext(config: config, adapterID: ObjectIdentifier(adapter))
+ }
+
+ private func isActiveSidebarConnection(_ connection: SidebarConnectionContext) -> Bool {
+ guard activeConnectionId == connection.config.id,
+ activeConfig == connection.config,
+ let activeAdapter else { return false }
+ return ObjectIdentifier(activeAdapter) == connection.adapterID
+ }
+
+ private func isCurrentSidebarReload(_ reload: SidebarReload) -> Bool {
+ reload.generation == sidebarLoadGeneration
+ && isActiveSidebarConnection(reload.connection)
+ }
+
+ @discardableResult
+ private func publishSidebarSnapshot(
+ _ snapshot: SidebarSnapshot,
+ using reload: SidebarReload
+ ) -> Bool {
+ guard isCurrentSidebarReload(reload) else { return false }
+ sidebarSchemas = snapshot.schemas
+ selectedSidebarSchema = snapshot.selectedSchema
+ sidebarItems = snapshot.items
+ publishedSidebarContext = reload.connection
+ publishedSidebarSnapshot = snapshot
+ return true
+ }
+
// MARK: - Tab Management
+ func selectSidebarItem(_ type: SidebarItemType, schema: String?) {
+ selectedSidebarItem = type
+ selectedSidebarItemSchema = schema
+ }
+
+ func clearSidebarSelection() {
+ selectedSidebarItem = nil
+ selectedSidebarItemSchema = nil
+ }
+
+ func isSidebarItemActive(_ item: SidebarItem) -> Bool {
+ selectedSidebarItem == item.type && selectedSidebarItemSchema == item.schema
+ }
+
private func syncSidebarFromActiveTab() {
guard let activeId = activeTabId,
let tab = tabs.first(where: { $0.id == activeId }),
let name = tab.tableName else { return }
- switch tab.type {
- case .functionDetail:
- if tab.initialViewMode == "procedure" {
- selectedSidebarItem = .procedure(name)
- } else {
- selectedSidebarItem = .function(name)
- }
- default:
- selectedSidebarItem = .table(name)
+ let type: SidebarItemType
+ if let sidebarItemType = tab.sidebarItemType {
+ type = sidebarItemType
+ } else if tab.type == .functionDetail {
+ type = tab.initialViewMode == "procedure" ? .procedure(name) : .function(name)
+ } else {
+ type = .table(name)
}
+ selectSidebarItem(type, schema: tab.schema)
}
- func openTable(name: String, schema: String?) {
- if let existing = tabs.first(where: { $0.type == .dataGrid && $0.tableName == name && $0.schema == schema }) {
- activeTabId = existing.id
+ func openTable(
+ name: String,
+ schema: String?,
+ sidebarItemType: SidebarItemType? = nil
+ ) {
+ if let index = tabs.firstIndex(where: { $0.type == .dataGrid && $0.tableName == name && $0.schema == schema }) {
+ if let sidebarItemType {
+ tabs[index].sidebarItemType = sidebarItemType
+ }
+ activeTabId = tabs[index].id
return
}
- let tab = ContentTab(id: UUID(), type: .dataGrid, title: name, tableName: name, schema: schema, databaseName: currentDatabaseName)
+ let tab = ContentTab(
+ id: UUID(),
+ type: .dataGrid,
+ title: name,
+ tableName: name,
+ schema: schema,
+ databaseName: currentDatabaseName,
+ sidebarItemType: sidebarItemType ?? .table(name)
+ )
tabs.append(tab)
activeTabId = tab.id
if let db = currentDatabaseName { ensureTabGroup(for: db) }
@@ -696,8 +888,7 @@ final class AppState: ObservableObject {
// Reload sidebar for the new database
if let cfg = activeConfig, let adp = activeAdapter {
- await loadSidebarSchemas(config: cfg, adapter: adp)
- await loadSidebar(config: cfg, adapter: adp, schema: selectedSidebarSchema)
+ await reloadSidebar(config: cfg, adapter: adp)
}
} catch {
print("Switch database failed: \(error)")
@@ -738,6 +929,9 @@ final class AppState: ObservableObject {
func disconnect() {
sidebarLoadGeneration &+= 1
+ pendingSidebarReload = nil
+ publishedSidebarContext = nil
+ publishedSidebarSnapshot = nil
if let adapter = activeAdapter {
Task { try? await adapter.disconnect() }
}
@@ -756,6 +950,7 @@ final class AppState: ObservableObject {
sidebarSchemas.removeAll()
selectedSidebarSchema = nil
selectedSidebarItem = nil
+ selectedSidebarItemSchema = nil
selectedRowDetails = nil
onDetailFieldEdit = nil
serverVersion = nil
@@ -768,11 +963,14 @@ final class AppState: ObservableObject {
redisDBSize = nil
}
- func refreshSidebar() {
+ func refreshSidebar(preferredSchema: String? = nil) {
guard let adapter = activeAdapter, let config = activeConfig else { return }
Task {
- await loadSidebarSchemas(config: config, adapter: adapter)
- await loadSidebar(config: config, adapter: adapter, schema: selectedSidebarSchema)
+ await reloadSidebar(
+ config: config,
+ adapter: adapter,
+ preferredSchema: preferredSchema
+ )
}
}
diff --git a/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift b/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift
index 8ed8efc..eae3b4d 100644
--- a/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift
+++ b/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift
@@ -217,23 +217,37 @@ final class PostgreSQLAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Se
appendBinding(param, to: &bindings)
}
- let pgQuery = PostgresQuery(unsafeSQL: sql, binds: bindings)
- let rows = try await client.query(pgQuery)
- let columns = rows.columns.map { col in
- ColumnHeader(name: col.name, dataType: col.dataType.description)
- }
+ return try await Self.withFormattedQueryErrors {
+ let pgQuery = PostgresQuery(unsafeSQL: sql, binds: bindings)
+ let rows = try await client.query(pgQuery)
+ let columns = rows.columns.map { col in
+ ColumnHeader(name: col.name, dataType: col.dataType.description)
+ }
- var resultRows: [[RowValue]] = []
- for try await row in rows {
- var rowValues: [RowValue] = []
- for (cell, meta) in zip(row, rows.columns) {
- rowValues.append(decodeCell(cell, dataType: meta.dataType))
+ var resultRows: [[RowValue]] = []
+ for try await row in rows {
+ var rowValues: [RowValue] = []
+ for (cell, meta) in zip(row, rows.columns) {
+ rowValues.append(self.decodeCell(cell, dataType: meta.dataType))
+ }
+ resultRows.append(rowValues)
}
- resultRows.append(rowValues)
+
+ let duration = CFAbsoluteTimeGetCurrent() - startTime
+ return QueryResult(columns: columns, rows: resultRows, rowsAffected: resultRows.count, executionTime: duration, queryType: queryType)
}
+ }
- let duration = CFAbsoluteTimeGetCurrent() - startTime
- return QueryResult(columns: columns, rows: resultRows, rowsAffected: resultRows.count, executionTime: duration, queryType: queryType)
+ static func withFormattedQueryErrors<T>(
+ _ operation: () async throws -> T
+ ) async throws -> T {
+ do {
+ return try await operation()
+ } catch let error as GridexError {
+ throw error
+ } catch {
+ throw GridexError.queryExecutionFailed(formatPostgresError(error))
+ }
}
private func appendBinding(_ value: RowValue, to bindings: inout PostgresBindings) {
diff --git a/macos/Presentation/Views/Sidebar/SidebarView.swift b/macos/Presentation/Views/Sidebar/SidebarView.swift
index e2163d7..50d22ce 100644
--- a/macos/Presentation/Views/Sidebar/SidebarView.swift
+++ b/macos/Presentation/Views/Sidebar/SidebarView.swift
@@ -249,9 +249,8 @@ struct SidebarView: View {
get: { appState.selectedSidebarSchema },
set: { schema in
guard schema != appState.selectedSidebarSchema else { return }
- appState.selectedSidebarSchema = schema
- appState.selectedSidebarItem = nil
- appState.refreshSidebar()
+ appState.clearSidebarSelection()
+ appState.refreshSidebar(preferredSchema: schema)
}
)) {
ForEach(appState.sidebarSchemas, id: \.self) { schema in
@@ -324,7 +323,7 @@ struct SidebarItemRow: View {
// Leaf item (table, view, function)
private var leafRow: some View {
- let isActive = appState.selectedSidebarItem == item.type
+ let isActive = appState.isSidebarItemActive(item)
let isPendingDelete: Bool = {
if case .table(let name) = item.type {
return appState.pendingTableDeletions[tableReference(name)] != nil
@@ -371,20 +370,20 @@ struct SidebarItemRow: View {
.onTapGesture(count: 2) {
switch item.type {
case .table(let name), .view(let name):
- appState.openTable(name: name, schema: item.schema)
+ appState.openTable(name: name, schema: item.schema, sidebarItemType: item.type)
NotificationCenter.default.post(name: .reloadData, object: nil)
default:
break
}
}
.onTapGesture {
- appState.selectedSidebarItem = item.type
+ appState.selectSidebarItem(item.type, schema: item.schema)
// Open table/view on single click
switch item.type {
case .table(let name):
- appState.openTable(name: name, schema: item.schema)
+ appState.openTable(name: name, schema: item.schema, sidebarItemType: item.type)
case .view(let name):
- appState.openTable(name: name, schema: item.schema)
+ appState.openTable(name: name, schema: item.schema, sidebarItemType: item.type)
case .function(let name):
appState.openFunction(name: name, schema: item.schema)
case .procedure(let name):
@@ -564,7 +563,7 @@ struct SidebarItemRow: View {
}
} else if case .table(let name) = item.type {
Button("Open in new tab") {
- appState.openTable(name: name, schema: item.schema)
+ appState.openTable(name: name, schema: item.schema, sidebarItemType: item.type)
}
Button("Open structure") {
diff --git a/macos/Tests/GridexTests/PostgreSQLSchemaActionRegressionTests.swift b/macos/Tests/GridexTests/PostgreSQLSchemaActionRegressionTests.swift
index 003549b..9d8b12c 100644
--- a/macos/Tests/GridexTests/PostgreSQLSchemaActionRegressionTests.swift
+++ b/macos/Tests/GridexTests/PostgreSQLSchemaActionRegressionTests.swift
@@ -13,6 +13,9 @@ final class SidebarLoadPublicationTests: XCTestCase {
let appState = AppState()
let config = makePostgreSQLConfig()
+ appState.activeConnectionId = config.id
+ appState.activeConfig = config
+ appState.activeAdapter = adapter
appState.selectedSidebarSchema = "tenant_a"
let staleLoad = Task {
await appState.loadSidebar(config: config, adapter: adapter, schema: "tenant_a")