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 schema-scoped actions (#80)

Tobid5bcbc139a48
diff --git a/macos/App/State/AppState.swift b/macos/App/State/AppState.swift
index dd96e99..d18a106 100644
--- a/macos/App/State/AppState.swift
+++ b/macos/App/State/AppState.swift
@@ -73,6 +73,7 @@ final class AppState: ObservableObject {
@Published var connectionError: String?
@Published var serverVersion: String?
@Published var sslInfo: String?
+ private var sidebarLoadGeneration = 0
// MARK: - Tab State
@@ -371,6 +372,9 @@ final class AppState: ObservableObject {
adapter: any DatabaseAdapter,
schema: String? = nil
) async {
+ sidebarLoadGeneration &+= 1
+ let loadGeneration = sidebarLoadGeneration
+
do {
// Run all queries in parallel instead of sequential
async let tablesTask = adapter.listTables(schema: schema)
@@ -412,6 +416,8 @@ final class AppState: ObservableObject {
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
} catch {
print("Sidebar load error: \(error)")
@@ -731,6 +737,7 @@ final class AppState: ObservableObject {
}
func disconnect() {
+ sidebarLoadGeneration &+= 1
if let adapter = activeAdapter {
Task { try? await adapter.disconnect() }
}
diff --git a/macos/Core/Models/Schema/SchemaSnapshot.swift b/macos/Core/Models/Schema/SchemaSnapshot.swift
index 5207daa..59110e5 100644
--- a/macos/Core/Models/Schema/SchemaSnapshot.swift
+++ b/macos/Core/Models/Schema/SchemaSnapshot.swift
@@ -43,7 +43,15 @@ struct TableDescription: Codable, Sendable, Equatable {
}
func toDDL(dialect: SQLDialect) -> String {
- var ddl = "CREATE TABLE \(dialect.quoteIdentifier(name)) (\n"
+ let tableIdentifier: String
+ switch dialect {
+ case .postgresql:
+ tableIdentifier = dialect.qualifiedIdentifier(name, schema: schema)
+ default:
+ tableIdentifier = dialect.quoteIdentifier(name)
+ }
+
+ var ddl = "CREATE TABLE \(tableIdentifier) (\n"
ddl += columns.map { " \($0.name) \($0.dataType)\($0.isNullable ? "" : " NOT NULL")\($0.defaultValue.map { " DEFAULT \($0)" } ?? "")" }.joined(separator: ",\n")
ddl += "\n);"
return ddl
diff --git a/macos/Core/Protocols/Database/DatabaseAdapter.swift b/macos/Core/Protocols/Database/DatabaseAdapter.swift
index 33a5f3d..e4aec48 100644
--- a/macos/Core/Protocols/Database/DatabaseAdapter.swift
+++ b/macos/Core/Protocols/Database/DatabaseAdapter.swift
@@ -54,6 +54,10 @@ protocol DatabaseAdapter: AnyObject, Sendable {
func commitTransaction() async throws
func rollbackTransaction() async throws
+ /// Execute raw statements without rewriting them in a transaction whose
+ /// PostgreSQL search path is scoped to `schema` for the transaction only.
+ func executeStatements(_ statements: [String], inSchemaTransaction schema: String) async throws
+
// Pagination
func fetchRows(
table: String,
@@ -75,6 +79,21 @@ protocol DatabaseAdapter: AnyObject, Sendable {
}
extension DatabaseAdapter {
+ func executeStatements(_ statements: [String], inSchemaTransaction schema: String) async throws {
+ try await beginTransaction()
+ do {
+ let quotedSchema = databaseType.sqlDialect.quoteIdentifier(schema)
+ _ = try await executeRaw(sql: "SET LOCAL search_path TO \(quotedSchema)")
+ for statement in statements {
+ _ = try await executeRaw(sql: statement)
+ }
+ try await commitTransaction()
+ } catch {
+ try? await rollbackTransaction()
+ throw error
+ }
+ }
+
func createDatabase(name: String) async throws {
let quoted = databaseType.sqlDialect.quoteIdentifier(name)
_ = try await executeRaw(sql: "CREATE DATABASE \(quoted)")
diff --git a/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift b/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift
index 54b3a12..5b8359d 100644
--- a/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift
+++ b/macos/Data/Adapters/PostgreSQL/PostgreSQLAdapter.swift
@@ -8,6 +8,7 @@ import PostgresNIO
import NIOCore
import NIOPosix
import NIOSSL
+import Logging
final class PostgreSQLAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Sendable {
let databaseType: DatabaseType = .postgresql
@@ -658,6 +659,34 @@ final class PostgreSQLAdapter: DatabaseAdapter, SchemaInspectable, @unchecked Se
func commitTransaction() async throws { _ = try await executeRaw(sql: "COMMIT") }
func rollbackTransaction() async throws { _ = try await executeRaw(sql: "ROLLBACK") }
+ func executeStatements(_ statements: [String], inSchemaTransaction schema: String) async throws {
+ try ensureConnected()
+ guard let client else { throw GridexError.queryExecutionFailed("No connection") }
+
+ let logger = Logger(label: "gridex.postgresql.sql-dump")
+ let quotedSchema = databaseType.sqlDialect.quoteIdentifier(schema)
+
+ do {
+ try await client.withTransaction(logger: logger) { connection in
+ let setupRows = try await connection.query(
+ PostgresQuery(unsafeSQL: "SET LOCAL search_path TO \(quotedSchema)"),
+ logger: logger
+ )
+ for try await _ in setupRows {}
+
+ for statement in statements {
+ let rows = try await connection.query(
+ PostgresQuery(unsafeSQL: statement),
+ logger: logger
+ )
+ for try await _ in rows {}
+ }
+ }
+ } catch {
+ throw GridexError.queryExecutionFailed(Self.formatPostgresError(error))
+ }
+ }
+
// MARK: - Pagination
func fetchRows(table: String, schema: String?, columns: [String]?, where filter: FilterExpression?, orderBy: [QuerySortDescriptor]?, limit: Int, offset: Int) async throws -> QueryResult {
diff --git a/macos/Presentation/Views/Sidebar/SQLDumpExecutor.swift b/macos/Presentation/Views/Sidebar/SQLDumpExecutor.swift
new file mode 100644
index 0000000..12ad27d
--- /dev/null
+++ b/macos/Presentation/Views/Sidebar/SQLDumpExecutor.swift
@@ -0,0 +1,33 @@
+import Foundation
+
+enum SQLDumpExecutor {
+ static func execute(
+ statements: [String],
+ schema: String?,
+ using adapter: any DatabaseAdapter
+ ) async -> ImportSQLResult {
+ if adapter.databaseType == .postgresql, let schema {
+ do {
+ try await adapter.executeStatements(statements, inSchemaTransaction: schema)
+ return ImportSQLResult(success: statements.count, total: statements.count, firstError: nil)
+ } catch {
+ return ImportSQLResult(success: 0, total: statements.count, firstError: error.localizedDescription)
+ }
+ }
+
+ var successCount = 0
+ var firstError: String?
+ for statement in statements {
+ do {
+ _ = try await adapter.executeRaw(sql: statement)
+ successCount += 1
+ } catch {
+ if firstError == nil {
+ firstError = error.localizedDescription
+ }
+ }
+ }
+
+ return ImportSQLResult(success: successCount, total: statements.count, firstError: firstError)
+ }
+}
diff --git a/macos/Presentation/Views/Sidebar/SidebarView.swift b/macos/Presentation/Views/Sidebar/SidebarView.swift
index 868e8e3..e2163d7 100644
--- a/macos/Presentation/Views/Sidebar/SidebarView.swift
+++ b/macos/Presentation/Views/Sidebar/SidebarView.swift
@@ -718,21 +718,11 @@ struct SidebarItemRow: View {
}
let statements = Self.splitSQLStatements(content)
-
- var successCount = 0
- var firstError: String?
- for stmt in statements {
- do {
- _ = try await adapter.executeRaw(sql: stmt)
- successCount += 1
- } catch {
- if firstError == nil {
- firstError = error.localizedDescription
- }
- }
- }
-
- return ImportSQLResult(success: successCount, total: statements.count, firstError: firstError)
+ return await SQLDumpExecutor.execute(
+ statements: statements,
+ schema: item.schema,
+ using: adapter
+ )
}
/// Split a SQL dump into individual statements. Correctly handles:
diff --git a/macos/Presentation/Views/TableList/TableListView.swift b/macos/Presentation/Views/TableList/TableListView.swift
index 5556753..562144e 100644
--- a/macos/Presentation/Views/TableList/TableListView.swift
+++ b/macos/Presentation/Views/TableList/TableListView.swift
@@ -165,7 +165,10 @@ final class TableListViewModel: ObservableObject {
let result: QueryResult
switch adapter.databaseType {
case .postgresql:
- result = try await adapter.executeRaw(sql: tableStatsQueryPostgres(schema: schema ?? "public"))
+ result = try await adapter.executeWithRowValues(
+ sql: tableStatsQueryPostgres(),
+ parameters: [.string(schema ?? "public")]
+ )
case .mysql:
result = try await adapter.executeRaw(sql: tableStatsQueryMySQL(schema: schema))
case .sqlite:
@@ -248,7 +251,7 @@ final class TableListViewModel: ObservableObject {
}
}
- private func tableStatsQueryPostgres(schema: String) -> String {
+ private func tableStatsQueryPostgres() -> String {
"""
SELECT
c.relname AS name,
@@ -283,7 +286,7 @@ final class TableListViewModel: ObservableObject {
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid
- WHERE n.nspname = '\(schema)'
+ WHERE n.nspname = $1
AND c.relkind IN ('r', 'f')
ORDER BY c.relname
"""