diff --git a/apple/TableProMobile/TableProMobile/AppState.swift b/apple/TableProMobile/TableProMobile/AppState.swift index 6b93ba3fc2..f3d01616b8 100644 --- a/apple/TableProMobile/TableProMobile/AppState.swift +++ b/apple/TableProMobile/TableProMobile/AppState.swift @@ -119,6 +119,7 @@ final class AppState { if loadStatus == .ready { KeychainSecureStore.cleanOrphanedCredentials(validConnectionIds: Set(connections.map(\.id))) + CertificateMaterializer().releaseAll(except: Set(connections.map(\.id))) Task { publishLibrary() } diff --git a/apple/TableProMobile/TableProMobile/Coordinators/ConnectionCoordinator.swift b/apple/TableProMobile/TableProMobile/Coordinators/ConnectionCoordinator.swift index f5be407722..d25e056259 100644 --- a/apple/TableProMobile/TableProMobile/Coordinators/ConnectionCoordinator.swift +++ b/apple/TableProMobile/TableProMobile/Coordinators/ConnectionCoordinator.swift @@ -68,6 +68,7 @@ final class ConnectionCoordinator { private(set) var queryHistory: [QueryHistoryItem] = [] private(set) var keepsDamagedHistoryCopy = false + @ObservationIgnored private var historyGeneration = 0 private var historyStorage: QueryHistoryStorage { appState.queryHistory } var connectionManager: ConnectionManager { appState.connectionManager } @@ -259,14 +260,26 @@ final class ConnectionCoordinator { TablePlacement( driver: session.map { ObjectIdentifier($0.driver) }, database: activeDatabase, - schema: supportsSchemas ? activeSchema : nil + schema: tableQualifier ) } + // What the Tables tab qualifies a table with. MySQL's `db`.`table` names the database where other engines name a + // schema, so a `USE` run in the Query tab never moves where a browse, a save or a drop lands. + var tableQualifier: String? { + if supportsSchemas { return activeSchema } + guard model.qualifiesTablesWithDatabase, !activeDatabase.isEmpty else { return nil } + return activeDatabase + } + static var editorHeldElsewhereMessage: String { String(localized: "Another window has unsaved changes on this connection. Save or discard them before switching database.") } + static var editorHeldHereMessage: String { + String(localized: "This window has unsaved changes on this connection, so the session stayed on its database. Save or discard them before switching database.") + } + static func lostTransactionMessage(_ loss: SessionLoss, connectionName: String) -> String? { switch loss { case .whileIdle: @@ -375,6 +388,8 @@ final class ConnectionCoordinator { await model.reloadMetadataIfReleased(from: self) // A catalog connection sees DDL the transaction ran only once it commits. noteCatalogChanged([.tables, .schemas, .databases]) + // A `SET LOCAL search_path` ends with the transaction. + await followSessionSchema() } func rollBackTransaction(as token: SessionTransactionMonitor.HoldToken) async throws { @@ -401,24 +416,125 @@ final class ConnectionCoordinator { // MARK: - Database / Schema Switching - // A MongoDB `use` moves the session itself, so the lists and the picker follow it there, once every request queued - // before has returned: a request Stop ended lands its `use` only then. The switch runs outside the run that asks, - // which Stop may have cancelled. While another window holds unsaved edits the session goes back instead, so they - // save where the picker says. - func followSessionDatabase() async { - guard supportsDatabaseSwitching, let driver = session?.driver as? PluginBackedDriver else { return } + // What a run may have moved: a `USE` moves the database, and a search path, a role or a transaction's end the schema. + struct SessionMove { + var database = false + var schema = false + } + + // A read that costs a statement replaces ROW_COUNT() and the warnings, so it is sent only after a run that can have + // moved the session. The work runs in a task of its own, since Stop may have cancelled the run that asks. + func followSessionPlacement(after move: SessionMove) async { + await followSessionDatabase(after: move) + if move.schema { await followSessionSchema() } + } + + private func followSessionDatabase(after move: SessionMove) async { + guard supportsDatabaseSwitching, let driver = session?.driver as? any SessionDatabaseReporting, + move.database || driver.reportsDatabaseWithoutStatement else { return } await Task { - guard let used = try? await driver.settledCurrentDatabase(), used != activeDatabase, - session?.driver === driver else { return } - guard !anotherWindowHoldsEditor else { - try? await driver.switchDatabase(to: activeDatabase) - presentFailure(title: Self.switchDatabaseFailedTitle, message: Self.editorHeldElsewhereMessage) + let used = try? await driver.sessionDatabase() + // With autocommit off, a MySQL read opens a transaction. + if !driver.reportsDatabaseWithoutStatement { await refreshTransaction() } + guard let used, !used.isEmpty, used != activeDatabase, session?.driver === driver else { return } + // An unsaved edit holds the session where it was made, as it holds the picker. + if isHeldByEditor || anotherWindowHoldsEditor, !activeDatabase.isEmpty { + let back = activeDatabase + let failure = await whileSwitching(to: back) { + do { + try await driver.switchDatabase(to: back) + return nil + } catch { + return ConnectionFailure(error: error, title: Self.switchDatabaseFailedTitle, redialRepeats: false) + } + } + guard failure != nil else { + presentFailure( + title: Self.switchDatabaseFailedTitle, + message: isHeldByEditor ? Self.editorHeldHereMessage : Self.editorHeldElsewhereMessage + ) + return + } + // The lists follow the session, and every window with an edit open keeps the database it was made in, + // this one too, since it did not ask for the move. + model.beginSwitch() + _ = await model.switchDatabase(to: used, from: self, inside: nil) + model.endSwitch() + await model.loadSchemasAfterSwitch(to: used, from: self) + await model.runHeldBackWork(from: self) + // MySQL names the database in every Tables tab write, and a plugin driver runs the app's requests in the + // menu's database; SQL Server saves only once the session is back. + presentFailure( + title: Self.switchDatabaseFailedTitle, + message: model.qualifiesTablesWithDatabase || driver.reportsDatabaseWithoutStatement + ? String(format: String(localized: "The query moved the session to “%@” and it could not go back to “%@”. Unsaved changes still save to “%@”."), used, back, back) + : String( + format: String(localized: "The query moved the session to “%@” and it could not go back to “%@”. To save the unsaved changes, run USE %@ in the Query tab of the window that holds them."), + used, back, SQLBuilder.quoteIdentifier(back, for: connection.type) + ) + ) return } await switchDatabase(to: used) }.value } + // The Tables tab names its schema, so only completion and the picker read where the session is. + private func followSessionSchema() async { + guard supportsSchemas, let driver = session?.driver as? any SessionSchemaReporting else { return } + await driver.settleCurrentSchema() + guard session?.driver === driver, let current = driver.currentSchema, current != activeSchema else { return } + appState.bumpSessionRevision(connection.id) + await followLiveSession() + } + + // From the start of a run with a `USE` until the picker follows it, another run's statements could go out around the + // move, so no window runs one, and on SQL Server, whose Tables tab names no database, every window's writes are + // refused. A driver that reports its database without a statement keeps the app's requests where the picker says. + func beginDatabaseMove(ifRunning text: String) -> Bool { + guard supportsDatabaseSwitching, let driver = session?.driver as? any SessionDatabaseReporting, + !driver.reportsDatabaseWithoutStatement, + SessionLocalStatements.effect(of: [text], databaseType: connection.type).usesDatabase else { return false } + model.beginDatabaseMove() + return true + } + + func endDatabaseMove() { + model.endDatabaseMove() + } + + var isDatabaseMoving: Bool { model.isDatabaseMoving } + + static var databaseMovingRefusal: AppError { + AppError( + category: .query, + title: String(localized: "Database Switch Running"), + message: String(localized: "A query that switches the database is running on this connection. Try again once it ends."), + recovery: nil, + underlying: nil + ) + } + + var databaseMoveRefusal: AppError? { + guard supportsDatabaseSwitching, !model.qualifiesTablesWithDatabase, + let driver = session?.driver as? any SessionDatabaseReporting, + !driver.reportsDatabaseWithoutStatement else { return nil } + if model.isDatabaseMoving { return Self.databaseMovingRefusal } + // A session that could not go back to where an unsaved edit was made. SQL Server compares names by its collation, + // which ignores case unless set otherwise. + if let current = driver.currentDatabase, !current.isEmpty, !activeDatabase.isEmpty, + current.caseInsensitiveCompare(activeDatabase) != .orderedSame { + return AppError( + category: .query, + title: String(localized: "Session in Another Database"), + message: String(format: String(localized: "The session is in “%@”, not “%@”, so this change cannot be saved now."), current, activeDatabase), + recovery: nil, + underlying: nil + ) + } + return nil + } + func switchDatabase(to name: String) async { await switchDatabase(to: name, inside: nil) } @@ -506,25 +622,76 @@ final class ConnectionCoordinator { // MARK: - Query History - func loadHistory() { - queryHistory = historyStorage.load(for: connection.id) - keepsDamagedHistoryCopy = historyStorage.hasSetAsideCopies + // The file is read and written off the main actor, so a run never waits on it. + func loadHistory() async { + let read = await Self.readHistory(for: connection.id, in: historyStorage) + show(read.listed) + keepsDamagedHistoryCopy = read.keepsDamagedCopy + } + + func addHistoryItem(_ item: QueryHistoryItem) async { + guard let listed = await Self.record(item, in: historyStorage) else { return } + show(listed) + } + + // Saves finish in any order; a list read before a later write never replaces what that write left. + private func show(_ listed: QueryHistoryStorage.Listed) { + guard listed.generation >= historyGeneration else { return } + historyGeneration = listed.generation + queryHistory = listed.items + } + + @concurrent + nonisolated private static func readHistory( + for connectionId: UUID, + in storage: QueryHistoryStorage + ) async -> (listed: QueryHistoryStorage.Listed, keepsDamagedCopy: Bool) { + (storage.listed(for: connectionId), storage.hasSetAsideCopies) } - func addHistoryItem(_ item: QueryHistoryItem) { - guard historyStorage.save(item) else { return } - loadHistory() + @concurrent + nonisolated private static func record( + _ item: QueryHistoryItem, + in storage: QueryHistoryStorage + ) async -> QueryHistoryStorage.Listed? { + storage.record(item) } - func deleteHistoryItem(_ id: UUID) { - historyStorage.delete(id) + // The row leaves the list at once, as a swipe expects, and the stored list, with any run saved meanwhile, follows. + @discardableResult + func deleteHistoryItem(_ id: UUID) -> Task { queryHistory.removeAll { $0.id == id } + let connectionId = connection.id + let storage = historyStorage + return Task { + let read = await Self.changeHistory(for: connectionId, in: storage) { $0.delete(id) } + show(read.listed) + } } - func clearHistory() { - historyStorage.clearAll(for: [connection.id], removingSetAsideCopies: keepsDamagedHistoryCopy) + @discardableResult + func clearHistory() -> Task { + let removingSetAside = keepsDamagedHistoryCopy + let connectionId = connection.id + let storage = historyStorage queryHistory = [] - keepsDamagedHistoryCopy = historyStorage.hasSetAsideCopies + return Task { + let read = await Self.changeHistory(for: connectionId, in: storage) { storage in + storage.clearAll(for: [connectionId], removingSetAsideCopies: removingSetAside) + } + show(read.listed) + keepsDamagedHistoryCopy = read.keepsDamagedCopy + } + } + + @concurrent + nonisolated private static func changeHistory( + for connectionId: UUID, + in storage: QueryHistoryStorage, + _ change: @Sendable (QueryHistoryStorage) -> Void + ) async -> (listed: QueryHistoryStorage.Listed, keepsDamagedCopy: Bool) { + change(storage) + return (storage.listed(for: connectionId), storage.hasSetAsideCopies) } func navigateToPendingTable() { diff --git a/apple/TableProMobile/TableProMobile/Coordinators/ConnectionSessionModel.swift b/apple/TableProMobile/TableProMobile/Coordinators/ConnectionSessionModel.swift index f8435c26d4..a1928c4a55 100644 --- a/apple/TableProMobile/TableProMobile/Coordinators/ConnectionSessionModel.swift +++ b/apple/TableProMobile/TableProMobile/Coordinators/ConnectionSessionModel.swift @@ -126,6 +126,10 @@ final class ConnectionSessionModel { record.type == .oracle } + var qualifiesTablesWithDatabase: Bool { + record.type == .mysql || record.type == .mariadb || record.type == .tidb || record.type == .oceanbase + } + private var redialsToSwitchDatabase: Bool { record.type == .postgresql || record.type == .redshift } @@ -687,6 +691,11 @@ final class ConnectionSessionModel { } enter(.adopt(live, by: nil)) commit(load, at: target, onFailure: .empty, for: request) + // The next open restores where the session went, not a schema a Roll Back or a commit can still take back. + if let schema = moved.schema, activeSchema == schema, + appState.sessionTransactions.hold(for: connectionId, on: live.driver) == nil { + UserDefaults.standard.set(schema, forKey: ConnectionDefaultsKey.lastSchema.name(for: connectionId)) + } // SQL Server lists another database's schemas. if moved.database != nil { await loadSchemas(restoring: activeSchema, from: scene) @@ -704,6 +713,19 @@ final class ConnectionSessionModel { switchesInFlight -= 1 } + // Runs with a `USE` in flight on the shared session, in any window. + private var databaseMoves = 0 + + var isDatabaseMoving: Bool { databaseMoves > 0 } + + func beginDatabaseMove() { + databaseMoves += 1 + } + + func endDatabaseMove() { + databaseMoves = max(0, databaseMoves - 1) + } + private func beginPlacementRequest() -> Int { placementEpoch += 1 return placementEpoch @@ -903,6 +925,14 @@ final class ConnectionSessionModel { await reloadMetadataIfReleased(from: scene) return } + // PostgreSQL undoes a `SET search_path` the transaction made, the picker's own among them, so the lists follow + // the session back. + if supportsSchemas, let reporting = session?.driver as? any SessionSchemaReporting { + await reporting.settleCurrentSchema() + if reporting === session?.driver, reporting.currentSchema.map({ $0 != activeSchema }) == true { + await follow(from: scene) + } + } guard let session else { return } let load = await loadTables(in: supportsSchemas ? activeSchema : nil, on: session) commit(load, onFailure: .keep) diff --git a/apple/TableProMobile/TableProMobile/Drivers/MSSQLDriver.swift b/apple/TableProMobile/TableProMobile/Drivers/MSSQLDriver.swift index 98bdec9fd4..6182d6bd72 100644 --- a/apple/TableProMobile/TableProMobile/Drivers/MSSQLDriver.swift +++ b/apple/TableProMobile/TableProMobile/Drivers/MSSQLDriver.swift @@ -20,7 +20,7 @@ nonisolated private extension MSSQLRawResult { } } -nonisolated final class MSSQLDriver: DatabaseDriver, @unchecked Sendable { +nonisolated final class MSSQLDriver: DatabaseDriver, SessionDatabaseReporting, @unchecked Sendable { private static let logger = Logger(subsystem: "com.TablePro", category: "MSSQLDriver") nonisolated(unsafe) private var conn: FreeTDSConnection @@ -33,8 +33,15 @@ nonisolated final class MSSQLDriver: DatabaseDriver, @unchecked Sendable { var supportsSchemas: Bool { true } var supportsTransactions: Bool { true } var sendsBatchesWhole: Bool { true } + var reportsDatabaseWithoutStatement: Bool { false } nonisolated(unsafe) private(set) var currentSchema: String? = "dbo" + // A connection that names no database opens in the login's default one, which only the server knows. + private let sessionDatabaseName = OSAllocatedUnfairLock(initialState: nil) + + var currentDatabase: String? { + sessionDatabaseName.withLock { $0 } + } nonisolated(unsafe) private(set) var serverVersion: String? // This form collects no CA for FreeTDS, so a verify mode from the Mac or an import cannot be honoured here. @@ -106,6 +113,8 @@ nonisolated final class MSSQLDriver: DatabaseDriver, @unchecked Sendable { } } + _ = try? await sessionDatabase() + if let serverSchema = try? await runQuery(MSSQLSchemaQueries.currentSchema).rows.first?.first ?? nil, !serverSchema.isEmpty { currentSchema = serverSchema @@ -281,6 +290,7 @@ nonisolated final class MSSQLDriver: DatabaseDriver, @unchecked Sendable { } catch let error as MSSQLCoreError { throw mapToConnectionError(error) } + sessionDatabaseName.withLock { $0 = name } } func fetchSchemas() async throws -> [String] { @@ -292,6 +302,12 @@ nonisolated final class MSSQLDriver: DatabaseDriver, @unchecked Sendable { currentSchema = name } + func sessionDatabase() async throws -> String? { + let name = try await runQuery(MSSQLPrincipalQueries.currentDatabase).rows.first?.first ?? nil + sessionDatabaseName.withLock { $0 = name } + return name + } + // MARK: - Table Metadata private var effectiveSchema: String { currentSchema ?? "dbo" } diff --git a/apple/TableProMobile/TableProMobile/Drivers/MySQLDriver.swift b/apple/TableProMobile/TableProMobile/Drivers/MySQLDriver.swift index cf0a58a580..47bb123785 100644 --- a/apple/TableProMobile/TableProMobile/Drivers/MySQLDriver.swift +++ b/apple/TableProMobile/TableProMobile/Drivers/MySQLDriver.swift @@ -10,7 +10,7 @@ import TableProPluginKit import TableProSQLGrammar import TableProSQLQuoting -nonisolated final class MySQLDriver: DatabaseDriver, @unchecked Sendable { +nonisolated final class MySQLDriver: DatabaseDriver, SessionDatabaseReporting, @unchecked Sendable { private let actor = MySQLActor() private let host: String private let port: Int @@ -32,6 +32,7 @@ nonisolated final class MySQLDriver: DatabaseDriver, @unchecked Sendable { var supportsSchemas: Bool { false } var currentSchema: String? { nil } var supportsTransactions: Bool { true } + var reportsDatabaseWithoutStatement: Bool { false } private let settledFacts = OSAllocatedUnfairLock(initialState: nil) @@ -376,6 +377,11 @@ nonisolated final class MySQLDriver: DatabaseDriver, @unchecked Sendable { throw MySQLError.unsupported("MySQL does not support schemas") } + // NULL once no database is selected, as after a DROP DATABASE of the one the session was in. + func sessionDatabase() async throws -> String? { + try await actor.execute("SELECT DATABASE()").rows.first?.first ?? nil + } + func fetchSchemas() async throws -> [String] { [] } func beginTransaction() async throws { diff --git a/apple/TableProMobile/TableProMobile/Drivers/PostgreSQLDriver.swift b/apple/TableProMobile/TableProMobile/Drivers/PostgreSQLDriver.swift index f36df9f778..1bf56c825c 100644 --- a/apple/TableProMobile/TableProMobile/Drivers/PostgreSQLDriver.swift +++ b/apple/TableProMobile/TableProMobile/Drivers/PostgreSQLDriver.swift @@ -9,7 +9,7 @@ import TableProQuery import TableProSQLGrammar import TableProSQLQuoting -nonisolated final class PostgreSQLDriver: DatabaseDriver, @unchecked Sendable { +nonisolated final class PostgreSQLDriver: DatabaseDriver, SessionSchemaReporting, @unchecked Sendable { static let logger = Logger(subsystem: "com.TablePro", category: "PostgreSQLDriver") private let actor = PostgreSQLActor() @@ -38,8 +38,12 @@ nonisolated final class PostgreSQLDriver: DatabaseDriver, @unchecked Sendable { return SQLQuoting.stringLiteralBody(value, escapes: escapes) } - // Set once during connect()/switchSchema() before the driver is shared — safe for concurrent reads - nonisolated(unsafe) private(set) var currentSchema: String? = "public" + // A run's end writes it while a window reads it, so it sits behind a lock. + private let sessionSchema = OSAllocatedUnfairLock(initialState: "public") + + var currentSchema: String? { + sessionSchema.withLock { $0 } + } nonisolated(unsafe) private(set) var serverVersion: String? nonisolated(unsafe) private(set) var serverVersionNumber: Int32 = 0 nonisolated(unsafe) private(set) var catalogPresence = PostgreSQLDriver.presence(probedRows: nil) @@ -94,7 +98,7 @@ nonisolated final class PostgreSQLDriver: DatabaseDriver, @unchecked Sendable { serverVersionNumber = await actor.serverVersionNumber() catalogPresence = await probeCatalogPresence() columnReadSupport = PostgreSQLColumnReadSupport() - await adoptServerSchema() + await settleCurrentSchema() await settleLexicalFacts() } @@ -117,10 +121,11 @@ nonisolated final class PostgreSQLDriver: DatabaseDriver, @unchecked Sendable { } } - private func adoptServerSchema() async { - guard let schema = try? await actor.execute("SELECT pg_catalog.current_schema()").rows.first?.first ?? nil, - !schema.isEmpty else { return } - currentSchema = schema + // A typed `SET search_path` moves it, and a transaction's end takes back a `SET` made inside it, the picker's own + // among them. Inside a transaction block the schema waits for the block to end. + func settleCurrentSchema() async { + guard let schema = await actor.currentSchemaOutsideBlock(), !schema.isEmpty else { return } + sessionSchema.withLock { $0 = schema } } func disconnect() async throws { @@ -279,7 +284,7 @@ nonisolated final class PostgreSQLDriver: DatabaseDriver, @unchecked Sendable { func switchSchema(to name: String) async throws { _ = try await actor.execute("SET search_path TO \(SQLQuoting.identifier(name))") - currentSchema = name + sessionSchema.withLock { $0 = name } } func fetchSchemas() async throws -> [String] { @@ -475,6 +480,12 @@ private actor PostgreSQLActor { ) } + // A read inside a block would take a REPEATABLE READ transaction's snapshot, and a later SET TRANSACTION would fail. + func currentSchemaOutsideBlock() -> String? { + guard let conn, !PostgreSQLSessionTransaction.isInsideBlock(PQtransactionStatus(conn)) else { return nil } + return (try? execute("SELECT pg_catalog.current_schema()"))?.rows.first?.first ?? nil + } + func ping() throws { guard let conn else { throw PostgreSQLError.notConnected } guard PostgreSQLSessionTransaction.pingSendsStatement(in: PQtransactionStatus(conn)) else { @@ -1160,7 +1171,7 @@ nonisolated private func pgOidToTypeName(_ oid: UInt32) -> String { case 700: return "real" case 701: return "double precision" case 869: return "inet" - // PostgreSQL OID constants — separators would obscure the wire-protocol values + // PostgreSQL OID constants: separators would obscure the wire-protocol values // swiftlint:disable number_separator case 1042: return "char" case 1043: return "varchar" diff --git a/apple/TableProMobile/TableProMobile/Drivers/SessionPlacementReporting.swift b/apple/TableProMobile/TableProMobile/Drivers/SessionPlacementReporting.swift new file mode 100644 index 0000000000..1737a8207e --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Drivers/SessionPlacementReporting.swift @@ -0,0 +1,24 @@ +import Foundation +import TableProDatabase + +// A statement the user runs can move the session to another database: a MySQL or SQL Server `USE`, a MongoDB `use`. +// The app's unqualified names then resolve there, so the picker follows what the session says. +nonisolated protocol SessionDatabaseReporting: DatabaseDriver { + // True when asking costs no statement on the session, which would replace what the user's last one left there. + var reportsDatabaseWithoutStatement: Bool { get } + func sessionDatabase() async throws -> String? +} + +// A statement the user runs, or a rollback that undoes a `SET`, can move the session's schema. +nonisolated protocol SessionSchemaReporting: DatabaseDriver { + // Reads the schema from the session into `currentSchema`; a session that cannot answer keeps what it had. + func settleCurrentSchema() async +} + +nonisolated extension PluginBackedDriver: SessionDatabaseReporting { + var reportsDatabaseWithoutStatement: Bool { true } + + func sessionDatabase() async throws -> String? { + try await settledCurrentDatabase() + } +} diff --git a/apple/TableProMobile/TableProMobile/Helpers/ClipboardExporter.swift b/apple/TableProMobile/TableProMobile/Helpers/ClipboardExporter.swift index dfc7c70383..f92dfca54b 100644 --- a/apple/TableProMobile/TableProMobile/Helpers/ClipboardExporter.swift +++ b/apple/TableProMobile/TableProMobile/Helpers/ClipboardExporter.swift @@ -183,21 +183,56 @@ nonisolated enum ClipboardExporter { for (i, col) in columns.enumerated() { let value = i < row.count ? row[i] : nil let key = " " + JSONText.stringLiteral(col.name) - if let value { - if isJsonNumber(value) { - pairs.append("\(key): \(value)") - } else if value == "true" || value == "false" { - pairs.append("\(key): \(value)") - } else { - pairs.append("\(key): \(JSONText.stringLiteral(value))") - } - } else { - pairs.append("\(key): null") - } + pairs.append("\(key): \(value.map { jsonValue($0, typeName: col.typeName) } ?? "null")") } return "{\n" + pairs.joined(separator: ",\n") + "\n}" } + // The column's type decides, as in the Mac export: text that reads like a number or `true` stays text. A column with + // no type, as SQLite reports for an expression, is read by its value. + private static func jsonValue(_ value: String, typeName: String) -> String { + if typeName.trimmingCharacters(in: .whitespaces).isEmpty { + let bare = isJsonNumber(value) || value == "true" || value == "false" + return bare ? value : JSONText.stringLiteral(value) + } + if isBooleanType(typeName), let flag = booleanLiteral(value) { + return flag + } + if isNumberType(typeName), isJsonNumber(value) { + return value + } + return JSONText.stringLiteral(value) + } + + // PostgreSQL's text format sends `t` or `f`, and SQLite keeps a boolean as 1 or 0. + private static func booleanLiteral(_ value: String) -> String? { + switch value.lowercased() { + case "true", "t", "1": "true" + case "false", "f", "0": "false" + default: nil + } + } + + // SQL Server documents `bit` as an integer type that holds 1, 0 or NULL. + private static func isNumberType(_ typeName: String) -> Bool { + ColumnInfo.isNumericType(typeName: typeName) || unwrappedTypeName(typeName) == "bit" + } + + private static func isBooleanType(_ typeName: String) -> Bool { + let base = unwrappedTypeName(typeName) + return base == "bool" || base == "boolean" + } + + // ClickHouse wraps the type, as in `Nullable(Bool)`. + private static func unwrappedTypeName(_ typeName: String) -> String { + var base = typeName.lowercased().trimmingCharacters(in: .whitespaces) + while base.hasSuffix(")"), let open = base.firstIndex(of: "("), + ["nullable", "lowcardinality"].contains(String(base[.. String { var lines: [String] = [] if includeHeader { diff --git a/apple/TableProMobile/TableProMobile/Helpers/QueryHistoryStorage.swift b/apple/TableProMobile/TableProMobile/Helpers/QueryHistoryStorage.swift index 3675636728..6fab3334ef 100644 --- a/apple/TableProMobile/TableProMobile/Helpers/QueryHistoryStorage.swift +++ b/apple/TableProMobile/TableProMobile/Helpers/QueryHistoryStorage.swift @@ -36,11 +36,29 @@ nonisolated struct QueryHistoryItem: Identifiable, Codable, Hashable { } } -nonisolated struct QueryHistoryStorage { +// One per library. The file is read once; every later read comes from the copy in memory, which takes a change only +// once the file holds it. The lock orders a save running off the main actor with a delete or clear on it. +nonisolated final class QueryHistoryStorage: Sendable { private static let maxEntries = 200 + // The whole list is encoded on every save, so its text is held to this many bytes; the newest entry always stays, + // and no entry is ever cut, since running part of a script from history would run part of it. + static let maxTextBytes = 2 * 1_024 * 1_024 private static let logger = Logger(subsystem: "com.TablePro", category: "QueryHistoryStorage") private let directory: URL + private let state = OSAllocatedUnfairLock(initialState: State()) + + private nonisolated struct State { + // Nil until the file has been read. + var items: [QueryHistoryItem]? + // Counts the writes, so a list read before a later write is never shown over it. + var generation = 0 + } + + nonisolated struct Listed: Sendable { + let items: [QueryHistoryItem] + let generation: Int + } init(directory: URL) { self.directory = directory @@ -52,42 +70,91 @@ nonisolated struct QueryHistoryStorage { @discardableResult func save(_ item: QueryHistoryItem) -> Bool { - guard var items = readAll() else { return false } - if let last = items.last, - last.query == item.query, - last.connectionId == item.connectionId, - last.wasSuccessful == item.wasSuccessful { - return false + record(item) != nil + } + + // The connection's list once the item is saved, read from memory; nil when nothing was saved. + func record(_ item: QueryHistoryItem) -> Listed? { + state.withLock { state -> Listed? in + guard var items = cached(&state) else { return nil } + if let last = items.last, + last.query == item.query, + last.connectionId == item.connectionId, + last.wasSuccessful == item.wasSuccessful { + return nil + } + items.append(item) + items = Self.withinBudget(items) + guard commit(items, to: &state) else { return nil } + return Listed(items: items.filter { $0.connectionId == item.connectionId }, generation: state.generation) } - items.append(item) - if items.count > Self.maxEntries { - items.removeFirst(items.count - Self.maxEntries) + } + + func listed(for connectionId: UUID) -> Listed { + state.withLock { state in + let items = cached(&state) ?? [] + return Listed(items: items.filter { $0.connectionId == connectionId }, generation: state.generation) } - return writeAll(items) } func loadAll() -> [QueryHistoryItem] { - readAll() ?? [] + state.withLock { cached(&$0) } ?? [] } func load(for connectionId: UUID) -> [QueryHistoryItem] { loadAll().filter { $0.connectionId == connectionId } } + var generation: Int { + state.withLock { $0.generation } + } + func delete(_ id: UUID) { - guard var items = readAll() else { return } - items.removeAll { $0.id == id } - writeAll(items) + state.withLock { state in + guard var items = cached(&state) else { return } + items.removeAll { $0.id == id } + commit(items, to: &state) + } } // The set-aside copy holds every connection's history: only a clear asked for after the footer named it removes it. func clearAll(for connectionIds: Set, removingSetAsideCopies: Bool = false) { - guard let items = readAll() else { return } - let kept = items.filter { !connectionIds.contains($0.connectionId) } - if kept.count != items.count, !writeAll(kept) { return } - if removingSetAsideCopies { - removeSetAsideCopies() + state.withLock { state in + guard let items = cached(&state) else { return } + let kept = items.filter { !connectionIds.contains($0.connectionId) } + if kept.count != items.count { + guard commit(kept, to: &state) else { return } + } + if removingSetAsideCopies { + removeSetAsideCopies() + } + } + } + + static func withinBudget(_ items: [QueryHistoryItem]) -> [QueryHistoryItem] { + var kept: [QueryHistoryItem] = [] + var bytes = 0 + for item in items.reversed() { + let size = item.query.utf8.count + (item.errorMessage?.utf8.count ?? 0) + guard kept.isEmpty || (kept.count < maxEntries && bytes + size <= maxTextBytes) else { break } + kept.append(item) + bytes += size } + return kept.reversed() + } + + // nil while the file cannot be read (a locked device), so no write replaces it with a partial list. + private func cached(_ state: inout State) -> [QueryHistoryItem]? { + if state.items == nil { state.items = readAll() } + return state.items + } + + @discardableResult + private func commit(_ items: [QueryHistoryItem], to state: inout State) -> Bool { + guard writeAll(items) else { return false } + state.items = items + state.generation += 1 + return true } var hasSetAsideCopies: Bool { @@ -111,7 +178,6 @@ nonisolated struct QueryHistoryStorage { } } - // nil while the file cannot be read (a locked device), so no write replaces it with a partial list. private func readAll() -> [QueryHistoryItem]? { guard FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) else { return [] } guard let data = try? Data(contentsOf: fileURL) else { return nil } diff --git a/apple/TableProMobile/TableProMobile/Helpers/SessionLocalStatements.swift b/apple/TableProMobile/TableProMobile/Helpers/SessionLocalStatements.swift index 5f5c1d92c6..fb746b4caa 100644 --- a/apple/TableProMobile/TableProMobile/Helpers/SessionLocalStatements.swift +++ b/apple/TableProMobile/TableProMobile/Helpers/SessionLocalStatements.swift @@ -11,6 +11,9 @@ nonisolated enum SessionLocalStatements { // A `USE`, a role or a search path moved the session off what the catalog connection sees, or a procedure or // dynamic SQL may have made a table only the session sees. var leavesCatalog = false + // A `USE` ran, the one statement that moves a MySQL or SQL Server session to another database: a procedure or + // dynamic SQL cannot, and SQL Server puts the database back when its `EXEC` or procedure ends. + var usesDatabase = false } private static let identifier = #"(`(?:[^`]|``)+`|"(?:[^"]|"")+"|\[[^\]]+\]|[\w$#]+)"# @@ -66,8 +69,10 @@ nonisolated enum SessionLocalStatements { effect.temporaryTables.insert(name) } let range = NSRange(location: 0, length: (code as NSString).length) + let uses = usePattern?.firstMatch(in: code, range: range) != nil + if uses { effect.usesDatabase = true } // A MySQL executable comment can hide any statement, a temporary table among them, from the patterns. - if usePattern?.firstMatch(in: code, range: range) != nil + if uses || contextPattern?.firstMatch(in: code, range: range) != nil || SQLLeadingComments.conditionalCommentOpeners.contains(where: { (code as NSString).range(of: $0, options: .literal).location != NSNotFound diff --git a/apple/TableProMobile/TableProMobile/Localizable.xcstrings b/apple/TableProMobile/TableProMobile/Localizable.xcstrings index 2588102bc1..bafad10cd7 100644 --- a/apple/TableProMobile/TableProMobile/Localizable.xcstrings +++ b/apple/TableProMobile/TableProMobile/Localizable.xcstrings @@ -1927,6 +1927,9 @@ }, "A number in %@ is larger than a 64-bit integer. Write it as a decimal, such as {\"$numberDecimal\": \"12345678901234567890\"}." : { + }, + "A query that switches the database is running on this connection. Try again once it ends." : { + }, "A renamed column's foreign key is rewritten, so its MATCH and DEFERRABLE clauses are not carried over." : { "extractionState" : "manual", @@ -7738,6 +7741,9 @@ } } } + }, + "Database Switch Running" : { + }, "Database Type" : { "localizations" : { @@ -20732,6 +20738,9 @@ "Services" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Session in Another Database" : { + }, "Session Token" : { "extractionState" : "manual", @@ -24451,6 +24460,9 @@ } } } + }, + "The connection moved to another database or schema. Choose the row again." : { + }, "The connection moved to another database or schema. Choose the table again." : { @@ -25738,6 +25750,26 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "The query moved the session to “%@” and it could not go back to “%@”. To save the unsaved changes, run USE %@ in the Query tab of the window that holds them." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "The query moved the session to “%1$@” and it could not go back to “%2$@”. To save the unsaved changes, run USE %3$@ in the Query tab of the window that holds them." + } + } + } + }, + "The query moved the session to “%@” and it could not go back to “%@”. Unsaved changes still save to “%@”." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "The query moved the session to “%1$@” and it could not go back to “%2$@”. Unsaved changes still save to “%3$@”." + } + } + } + }, "The query names its own output format, %@. Remove its FORMAT clause to read it as rows." : { }, @@ -26330,6 +26362,16 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "The session is in “%@”, not “%@”, so this change cannot be saved now." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "The session is in “%1$@”, not “%2$@”, so this change cannot be saved now." + } + } + } + }, "The shell drops a field named __proto__ from a new document. Remove the field, then set it on the saved document." : { }, @@ -27933,6 +27975,9 @@ } } } + }, + "This window has unsaved changes on this connection, so the session stayed on its database. Save or discard them before switching database." : { + }, "Ticket" : { "extractionState" : "manual", diff --git a/apple/TableProMobile/TableProMobile/Platform/ConnectionSecretsCopier.swift b/apple/TableProMobile/TableProMobile/Platform/ConnectionSecretsCopier.swift index 727fe85322..84b0ccc2d3 100644 --- a/apple/TableProMobile/TableProMobile/Platform/ConnectionSecretsCopier.swift +++ b/apple/TableProMobile/TableProMobile/Platform/ConnectionSecretsCopier.swift @@ -11,15 +11,18 @@ nonisolated struct ConnectionSecrets: Sendable { let secureStore: any SecureStore let certificateStore: any CertificateMaterialStoring let bookmarkStore: FileBookmarkStore + let materializer: CertificateMaterializer init( secureStore: any SecureStore, certificateStore: any CertificateMaterialStoring = CertificateMaterialStore(), - bookmarkStore: FileBookmarkStore = FileBookmarkStore() + bookmarkStore: FileBookmarkStore = FileBookmarkStore(), + materializer: CertificateMaterializer = CertificateMaterializer() ) { self.secureStore = secureStore self.certificateStore = certificateStore self.bookmarkStore = bookmarkStore + self.materializer = materializer } @discardableResult @@ -74,6 +77,8 @@ nonisolated struct ConnectionSecrets: Sendable { try? secureStore.delete(forKey: prefix + connectionId.uuidString) } certificateStore.deleteAll(for: connectionId) + // A connect wrote the decrypted client key to a file the drivers read. + materializer.release(for: connectionId) bookmarkStore.delete(for: connectionId) } } diff --git a/apple/TableProMobile/TableProMobile/Platform/SessionTransactionMonitor.swift b/apple/TableProMobile/TableProMobile/Platform/SessionTransactionMonitor.swift index b74ed25335..dc2d6ee94f 100644 --- a/apple/TableProMobile/TableProMobile/Platform/SessionTransactionMonitor.swift +++ b/apple/TableProMobile/TableProMobile/Platform/SessionTransactionMonitor.swift @@ -44,6 +44,7 @@ final class SessionTransactionMonitor { private var rollBackCounts: [UUID: Int] = [:] @ObservationIgnored private var refreshGenerations: [UUID: Int] = [:] @ObservationIgnored private var workGenerations: [UUID: Int] = [:] + @ObservationIgnored private var statementWaiters: [UUID: [UUID: CheckedContinuation]] = [:] @ObservationIgnored private let liveDriver: (UUID) -> (any DatabaseDriver)? init(liveDriver: @escaping (UUID) -> (any DatabaseDriver)?) { @@ -88,6 +89,26 @@ final class SessionTransactionMonitor { statementCounts[connectionId, default: 0] > 0 } + // A run that moves the session's database lets a write already on its way finish where it was aimed. Stop ends the + // wait, as it ends a run queued behind another. + func statementsFinished(for connectionId: UUID) async { + guard isRunningStatements(connectionId) else { return } + let waiter = UUID() + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + guard !Task.isCancelled else { + continuation.resume() + return + } + statementWaiters[connectionId, default: [:]][waiter] = continuation + } + } onCancel: { + Task { @MainActor [weak self] in + self?.statementWaiters[connectionId]?.removeValue(forKey: waiter)?.resume() + } + } + } + // `reading` work keeps Commit and Roll Back off the session while it streams, and stales a dialog opened before it. func track(_ connectionId: UUID, reading: Bool = false, _ work: () async throws -> T) async rethrows -> T { workCounts[connectionId, default: 0] += 1 @@ -207,6 +228,10 @@ final class SessionTransactionMonitor { guard !reading else { return } let statements = statementCounts[connectionId, default: 1] - 1 statementCounts[connectionId] = statements > 0 ? statements : nil + guard statements <= 0 else { return } + for waiter in (statementWaiters.removeValue(forKey: connectionId) ?? [:]).values { + waiter.resume() + } } } diff --git a/apple/TableProMobile/TableProMobile/Security/CertificateMaterializer.swift b/apple/TableProMobile/TableProMobile/Security/CertificateMaterializer.swift index 88aee704b9..d724150c54 100644 --- a/apple/TableProMobile/TableProMobile/Security/CertificateMaterializer.swift +++ b/apple/TableProMobile/TableProMobile/Security/CertificateMaterializer.swift @@ -17,15 +17,26 @@ nonisolated final class CertificateMaterializer: @unchecked Sendable { private let store: any CertificateMaterialStoring private let fileManager: FileManager + private let root: URL? - init(store: any CertificateMaterialStoring = CertificateMaterialStore(), fileManager: FileManager = .default) { + // `root` is the folder that holds one folder per connection; nil is Application Support's. + init( + store: any CertificateMaterialStoring = CertificateMaterialStore(), + fileManager: FileManager = .default, + root: URL? = nil + ) { self.store = store self.fileManager = fileManager + self.root = root } + // A role the store no longer holds loses its file, so a certificate removed in the form leaves no key behind. func materialize(for connectionId: UUID) throws -> MaterializedCertificates { let paths = try CertificateRole.allCases.reduce(into: [CertificateRole: String]()) { result, role in - guard let pem = store.pem(role: role, for: connectionId) else { return } + guard let pem = store.pem(role: role, for: connectionId) else { + release(role, for: connectionId) + return + } result[role] = try write(pem, role: role, for: connectionId) } @@ -39,7 +50,31 @@ nonisolated final class CertificateMaterializer: @unchecked Sendable { func release(for connectionId: UUID) { let directory = directory(for: connectionId) guard fileManager.fileExists(atPath: directory.path) else { return } - try? fileManager.removeItem(at: directory) + do { + try fileManager.removeItem(at: directory) + } catch { + Self.logger.error("Client certificate files were not removed: \(error.localizedDescription, privacy: .private)") + } + } + + // Deletes before this release left the files of connections that are gone. Only a loaded library may ask. + func releaseAll(except kept: Set) { + guard let root = try? rootDirectory(), + let names = try? fileManager.contentsOfDirectory(atPath: root.path) else { return } + for name in names { + guard let connectionId = UUID(uuidString: name), !kept.contains(connectionId) else { continue } + release(for: connectionId) + } + } + + func release(_ role: CertificateRole, for connectionId: UUID) { + let file = directory(for: connectionId).appendingPathComponent("\(role.rawValue).pem") + guard fileManager.fileExists(atPath: file.path) else { return } + do { + try fileManager.removeItem(at: file) + } catch { + Self.logger.error("A stale client certificate file was not removed: \(error.localizedDescription, privacy: .private)") + } } private func write(_ pem: String, role: CertificateRole, for connectionId: UUID) throws -> String { @@ -72,6 +107,7 @@ nonisolated final class CertificateMaterializer: @unchecked Sendable { } private func rootDirectory() throws -> URL { + if let root { return root } let support = try fileManager.url( for: .applicationSupportDirectory, in: .userDomainMask, diff --git a/apple/TableProMobile/TableProMobile/ViewModels/ConnectionFormViewModel+Certificates.swift b/apple/TableProMobile/TableProMobile/ViewModels/ConnectionFormViewModel+Certificates.swift index 2b4a3991b0..c3397a0e25 100644 --- a/apple/TableProMobile/TableProMobile/ViewModels/ConnectionFormViewModel+Certificates.swift +++ b/apple/TableProMobile/TableProMobile/ViewModels/ConnectionFormViewModel+Certificates.swift @@ -84,6 +84,8 @@ extension ConnectionFormViewModel { func persistCertificates(for connectionId: UUID) -> Bool { for role in removedCertificates where pendingCertificates[role] == nil { certificateStore.delete(role: role, for: connectionId) + // A connect wrote it to a file the drivers read, and no connect may follow to clear it. + CertificateMaterializer(store: certificateStore).release(role, for: connectionId) storedCertificateRoles.remove(role) } removedCertificates.removeAll() diff --git a/apple/TableProMobile/TableProMobile/ViewModels/DataBrowserViewModel.swift b/apple/TableProMobile/TableProMobile/ViewModels/DataBrowserViewModel.swift index ddf69bbe3e..2dafc1a8b0 100644 --- a/apple/TableProMobile/TableProMobile/ViewModels/DataBrowserViewModel.swift +++ b/apple/TableProMobile/TableProMobile/ViewModels/DataBrowserViewModel.swift @@ -335,15 +335,25 @@ final class DataBrowserViewModel { ) } - // SQL Server's `OFFSET FETCH` requires `ORDER BY`. Without a user sort, a key column keeps paging stable. + // The whole key orders the page, after the user's sort as its tiebreak. PostgreSQL and ClickHouse return an + // unpredictable subset for LIMIT and OFFSET without an order, so Next Page repeats and skips rows; a ClickHouse key + // need not be unique, so rows that share one can still trade places. SQL Server and Oracle `OFFSET FETCH` needs an + // ORDER BY, so a keyless table there sorts by its first column. Redshift keys are not enforced and its sort is a full + // sort, so it pages as it scans. private func effectiveSortState() -> SortState { - if sortState.isSorting { return sortState } - guard databaseType == .mssql || databaseType == .oracle else { return sortState } - let fallback = columnDetails.first(where: \.isPrimaryKey)?.name ?? columnDetails.first?.name - guard let fallback else { return sortState } - return SortState(columns: [SortColumn(name: fallback, ascending: true)]) + guard Self.keyOrderedPaging.contains(databaseType) else { return sortState } + var keyColumns = columnDetails.filter(\.isPrimaryKey).map(\.name) + if keyColumns.isEmpty, !sortState.isSorting, databaseType == .mssql || databaseType == .oracle, + let first = columnDetails.first { + keyColumns = [first.name] + } + let tiebreak = keyColumns.filter { key in !sortState.columns.contains { $0.name == key } } + guard !tiebreak.isEmpty else { return sortState } + return SortState(columns: sortState.columns + tiebreak.map { SortColumn(name: $0, ascending: true) }) } + private static let keyOrderedPaging: Set = [.postgresql, .clickhouse, .mssql, .oracle] + private func readRequest(table: TableInfo) -> TableReadRequest { TableReadRequest( table: table.name, @@ -492,6 +502,29 @@ final class DataBrowserViewModel { ) } + // Where the rows on screen were read. Another window's switch re-attaches the browser to another schema, where the + // same key names another row. + struct RowSource: Equatable { + let driver: ObjectIdentifier? + let schema: String? + } + + var rowSource: RowSource { + RowSource(driver: session.map { ObjectIdentifier($0.driver) }, schema: schema) + } + + func refusesDelete(raisedOn source: RowSource) -> Bool { + guard source != rowSource else { return false } + operationError = AppError( + category: .query, + title: String(localized: "Row Not Deleted"), + message: String(localized: "The connection moved to another database or schema. Choose the row again."), + recovery: nil, + underlying: nil + ) + return true + } + func deleteRow(_ locator: RowLocator) async -> Bool { guard let session, let table else { return false } let schema = schema diff --git a/apple/TableProMobile/TableProMobile/Views/Components/LiteralInputTraits.swift b/apple/TableProMobile/TableProMobile/Views/Components/LiteralInputTraits.swift index 7ebbf7c185..dcd3b61333 100644 --- a/apple/TableProMobile/TableProMobile/Views/Components/LiteralInputTraits.swift +++ b/apple/TableProMobile/TableProMobile/Views/Components/LiteralInputTraits.swift @@ -28,3 +28,16 @@ extension UITextView { writingToolsBehavior = .none } } + +// The bar keeps traits of its own beside its field's, so both are set. +extension UISearchBar { + func applyLiteralInputTraits() { + autocorrectionType = .no + autocapitalizationType = .none + spellCheckingType = .no + smartQuotesType = .no + smartDashesType = .no + smartInsertDeleteType = .no + searchTextField.applyLiteralInputTraits() + } +} diff --git a/apple/TableProMobile/TableProMobile/Views/Components/LiteralSearchField.swift b/apple/TableProMobile/TableProMobile/Views/Components/LiteralSearchField.swift new file mode 100644 index 0000000000..89923ad7a2 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Views/Components/LiteralSearchField.swift @@ -0,0 +1,92 @@ +import SwiftUI +import UIKit + +// A search the server runs with LIKE: SwiftUI's `.searchable` field cannot turn smart quotes off, and Smart Punctuation +// would send `O’Brien` for `O'Brien`. +struct LiteralSearchField: UIViewRepresentable { + private let prompt: String + @Binding private var text: String + @Binding private var isEditing: Bool + private let onSubmit: () -> Void + + init(_ prompt: LocalizedStringResource, text: Binding, isEditing: Binding, onSubmit: @escaping () -> Void) { + self.prompt = String(localized: prompt) + self._text = text + self._isEditing = isEditing + self.onSubmit = onSubmit + } + + static func configure(_ bar: UISearchBar) { + bar.searchBarStyle = .minimal + bar.returnKeyType = .search + bar.applyLiteralInputTraits() + } + + func makeUIView(context: Context) -> UISearchBar { + let bar = UISearchBar() + Self.configure(bar) + bar.delegate = context.coordinator + bar.placeholder = prompt + bar.text = text + return bar + } + + func updateUIView(_ bar: UISearchBar, context: Context) { + context.coordinator.field = self + // Text being composed is the input method's until it is committed. + if bar.searchTextField.markedTextRange == nil, bar.text != text { + bar.text = text + } + if bar.placeholder != prompt { + bar.placeholder = prompt + } + bar.isUserInteractionEnabled = context.environment.isEnabled + // Focusing sends the delegate's begin-editing call, which writes `isEditing`; not while SwiftUI is updating. + if isEditing, !bar.searchTextField.isFirstResponder { + DispatchQueue.main.async { bar.searchTextField.becomeFirstResponder() } + } + } + + func sizeThatFits(_ proposal: ProposedViewSize, uiView bar: UISearchBar, context: Context) -> CGSize? { + guard let width = proposal.width, width.isFinite else { return nil } + return CGSize(width: width, height: bar.intrinsicContentSize.height) + } + + func makeCoordinator() -> Coordinator { + Coordinator(field: self) + } + + final class Coordinator: NSObject, UISearchBarDelegate { + var field: LiteralSearchField + + init(field: LiteralSearchField) { + self.field = field + } + + func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { + field.text = searchText + } + + func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { + searchBar.setShowsCancelButton(true, animated: true) + field.isEditing = true + } + + func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { + searchBar.setShowsCancelButton(false, animated: true) + field.isEditing = false + } + + func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { + field.onSubmit() + searchBar.resignFirstResponder() + } + + // As the system search does, Cancel clears the search and ends it. + func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { + searchBar.text = "" + field.text = "" + searchBar.resignFirstResponder() + } + } +} diff --git a/apple/TableProMobile/TableProMobile/Views/ConnectedView.swift b/apple/TableProMobile/TableProMobile/Views/ConnectedView.swift index 71f3fc0270..2fa227aa8a 100644 --- a/apple/TableProMobile/TableProMobile/Views/ConnectedView.swift +++ b/apple/TableProMobile/TableProMobile/Views/ConnectedView.swift @@ -86,11 +86,11 @@ struct ConnectedView: View { guard !Task.isCancelled else { return } switch resolved.phase { case .connected: - resolved.loadHistory() + await resolved.loadHistory() hapticSuccess.toggle() case .lost: // A lost open comes back to the tabs through Reconnect, which never runs this task. - resolved.loadHistory() + await resolved.loadHistory() hapticError.toggle() case .failed: hapticError.toggle() diff --git a/apple/TableProMobile/TableProMobile/Views/DataBrowserView.swift b/apple/TableProMobile/TableProMobile/Views/DataBrowserView.swift index 80a1d76327..00f7d21e11 100644 --- a/apple/TableProMobile/TableProMobile/Views/DataBrowserView.swift +++ b/apple/TableProMobile/TableProMobile/Views/DataBrowserView.swift @@ -22,7 +22,7 @@ struct DataBrowserView: View { // Not persisted. This search runs on the server and is applied on submit, so a value restored // into the field would name a filter the rows on screen were never fetched under. @State private var searchText = "" - @FocusState private var searchFocused: Bool + @State private var searchFocused = false @State private var showInsertSheet = false @State private var showFilterSheet = false @State private var showShareSheet = false @@ -31,7 +31,7 @@ struct DataBrowserView: View { @State private var showMatchedRow = false @State private var showGoToPage = false @State private var goToPageInput = "" - @State private var deleteTarget: RowLocator? + @State private var deleteTarget: PendingRowDelete? @State private var fkPreviewItem: FKPreviewItem? @State private var shareText = "" @State private var isCompletingCells = false @@ -40,7 +40,7 @@ struct DataBrowserView: View { @AppStorage(AppPreferences.rowLayoutKey) private var preferredLayout: RowLayout? private var activeSchema: String? { - coordinator.supportsSchemas ? coordinator.activeSchema : nil + coordinator.tableQualifier } private var browserSchema: String? { @@ -137,6 +137,9 @@ struct DataBrowserView: View { } // A redial or another window's database switch hands this table a new session; a referenced table keeps its schema. .onChange(of: BrowseSource(session: session, schema: browserSchema)) { _, source in + // The confirmation names a row of the table this browser showed before. + showDeleteConfirmation = false + deleteTarget = nil guard source.driver != nil else { return } viewModel.attach( session: session, table: table, databaseType: connection.type, @@ -249,11 +252,12 @@ struct DataBrowserView: View { content .tableTitle(table.name, schema: displaySchema) .navigationBarTitleDisplayMode(.inline) - .searchable(text: $searchText, prompt: "Search all columns") - .searchFocused($searchFocused) - .textInputAutocapitalization(.never) - .onSubmit(of: .search) { - Task { await viewModel.applySearch(searchText) } + .safeAreaInset(edge: .top, spacing: 0) { + LiteralSearchField("Search all columns", text: $searchText, isEditing: $searchFocused) { + Task { await viewModel.applySearch(searchText) } + } + .padding(.horizontal, 8) + .background(.bar) } .onChange(of: searchText) { oldValue, newValue in if newValue.isEmpty, !oldValue.isEmpty, viewModel.hasActiveSearch { @@ -435,7 +439,7 @@ struct DataBrowserView: View { } private func confirmDelete(_ locator: RowLocator) { - deleteTarget = locator + deleteTarget = PendingRowDelete(locator: locator, source: viewModel.rowSource) showDeleteConfirmation = true } @@ -674,7 +678,17 @@ struct DataBrowserView: View { } } - private func performDelete(_ locator: RowLocator) async { + private func performDelete(_ pending: PendingRowDelete) async { + if let refusal = coordinator.databaseMoveRefusal { + viewModel.operationError = refusal + hapticError.toggle() + return + } + guard !viewModel.refusesDelete(raisedOn: pending.source) else { + hapticError.toggle() + return + } + let locator = pending.locator let success = await coordinator.track(failed: { !$0 }) { await viewModel.deleteRow(locator) } if success { hapticSuccess.toggle() @@ -684,6 +698,11 @@ struct DataBrowserView: View { } } +private struct PendingRowDelete { + let locator: RowLocator + let source: DataBrowserViewModel.RowSource +} + private struct BrowseSource: Equatable { let driver: ObjectIdentifier? let schema: String? diff --git a/apple/TableProMobile/TableProMobile/Views/ForeignKeyNavigation.swift b/apple/TableProMobile/TableProMobile/Views/ForeignKeyNavigation.swift index b6fc1ae4f3..26860ecb69 100644 --- a/apple/TableProMobile/TableProMobile/Views/ForeignKeyNavigation.swift +++ b/apple/TableProMobile/TableProMobile/Views/ForeignKeyNavigation.swift @@ -33,8 +33,7 @@ private struct ForeignKeyPreviewModifier: ViewModifier { @State private var openedReference: ForeignKeyReference? private var currentSchema: String? { - guard let coordinator, coordinator.supportsSchemas else { return nil } - return coordinator.activeSchema + coordinator?.tableQualifier } func body(content: Content) -> some View { diff --git a/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift b/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift index cea001a54a..65c79ebe96 100644 --- a/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift +++ b/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift @@ -305,6 +305,12 @@ struct InsertRowView: View { } private func executeInsert(_ write: PlannedRowWrite) async { + if let refusal = coordinator.databaseMoveRefusal { + operationError = refusal + showOperationError = true + hapticError.toggle() + return + } isSaving = true defer { isSaving = false } diff --git a/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift b/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift index 10c61e5e8e..c5a1de6cef 100644 --- a/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift +++ b/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift @@ -380,7 +380,7 @@ struct QueryEditorView: View { } private var canRun: Bool { - !isExecuting && !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + !isExecuting && !coordinator.isDatabaseMoving && !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } private var runAtCursorTitle: String { @@ -833,8 +833,14 @@ struct QueryEditorView: View { // Claimed before the first await, so a second Run while the session reports how it reads literals starts nothing. private func executeQueryDirect(_ trimmed: String) async { guard let session, !isExecuting else { return } + // A run with a `USE` in any window holds the session until the picker follows it. + guard !coordinator.isDatabaseMoving else { + appError = ConnectionCoordinator.databaseMovingRefusal + return + } isExecuting = true + let movesDatabase = coordinator.beginDatabaseMove(ifRunning: trimmed) let startedAt = Date() executionStartTime = startedAt appError = nil @@ -843,6 +849,7 @@ struct QueryEditorView: View { await completion.finishColumnReads() let script = await plan(trimmed, on: session) guard !script.isEmpty else { + if movesDatabase { coordinator.endDatabaseMove() } isExecuting = false completion.reopenColumnReads() executionStartTime = nil @@ -857,12 +864,15 @@ struct QueryEditorView: View { startedAt: startedAt ) + // A write another window started before this run lands where it was aimed before the run can move the session. + if movesDatabase { await appState.sessionTransactions.statementsFinished(for: connectionId) } let holdsCatalog = SessionLocalStatements.changesDatabases(trimmed, databaseType: databaseType) if holdsCatalog { await appState.connectionManager.holdCatalogConnections(for: connectionId) } // Waited on before the Stop check, and nothing suspends from here until `track` marks the session busy, which // keeps a new list reload off it. await appState.catalogChanges.sessionReadsFinished(for: connectionId) guard !Task.isCancelled else { + if movesDatabase { coordinator.endDatabaseMove() } if holdsCatalog { appState.connectionManager.releaseCatalogConnections(for: connectionId) } recordHistory(query: trimmed, outcome: .stopped, errorMessage: QueryExecutionOutcome.stopped.historyMessage) isExecuting = false @@ -872,6 +882,17 @@ struct QueryEditorView: View { return } + // Another window may have begun a run with a `USE` while this one planned; nothing suspends from here to `track`. + guard movesDatabase || !coordinator.isDatabaseMoving else { + if holdsCatalog { appState.connectionManager.releaseCatalogConnections(for: connectionId) } + appError = ConnectionCoordinator.databaseMovingRefusal + isExecuting = false + completion.reopenColumnReads() + executionStartTime = nil + await appState.queryActivities.end(token: token, outcome: QueryExecutionOutcome.failed.activityOutcome) + return + } + let progressUpdater = startActivityProgressUpdater(token: token) await coordinator.track( @@ -884,9 +905,15 @@ struct QueryEditorView: View { progressUpdater.cancel() // Released before the change posts, so the reload it starts can open a catalog connection again. if holdsCatalog { appState.connectionManager.releaseCatalogConnections(for: connectionId) } - postCatalogChanges(on: session) - // Waits for a request Stop ended to return, which the run's end must not. - Task { await coordinator.followSessionDatabase() } + let move = postCatalogChanges(on: session) + let follow = Task { + await coordinator.followSessionPlacement(after: move) + if movesDatabase { coordinator.endDatabaseMove() } + } + // The follow waits for a statement Stop ended to return, which the run's end must not; Run stays off until the + // move lands. A plugin driver's read waits for its stopped request too. + let stopped = QueryExecutionOutcome(phase: viewModel.phase) == .stopped + if !stopped, !(session.driver is PluginBackedDriver) { await follow.value } let phase = viewModel.phase let outcome = QueryExecutionOutcome(phase: phase) @@ -926,17 +953,18 @@ struct QueryEditorView: View { // Every statement sent counts as run, a failed one's too: a missed reload leaves the lists naming what is gone. // They are read as sent, since a run splits the rest of its text again after a statement that changes how the // session reads literals. - private func postCatalogChanges(on session: ConnectionSession) { + private func postCatalogChanges(on session: ConnectionSession) -> ConnectionCoordinator.SessionMove { let statements = viewModel.sentStatements // A key or a collection a write made or removed is on the lists too; only a proven read leaves them as they are. guard databaseType.speaksSQL else { if statements.contains(where: { SQLWriteClassifier.isWriteQuery($0, databaseType: databaseType) }) { coordinator.noteCatalogChanged([.tables, .databases]) } - return + return ConnectionCoordinator.SessionMove() } + let sessionEffect = SessionLocalStatements.effect(of: statements, databaseType: databaseType) appState.catalogChanges.noteSessionEffect( - SessionLocalStatements.effect(of: statements, databaseType: databaseType), + sessionEffect, for: connectionId, driver: ObjectIdentifier(session.driver) ) @@ -948,6 +976,12 @@ struct QueryEditorView: View { // A commit shows the transaction's DDL to the catalog connection, a rollback takes it back from the session. if effect.endsTransaction { kinds.formUnion([.tables, .schemas, .databases]) } coordinator.noteCatalogChanged(kinds) + // A transaction's end takes back a `SET LOCAL` or a `SET` inside it, a function may set the search path, and a + // typed ROLLBACK of a held transaction also reaches the Roll Back reload. + return ConnectionCoordinator.SessionMove( + database: sessionEffect.usesDatabase, + schema: sessionEffect.leavesCatalog || effect.endsTransaction + ) } private func plan(_ text: String, on session: ConnectionSession) async -> QueryScript { @@ -973,14 +1007,13 @@ struct QueryEditorView: View { } private func recordHistory(query: String, outcome: QueryExecutionOutcome, errorMessage: String?) { - coordinator.addHistoryItem( - QueryHistoryItem( - query: query, - connectionId: connectionId, - wasSuccessful: outcome == .completed, - errorMessage: errorMessage - ) + let item = QueryHistoryItem( + query: query, + connectionId: connectionId, + wasSuccessful: outcome == .completed, + errorMessage: errorMessage ) + Task { await coordinator.addHistoryItem(item) } } // MARK: - Live Activity diff --git a/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift b/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift index e9d4fa1614..f034403e10 100644 --- a/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift +++ b/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift @@ -422,6 +422,7 @@ struct RowDetailView: View { } private func handleSave() async { + guard !refusesWhileDatabaseMoves() else { return } let success = await connectionCoordinator.track(failed: { _ in viewModel.operationError != nil }) { await viewModel.saveChanges() } @@ -437,6 +438,7 @@ struct RowDetailView: View { } private func executePendingSave() async { + guard !refusesWhileDatabaseMoves() else { return } let success = await connectionCoordinator.track(failed: { _ in viewModel.operationError != nil }) { await viewModel.executePendingSave() } @@ -447,6 +449,13 @@ struct RowDetailView: View { } } + private func refusesWhileDatabaseMoves() -> Bool { + guard let refusal = connectionCoordinator.databaseMoveRefusal else { return false } + viewModel.operationError = refusal + hapticError.toggle() + return true + } + // Names the cell rather than carrying its text, so the route stays cheap to compare. private struct FullValueRoute: Hashable { let row: Int diff --git a/apple/TableProMobile/TableProMobile/Views/TableListView.swift b/apple/TableProMobile/TableProMobile/Views/TableListView.swift index 21c06dbf9e..d22b0116c2 100644 --- a/apple/TableProMobile/TableProMobile/Views/TableListView.swift +++ b/apple/TableProMobile/TableProMobile/Views/TableListView.swift @@ -226,6 +226,11 @@ struct TableListView: View { // Another window can switch the shared session between the tap and the confirmation; the table named in the dialog // may then sit in another database or schema, so nothing runs. private func driver(for action: PendingTableAction) -> (any DatabaseDriver)? { + if let refusal = coordinator.databaseMoveRefusal { + errorMessage = refusal.message + showError = true + return nil + } guard action.placement == coordinator.tablePlacement, let driver = session?.driver else { errorMessage = String(localized: "The connection moved to another database or schema. Choose the table again.") showError = true diff --git a/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorCatalogTests.swift b/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorCatalogTests.swift index b8843230d4..5c5355b794 100644 --- a/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorCatalogTests.swift +++ b/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorCatalogTests.swift @@ -241,7 +241,7 @@ struct ConnectionCoordinatorCatalogTests { let stopped = Task { @MainActor in withUnsafeCurrentTask { $0?.cancel() } - await coordinator.followSessionDatabase() + await coordinator.followSessionPlacement(after: .init()) } await stopped.value @@ -267,7 +267,7 @@ struct ConnectionCoordinatorCatalogTests { let stopped = Task { try await session.fetchTables(schema: nil) } for await _ in entered { break } - let follow = Task { await coordinator.followSessionDatabase() } + let follow = Task { await coordinator.followSessionPlacement(after: .init()) } release.yield() _ = try await stopped.value await follow.value @@ -285,7 +285,7 @@ struct ConnectionCoordinatorCatalogTests { appState.setEditorHold(true, by: otherWindow, on: connection.id) session.used = "archive" - await coordinator.followSessionDatabase() + await coordinator.followSessionPlacement(after: .init()) #expect(coordinator.activeDatabase == "app_prod") #expect(session.used == "app_prod") @@ -322,6 +322,173 @@ struct ConnectionCoordinatorCatalogTests { #expect(session.switchedDatabases.isEmpty) } + @Test("A USE run in the Query tab moves the picker, the lists and the redial to the session's database") + func useMovesThePickerToTheSessionsDatabase() async { + let session = driver(tables: ["orders"]) + session.scriptedDatabases = ["app_prod", "app_staging"] + let coordinator = await connected(session) + session.scriptedSessionDatabase = "app_staging" + session.scriptedTables = [TableInfo(name: "orders"), TableInfo(name: "staging_only")] + #expect(coordinator.tableQualifier == "app_prod") + + await coordinator.followSessionPlacement(after: .init(database: true)) + + #expect(coordinator.activeDatabase == "app_staging") + #expect(names(coordinator) == ["orders", "staging_only"]) + #expect(appState.connectionManager.session(for: connection.id)?.activeDatabase == "app_staging") + #expect(coordinator.tablePlacement.database == "app_staging") + #expect(coordinator.tableQualifier == "app_staging") + #expect(!coordinator.showFailureAlert) + } + + @Test("A run that cannot have moved the session sends it no statement") + func runWithoutUseLeavesTheSessionAlone() async { + let session = driver(tables: ["orders"]) + let coordinator = await connected(session) + session.scriptedSessionDatabase = "app_staging" + + await coordinator.followSessionPlacement(after: .init()) + + #expect(session.sessionDatabaseReads == 0) + #expect(coordinator.activeDatabase == "app_prod") + } + + @Test("While this window holds an unsaved edit, a USE is undone so the edit saves where it was made") + func ownHeldEditUndoesTheUse() async { + let session = driver(tables: ["orders"]) + let coordinator = await connected(session) + coordinator.isHeldByEditor = true + session.scriptedSessionDatabase = "app_staging" + + await coordinator.followSessionPlacement(after: .init(database: true)) + + #expect(coordinator.activeDatabase == "app_prod") + #expect(session.switchedDatabases.last == "app_prod") + #expect(coordinator.failureAlertMessage == ConnectionCoordinator.editorHeldHereMessage) + coordinator.isHeldByEditor = false + } + + @Test("When the session cannot go back under another window's unsaved edit, the lists follow it and the edit keeps its database") + func failedMoveBackFollowsTheSession() async { + let session = driver(tables: ["orders"]) + let coordinator = await connected(session) + let editing = ConnectionCoordinator(connection: connection, appState: appState) + editing.isHeldByEditor = true + session.scriptedSessionDatabase = "app_staging" + session.refusedDatabases = ["app_prod"] + + await coordinator.followSessionPlacement(after: .init(database: true)) + + #expect(coordinator.activeDatabase == "app_staging") + #expect(coordinator.showFailureAlert) + #expect(editing.activeDatabase == "app_prod") + #expect(editing.tableQualifier == "app_prod") + editing.isHeldByEditor = false + } + + @Test("While a run with a USE is in flight, SQL Server writes in every window are refused and no window runs") + func useRunRefusesSQLServerWrites() async { + var mssql = connection + mssql.type = .mssql + factory.queue(driver(tables: ["orders"])) + let coordinator = ConnectionCoordinator(connection: mssql, appState: appState) + await coordinator.connect() + let otherWindow = ConnectionCoordinator(connection: mssql, appState: appState) + await otherWindow.connect() + + #expect(!coordinator.beginDatabaseMove(ifRunning: "SELECT * FROM orders")) + #expect(otherWindow.databaseMoveRefusal == nil) + + #expect(coordinator.beginDatabaseMove(ifRunning: "USE archive\nDELETE FROM orders")) + #expect(otherWindow.isDatabaseMoving) + #expect(otherWindow.databaseMoveRefusal != nil) + + coordinator.endDatabaseMove() + #expect(!otherWindow.isDatabaseMoving) + #expect(otherWindow.databaseMoveRefusal == nil) + } + + @Test("MySQL writes name their database, so a run with a USE holds only the Run button") + func useRunLeavesMySQLWritesAlone() async { + let coordinator = await connected(driver(tables: ["orders"])) + + #expect(coordinator.beginDatabaseMove(ifRunning: "USE app_staging")) + + #expect(coordinator.isDatabaseMoving) + #expect(coordinator.databaseMoveRefusal == nil) + coordinator.endDatabaseMove() + } + + @Test("A SQL Server session left in another database refuses writes made for the one the window shows") + func sqlServerSessionElsewhereRefusesWrites() async { + var mssql = connection + mssql.type = .mssql + let session = driver(tables: ["orders"]) + factory.queue(session) + let coordinator = ConnectionCoordinator(connection: mssql, appState: appState) + await coordinator.connect() + session.scriptedCurrentDatabase = "APP_PROD" + #expect(coordinator.databaseMoveRefusal == nil) + + session.scriptedCurrentDatabase = "archive" + + #expect(coordinator.databaseMoveRefusal != nil) + } + + @Test("A COMMIT that ends a SET LOCAL search_path moves the schema picker back") + func commitMovesTheSchemaPickerBack() async { + let session = driver(tables: ["orders"]) + session.scriptedSchemas = ["archive", "public"] + var postgres = connection + postgres.type = .postgresql + factory.queue(session) + let coordinator = ConnectionCoordinator(connection: postgres, appState: appState) + await coordinator.connect() + session.scriptedSessionSchema = "archive" + await coordinator.followSessionPlacement(after: .init(schema: true)) + #expect(coordinator.activeSchema == "archive") + + session.scriptedSessionSchema = "public" + await coordinator.followSessionPlacement(after: .init(schema: true)) + + #expect(coordinator.activeSchema == "public") + } + + @Test("A typed SET search_path moves the schema picker to where the session reads") + func setSearchPathMovesTheSchemaPicker() async { + let session = driver(tables: ["orders"]) + session.scriptedSchemas = ["archive", "public"] + var postgres = connection + postgres.type = .postgresql + factory.queue(session) + let coordinator = ConnectionCoordinator(connection: postgres, appState: appState) + await coordinator.connect() + #expect(coordinator.activeSchema == "public") + session.scriptedSessionSchema = "archive" + + await coordinator.followSessionPlacement(after: .init(schema: true)) + + #expect(coordinator.activeSchema == "archive") + } + + @Test("A Roll Back that undoes the picker's schema switch moves the picker back") + func rollBackMovesTheSchemaPickerBack() async { + let session = driver(tables: ["orders"]) + session.scriptedSchemas = ["archive", "public"] + var postgres = connection + postgres.type = .postgresql + factory.queue(session) + let coordinator = ConnectionCoordinator(connection: postgres, appState: appState) + await coordinator.connect() + await coordinator.switchSchema(to: "archive") + #expect(coordinator.activeSchema == "archive") + session.scriptedSessionSchema = "public" + + await coordinator.reloadAfterRollBack() + + #expect(coordinator.activeSchema == "public") + } + private func usedDatabaseDriver(_ plugin: StubPluginDriver) -> UsedDatabaseDriver { UsedDatabaseDriver( plugin: plugin, dialedHosts: [], readsOnly: { _ in true }, diff --git a/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorHistoryTests.swift b/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorHistoryTests.swift index 3e20144874..a0599724f2 100644 --- a/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorHistoryTests.swift +++ b/apple/TableProMobile/TableProMobileTests/ConnectionCoordinatorHistoryTests.swift @@ -16,29 +16,29 @@ struct ConnectionCoordinatorHistoryTests { #expect(appState.addConnection(connection)) } - private func makeCoordinator() -> ConnectionCoordinator { + private func makeCoordinator() async -> ConnectionCoordinator { let coordinator = ConnectionCoordinator(connection: connection, appState: appState) - coordinator.loadHistory() + await coordinator.loadHistory() return coordinator } @Test("Running the same query twice in a row lists it once, as the store keeps it") - func repeatedQueryIsListedOnce() { - let coordinator = makeCoordinator() + func repeatedQueryIsListedOnce() async { + let coordinator = await makeCoordinator() - coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) - coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) #expect(coordinator.queryHistory.count == 1) #expect(coordinator.queryHistory.map(\.id) == appState.queryHistory.load(for: connection.id).map(\.id)) } @Test("The same query failing after it succeeded is listed twice") - func differentOutcomeIsListedAgain() { - let coordinator = makeCoordinator() + func differentOutcomeIsListedAgain() async { + let coordinator = await makeCoordinator() - coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) - coordinator.addHistoryItem( + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) + await coordinator.addHistoryItem( QueryHistoryItem(query: "SELECT 1", connectionId: connection.id, wasSuccessful: false, errorMessage: "gone") ) @@ -46,30 +46,57 @@ struct ConnectionCoordinatorHistoryTests { } @Test("A query past the store's cap drops the oldest entry from the list too") - func listFollowsTheStoreCap() { + func listFollowsTheStoreCap() async { for index in 0..<200 { appState.queryHistory.save(QueryHistoryItem(query: "SELECT \(index)", connectionId: connection.id)) } - let coordinator = makeCoordinator() + let coordinator = await makeCoordinator() #expect(coordinator.queryHistory.count == 200) - coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 200", connectionId: connection.id)) + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 200", connectionId: connection.id)) #expect(coordinator.queryHistory.count == 200) #expect(coordinator.queryHistory.first?.query == "SELECT 1") #expect(coordinator.queryHistory.last?.query == "SELECT 200") } + @Test("A delete lists what the store holds after it, a run another window saved meanwhile included") + func deleteListsRunsSavedMeanwhile() async throws { + let coordinator = await makeCoordinator() + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) + let first = try #require(coordinator.queryHistory.first?.id) + appState.queryHistory.save(QueryHistoryItem(query: "SELECT 2", connectionId: connection.id)) + + await coordinator.deleteHistoryItem(first).value + + #expect(coordinator.queryHistory.map(\.query) == ["SELECT 2"]) + #expect(appState.queryHistory.load(for: connection.id).map(\.query) == ["SELECT 2"]) + } + + @Test("Clearing empties the list and the store for this connection only") + func clearEmptiesThisConnection() async { + let other = UUID() + appState.queryHistory.save(QueryHistoryItem(query: "SELECT 0", connectionId: other)) + let coordinator = await makeCoordinator() + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) + + await coordinator.clearHistory().value + + #expect(coordinator.queryHistory.isEmpty) + #expect(appState.queryHistory.load(for: connection.id).isEmpty) + #expect(appState.queryHistory.load(for: other).map(\.query) == ["SELECT 0"]) + } + @Test("A history file that cannot be read or written leaves the listed history in place") - func unreadableStoreKeepsTheList() throws { + func unreadableStoreKeepsTheList() async throws { appState.queryHistory.save(QueryHistoryItem(query: "SELECT 1", connectionId: connection.id)) - let coordinator = makeCoordinator() + let coordinator = await makeCoordinator() let historyFile = fixture.libraryDirectory.appendingPathComponent("query-history.json") try FileManager.default.removeItem(at: historyFile) try FileManager.default.createDirectory(at: historyFile, withIntermediateDirectories: false) try Data("locked".utf8).write(to: historyFile.appendingPathComponent("entry")) - coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 2", connectionId: connection.id)) + await coordinator.addHistoryItem(QueryHistoryItem(query: "SELECT 2", connectionId: connection.id)) #expect(coordinator.queryHistory.map(\.query) == ["SELECT 1"]) } diff --git a/apple/TableProMobile/TableProMobileTests/DataBrowserViewModelTests.swift b/apple/TableProMobile/TableProMobileTests/DataBrowserViewModelTests.swift index 8c3f42995f..c145e8f609 100644 --- a/apple/TableProMobile/TableProMobileTests/DataBrowserViewModelTests.swift +++ b/apple/TableProMobile/TableProMobileTests/DataBrowserViewModelTests.swift @@ -469,6 +469,40 @@ struct DataBrowserViewModelTests { #expect(driver.executedQueries.contains(where: { $0.uppercased().hasPrefix("DELETE") })) } + @Test("A delete confirmed after another window moved the browser to another schema is refused") + func deleteRaisedInAnotherSchemaIsRefused() { + let driver = MockDatabaseDriver() + let session = makeSession(driver: driver) + let vm = DataBrowserViewModel() + vm.attach(session: session, table: TableInfo(name: "users"), databaseType: .mssql, host: "localhost", schema: "dbo") + let raised = vm.rowSource + #expect(!vm.refusesDelete(raisedOn: raised)) + #expect(vm.operationError == nil) + + vm.attach(session: session, table: TableInfo(name: "users"), databaseType: .mssql, host: "localhost", schema: "archive") + + #expect(vm.refusesDelete(raisedOn: raised)) + #expect(vm.operationError != nil) + #expect(driver.executedQueries.isEmpty) + } + + @Test("A delete confirmed after a redial handed the browser a new session is refused") + func deleteRaisedOnAnOlderSessionIsRefused() { + let vm = DataBrowserViewModel() + vm.attach( + session: makeSession(driver: MockDatabaseDriver()), table: TableInfo(name: "users"), + databaseType: .postgresql, host: "localhost", schema: "public" + ) + let raised = vm.rowSource + + vm.attach( + session: makeSession(driver: MockDatabaseDriver()), table: TableInfo(name: "users"), + databaseType: .postgresql, host: "localhost", schema: "public" + ) + + #expect(vm.refusesDelete(raisedOn: raised)) + } + @Test("A binary, NULL or ref-less cut key cell gives no key, and a cut one with a ref gives the whole key") func nonTextKeyGivesNoKey() async { let columns = [ @@ -872,6 +906,81 @@ struct DataBrowserViewModelTests { return QueryResult(columns: makeColumns(), rows: rows, rowsAffected: 0, executionTime: 0) } + private func firstPageQuery( + _ type: DatabaseType, + columns: [ColumnInfo], + sort: SortState = SortState() + ) async -> String? { + let driver = MockDatabaseDriver() + driver.scriptedColumns = columns + let vm = DataBrowserViewModel() + vm.attach(session: makeSession(driver: driver), table: TableInfo(name: "events"), databaseType: type, host: "localhost") + vm.sortState = sort + await vm.load(isInitial: true) + // The page size is the user's default, so the expected text names it as `{limit}`. + return driver.executedQueries.first?.replacingOccurrences(of: "LIMIT \(vm.pagination.pageSize) ", with: "LIMIT {limit} ") + .replacingOccurrences(of: "NEXT \(vm.pagination.pageSize) ROWS", with: "NEXT {limit} ROWS") + } + + private var compositeKey: [ColumnInfo] { + [ + ColumnInfo(name: "tenant", typeName: "INT", isPrimaryKey: true, ordinalPosition: 0), + ColumnInfo(name: "id", typeName: "INT", isPrimaryKey: true, ordinalPosition: 1), + ColumnInfo(name: "status", typeName: "TEXT", ordinalPosition: 2) + ] + } + + @Test("A PostgreSQL page orders by every key column, so paging neither repeats nor skips rows") + func postgresPageOrdersByTheWholeKey() async { + let query = await firstPageQuery(.postgresql, columns: compositeKey) + #expect(query == #"SELECT * FROM "events" ORDER BY "tenant" ASC, "id" ASC LIMIT {limit} OFFSET 0"#) + } + + @Test("A ClickHouse page orders by its key columns") + func clickHousePageOrdersByTheKey() async { + let columns = [ + ColumnInfo(name: "day", typeName: "Date", isPrimaryKey: true, ordinalPosition: 0), + ColumnInfo(name: "hits", typeName: "UInt64", ordinalPosition: 1) + ] + let query = await firstPageQuery(.clickhouse, columns: columns) + #expect(query == "SELECT * FROM `events` ORDER BY `day` ASC LIMIT {limit} OFFSET 0") + } + + @Test("A PostgreSQL table with no key pages as before") + func keylessPostgresPageHasNoOrder() async { + let columns = [ColumnInfo(name: "note", typeName: "TEXT", ordinalPosition: 0)] + let query = await firstPageQuery(.postgresql, columns: columns) + #expect(query == #"SELECT * FROM "events" LIMIT {limit} OFFSET 0"#) + } + + @Test("The user's sort comes first and the key breaks its ties") + func userSortKeepsTheKeyAsTiebreak() async { + let sort = SortState(columns: [SortColumn(name: "status", ascending: false)]) + let query = await firstPageQuery(.postgresql, columns: compositeKey, sort: sort) + #expect(query == #"SELECT * FROM "events" ORDER BY "status" DESC, "tenant" ASC, "id" ASC LIMIT {limit} OFFSET 0"#) + } + + @Test("A key column the user sorts by is not repeated") + func userSortOnAKeyColumnIsNotRepeated() async { + let sort = SortState(columns: [SortColumn(name: "id", ascending: false)]) + let query = await firstPageQuery(.postgresql, columns: compositeKey, sort: sort) + #expect(query == #"SELECT * FROM "events" ORDER BY "id" DESC, "tenant" ASC LIMIT {limit} OFFSET 0"#) + } + + @Test("SQL Server orders by the whole key, and a keyless table by its first column") + func sqlServerOrdersByTheWholeKey() async { + let keyed = await firstPageQuery(.mssql, columns: compositeKey) + #expect(keyed == "SELECT * FROM [events] ORDER BY [tenant] ASC, [id] ASC OFFSET 0 ROWS FETCH NEXT {limit} ROWS ONLY") + let keyless = await firstPageQuery(.mssql, columns: [ColumnInfo(name: "note", typeName: "NVARCHAR", ordinalPosition: 0)]) + #expect(keyless == "SELECT * FROM [events] ORDER BY [note] ASC OFFSET 0 ROWS FETCH NEXT {limit} ROWS ONLY") + } + + @Test("MySQL and Redshift pages keep their scan order") + func scanOrderedEnginesAddNoOrder() async { + #expect(await firstPageQuery(.mysql, columns: compositeKey) == "SELECT * FROM `events` LIMIT {limit} OFFSET 0") + #expect(await firstPageQuery(.redshift, columns: compositeKey) == #"SELECT * FROM "events" LIMIT {limit} OFFSET 0"#) + } + @Test("A page trimmed under memory pressure labels the rows it kept, not the ones it dropped") func trimmedPageLabelsTheRowsItKept() async { let driver = MockDatabaseDriver() diff --git a/apple/TableProMobile/TableProMobileTests/Helpers/ClipboardExporterFidelityTests.swift b/apple/TableProMobile/TableProMobileTests/Helpers/ClipboardExporterFidelityTests.swift index fe8b181201..0f68fa77de 100644 --- a/apple/TableProMobile/TableProMobileTests/Helpers/ClipboardExporterFidelityTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Helpers/ClipboardExporterFidelityTests.swift @@ -76,12 +76,54 @@ struct ClipboardExporterFidelityTests { } } - @Test("real numbers are still emitted unquoted") + @Test("numbers in a numeric column are emitted unquoted") func realNumbersStayNumbers() { - #expect(json(["1", "0", "x"]).contains("\"zip\": 0")) - #expect(json(["1", "-12", "x"]).contains("\"zip\": -12")) - #expect(json(["1", "1.5", "x"]).contains("\"zip\": 1.5")) - #expect(json(["1", "1e10", "x"]).contains("\"zip\": 1e10")) + #expect(json(["0", "1", "x"]).contains("\"id\": 0")) + #expect(json(["-12", "1", "x"]).contains("\"id\": -12")) + #expect(json(["1.5", "1", "x"]).contains("\"id\": 1.5")) + #expect(json(["1e10", "1", "x"]).contains("\"id\": 1e10")) + } + + @Test("text that reads like a number or a boolean stays a string in a text column") + func textColumnsStayStrings() throws { + for value in ["1e10", "12345678901234567890", "0", "true", "false"] { + let text = json(["1", value, value]) + #expect(text.contains("\"zip\": \"\(value)\""), "\(value) should stay quoted") + #expect(text.contains("\"note\": \"\(value)\""), "\(value) should stay quoted") + _ = try JSONSerialization.jsonObject(with: try #require(text.data(using: .utf8))) + } + } + + @Test("each column's declared type picks the JSON type") + func declaredTypePicksTheJSONType() throws { + func value(_ text: String, typeName: String) throws -> String { + let output = ClipboardExporter.exportRow( + columns: [ColumnInfo(name: "v", typeName: typeName, ordinalPosition: 0)], row: [text], format: .json, + tableName: "t", databaseType: .postgresql, driver: nil + ) + _ = try JSONSerialization.jsonObject(with: try #require(output.data(using: .utf8))) + let line = try #require(output.split(separator: "\n").first { $0.contains("\"v\"") }) + return String(line.drop { $0 != ":" }.dropFirst(2)) + } + #expect(try value("t", typeName: "bool") == "true") + #expect(try value("f", typeName: "bool") == "false") + #expect(try value("TRUE", typeName: "BOOLEAN") == "true") + #expect(try value("false", typeName: "Nullable(Bool)") == "false") + #expect(try value("yes", typeName: "bool") == "\"yes\"") + #expect(try value("42", typeName: "int4") == "42") + #expect(try value("12.50", typeName: "numeric(10,2)") == "12.50") + #expect(try value("-1.5e3", typeName: "Float64") == "-1.5e3") + #expect(try value("18446744073709551615", typeName: "UInt64") == "18446744073709551615") + #expect(try value("1", typeName: "bit") == "1") + #expect(try value("NaN", typeName: "float8") == "\"NaN\"") + #expect(try value("$5.00", typeName: "money") == "\"$5.00\"") + #expect(try value("t", typeName: "text") == "\"t\"") + #expect(try value("1", typeName: "BOOLEAN") == "true") + #expect(try value("0", typeName: "BOOLEAN") == "false") + // SQLite reports no type for an expression such as count(*), so its value decides. + #expect(try value("42", typeName: "") == "42") + #expect(try value("true", typeName: "") == "true") + #expect(try value("01234", typeName: "") == "\"01234\"") } @Test("a NULL is emitted as JSON null") diff --git a/apple/TableProMobile/TableProMobileTests/Helpers/LiteralInputTraitsTests.swift b/apple/TableProMobile/TableProMobileTests/Helpers/LiteralInputTraitsTests.swift index 4094fa3120..9ec1769267 100644 --- a/apple/TableProMobile/TableProMobileTests/Helpers/LiteralInputTraitsTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Helpers/LiteralInputTraitsTests.swift @@ -40,6 +40,20 @@ struct LiteralInputTraitsTests { #expect(textView.writingToolsBehavior == UIWritingToolsBehavior.none) } + @Test("The table search types what the keyboard sends, so a name with an apostrophe still matches") + func searchFieldTraits() { + let bar = UISearchBar() + + LiteralSearchField.configure(bar) + + let field = bar.searchTextField + #expect(field.smartQuotesType == .no) + #expect(field.smartDashesType == .no) + #expect(field.autocorrectionType == .no) + #expect(field.autocapitalizationType == UITextAutocapitalizationType.none) + #expect(bar.returnKeyType == .search) + } + @Test("The traits leave the keyboard type the field asked for") func keyboardTypeKept() { let field = UITextField() diff --git a/apple/TableProMobile/TableProMobileTests/Helpers/SessionLocalStatementsTests.swift b/apple/TableProMobile/TableProMobileTests/Helpers/SessionLocalStatementsTests.swift index f227485b50..6936bedadb 100644 --- a/apple/TableProMobile/TableProMobileTests/Helpers/SessionLocalStatementsTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Helpers/SessionLocalStatementsTests.swift @@ -70,6 +70,21 @@ struct SessionLocalStatementsTests { ) } + @Test("Only a USE moves the session's database, so only it makes the app read where the session went") + func onlyUseMovesTheDatabase() { + #expect(SessionLocalStatements.effect(of: ["USE archive"], databaseType: .mysql).usesDatabase) + #expect(SessionLocalStatements.effect(of: ["/*!40000 USE archive */"], databaseType: .mysql).usesDatabase) + #expect( + SessionLocalStatements.effect(of: ["SELECT 1\nUSE [archive]\nSELECT 2"], databaseType: .mssql).usesDatabase + ) + for statement in ["CALL make_scratch()", "EXECUTE stmt", "SET ROLE admin", "/*!40101 SET NAMES utf8 */"] { + let effect = SessionLocalStatements.effect(of: [statement], databaseType: .mysql) + #expect(effect.leavesCatalog, "\(statement)") + #expect(!effect.usesDatabase, "\(statement)") + } + #expect(!SessionLocalStatements.effect(of: ["SELECT * FROM t USE INDEX (i)"], databaseType: .mysql).usesDatabase) + } + @Test("A procedure call, dynamic SQL or an anonymous block may make a table only the session sees") func opaqueStatementsLeaveTheCatalog() { #expect(SessionLocalStatements.effect(of: ["CALL make_scratch()"], databaseType: .mysql).leavesCatalog) diff --git a/apple/TableProMobile/TableProMobileTests/Mocks/MockDatabaseDriver.swift b/apple/TableProMobile/TableProMobileTests/Mocks/MockDatabaseDriver.swift index 5718af7b1f..a6fa48dd8f 100644 --- a/apple/TableProMobile/TableProMobileTests/Mocks/MockDatabaseDriver.swift +++ b/apple/TableProMobile/TableProMobileTests/Mocks/MockDatabaseDriver.swift @@ -3,6 +3,7 @@ import TableProDatabase import TableProModels import TableProPluginKit import TableProSQLGrammar +@testable import TableProMobile final class MockDatabaseDriver: DatabaseDriver, @unchecked Sendable { enum MockError: Error { case scripted } @@ -16,6 +17,10 @@ final class MockDatabaseDriver: DatabaseDriver, @unchecked Sendable { var scriptedDatabases: [String] = [] // The database the driver says it is in, which may be named differently from the one the connection stores. var scriptedCurrentDatabase: String? + // What `SELECT DATABASE()` and `current_schema()` answer; nil keeps the driver where it is. + var scriptedSessionDatabase: String? + var scriptedSessionSchema: String? + private(set) var sessionDatabaseReads = 0 var scriptedSchemas: [String] = [] var scriptedTransactionState: DriverTransactionState = .unknown // Answered in order, one per call, before falling back to `scriptedTransactionState`. @@ -115,8 +120,11 @@ final class MockDatabaseDriver: DatabaseDriver, @unchecked Sendable { func fetchSchemas() async throws -> [String] { scriptedSchemas } var currentDatabase: String? { scriptedCurrentDatabase } + var refusedDatabases: Set = [] + func switchDatabase(to name: String) async throws { if let switchDatabaseError { throw switchDatabaseError } + if refusedDatabases.contains(name) { throw MockError.scripted } switchedDatabases.append(name) } func switchSchema(to name: String) async throws { @@ -179,3 +187,17 @@ final class MockSecureStore: SecureStore, @unchecked Sendable { storage[key] = value } } + +extension MockDatabaseDriver: SessionDatabaseReporting, SessionSchemaReporting { + var reportsDatabaseWithoutStatement: Bool { false } + + func sessionDatabase() async throws -> String? { + sessionDatabaseReads += 1 + return scriptedSessionDatabase + } + + func settleCurrentSchema() async { + guard let scriptedSessionSchema else { return } + currentSchema = scriptedSessionSchema + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Platform/SessionTransactionMonitorTests.swift b/apple/TableProMobile/TableProMobileTests/Platform/SessionTransactionMonitorTests.swift index 5815991060..be0bde871b 100644 --- a/apple/TableProMobile/TableProMobileTests/Platform/SessionTransactionMonitorTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Platform/SessionTransactionMonitorTests.swift @@ -1,6 +1,7 @@ import Foundation import TableProDatabase @testable import TableProMobile +import TableProTestSupport import Testing @MainActor @@ -29,6 +30,57 @@ struct SessionTransactionMonitorTests { return driver } + @Test("A run that moves the database waits for a write already on the session") + func moveWaitsForAWriteInFlight() async throws { + attach() + await monitor.statementsFinished(for: id) + let log = EventLog() + let gate = TestGate() + let write = Task { + await monitor.track(id) { + await gate.enter() + log.events.append("write") + } + } + await gate.waitUntilEntered() + let run = Task { + log.events.append("waiting") + await monitor.statementsFinished(for: id) + log.events.append("run") + } + try await waitUntil { log.events.contains("waiting") } + + await gate.open() + await write.value + await run.value + + #expect(log.events == ["waiting", "write", "run"]) + } + + @Test("Stop ends the wait for a write that is still running") + func stopEndsTheWait() async throws { + attach() + let log = EventLog() + let gate = TestGate() + let write = Task { await monitor.track(id) { await gate.enter() } } + await gate.waitUntilEntered() + let run = Task { + log.events.append("waiting") + await monitor.statementsFinished(for: id) + log.events.append("run") + } + try await waitUntil { log.events.contains("waiting") } + + run.cancel() + await run.value + + #expect(log.events == ["waiting", "run"]) + #expect(monitor.isRunningStatements(id)) + await gate.open() + await write.value + #expect(!monitor.isRunningStatements(id)) + } + @Test("A run that leaves a transaction open shows it, explicit or implicit") func runLeavesTheTransactionOpen() async { let driver = attach(.explicitTransaction) @@ -332,3 +384,8 @@ struct SessionTransactionMonitorTests { #expect(serverState == .idle) } } + +@MainActor +private final class EventLog { + var events: [String] = [] +} diff --git a/apple/TableProMobile/TableProMobileTests/QueryHistoryStorageTests.swift b/apple/TableProMobile/TableProMobileTests/QueryHistoryStorageTests.swift new file mode 100644 index 0000000000..d35d206be2 --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/QueryHistoryStorageTests.swift @@ -0,0 +1,97 @@ +import Foundation +import Testing +@testable import TableProMobile + +struct QueryHistoryStorageTests { + private let directory: URL + + init() throws { + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent("ios-history-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + private var historyURL: URL { + directory.appendingPathComponent("query-history.json") + } + + @Test("A recorded run returns its connection's list, so the window needs no second read") + func recordReturnsTheConnectionsList() throws { + let storage = QueryHistoryStorage(directory: directory) + let mine = UUID() + storage.save(QueryHistoryItem(query: "SELECT 1", connectionId: mine)) + storage.save(QueryHistoryItem(query: "SELECT 2", connectionId: UUID())) + + let listed = try #require(storage.record(QueryHistoryItem(query: "SELECT 3", connectionId: mine))) + + #expect(listed.items.map(\.query) == ["SELECT 1", "SELECT 3"]) + #expect(listed.generation == storage.generation) + } + + @Test("The same run twice in a row records nothing the second time") + func duplicateRecordsNothing() { + let storage = QueryHistoryStorage(directory: directory) + let connectionId = UUID() + #expect(storage.record(QueryHistoryItem(query: "SELECT 1", connectionId: connectionId)) != nil) + + #expect(storage.record(QueryHistoryItem(query: "SELECT 1", connectionId: connectionId)) == nil) + } + + @Test("Text past the budget drops the oldest entries whole, and the newest entry always stays") + func byteBudgetDropsTheOldestWhole() { + let connectionId = UUID() + let half = String(repeating: "x", count: QueryHistoryStorage.maxTextBytes / 2) + let items = [ + QueryHistoryItem(query: "SELECT 1", connectionId: connectionId), + QueryHistoryItem(query: half, connectionId: connectionId), + QueryHistoryItem(query: half, connectionId: connectionId), + ] + + let kept = QueryHistoryStorage.withinBudget(items) + #expect(kept.map(\.query.utf8.count) == [half.utf8.count, half.utf8.count]) + + let huge = String(repeating: "y", count: QueryHistoryStorage.maxTextBytes + 1) + let alone = QueryHistoryStorage.withinBudget(items + [QueryHistoryItem(query: huge, connectionId: connectionId)]) + #expect(alone.map(\.query) == [huge]) + } + + @Test("At most 200 entries are kept") + func entryCapStillHolds() { + let connectionId = UUID() + let items = (0..<250).map { QueryHistoryItem(query: "SELECT \($0)", connectionId: connectionId) } + + let kept = QueryHistoryStorage.withinBudget(items) + + #expect(kept.count == 200) + #expect(kept.first?.query == "SELECT 50") + #expect(kept.last?.query == "SELECT 249") + } + + @Test("A write that fails leaves the listed history as the file holds it") + func failedWriteKeepsTheList() throws { + let storage = QueryHistoryStorage(directory: directory) + #expect(storage.save(QueryHistoryItem(query: "SELECT 1", connectionId: UUID()))) + let generation = storage.generation + try FileManager.default.removeItem(at: historyURL) + try FileManager.default.createDirectory(at: historyURL, withIntermediateDirectories: false) + + #expect(!storage.save(QueryHistoryItem(query: "SELECT 2", connectionId: UUID()))) + + #expect(storage.loadAll().map(\.query) == ["SELECT 1"]) + #expect(storage.generation == generation) + } + + @Test("The file follows memory, so the next launch reads what this one recorded") + func fileFollowsMemory() { + let first = QueryHistoryStorage(directory: directory) + let connectionId = UUID() + first.save(QueryHistoryItem(query: "SELECT 1", connectionId: connectionId)) + first.save(QueryHistoryItem(query: "SELECT 2", connectionId: connectionId)) + first.delete(first.loadAll()[0].id) + + let relaunched = QueryHistoryStorage(directory: directory) + + #expect(relaunched.load(for: connectionId).map(\.query) == ["SELECT 2"]) + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Security/CertificateMaterializerTests.swift b/apple/TableProMobile/TableProMobileTests/Security/CertificateMaterializerTests.swift new file mode 100644 index 0000000000..3219b7c7a7 --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Security/CertificateMaterializerTests.swift @@ -0,0 +1,81 @@ +import Foundation +@testable import TableProMobile +import TableProDatabase +import Testing + +struct CertificateMaterializerTests { + private let root: URL + private let certificates = InMemoryCertificateStore() + + init() throws { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent("ios-certificates-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + private var materializer: CertificateMaterializer { + CertificateMaterializer(store: certificates, root: root) + } + + private func folder(_ connectionId: UUID) -> URL { + root.appendingPathComponent(connectionId.uuidString, isDirectory: true) + } + + private func exists(_ url: URL) -> Bool { + FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) + } + + @Test("Deleting a connection removes the client key a connect wrote to disk") + func deleteRemovesTheKeyFile() throws { + let connectionId = UUID() + try certificates.store("key", role: .clientKey, for: connectionId) + let written = try #require(try materializer.materialize(for: connectionId).clientKeyPath) + #expect(exists(URL(filePath: written))) + + let secrets = ConnectionSecrets( + secureStore: MockSecureStore(), + certificateStore: certificates, + bookmarkStore: FileBookmarkStore(suiteName: "com.TablePro.tests.CertificateMaterializer.\(UUID().uuidString)"), + materializer: materializer + ) + secrets.delete(for: connectionId) + + #expect(!exists(URL(filePath: written))) + #expect(!exists(folder(connectionId))) + } + + @Test("A certificate removed from the connection loses its file on the next connect") + func removedRoleLosesItsFile() throws { + let connectionId = UUID() + try certificates.store("ca", role: .certificateAuthority, for: connectionId) + try certificates.store("key", role: .clientKey, for: connectionId) + let first = try materializer.materialize(for: connectionId) + let keyPath = try #require(first.clientKeyPath) + + certificates.delete(role: .clientKey, for: connectionId) + let second = try materializer.materialize(for: connectionId) + + #expect(second.clientKeyPath == nil) + #expect(second.caCertificatePath != nil) + #expect(!exists(URL(filePath: keyPath))) + } + + @Test("The launch sweep removes the folders of connections that are gone and keeps the rest") + func sweepKeepsKnownConnections() throws { + let kept = UUID() + let gone = UUID() + for connectionId in [kept, gone] { + try certificates.store("key", role: .clientKey, for: connectionId) + _ = try materializer.materialize(for: connectionId) + } + let unrelated = root.appendingPathComponent("not-a-connection", isDirectory: true) + try FileManager.default.createDirectory(at: unrelated, withIntermediateDirectories: true) + + materializer.releaseAll(except: [kept]) + + #expect(exists(folder(kept))) + #expect(!exists(folder(gone))) + #expect(exists(unrelated)) + } +} diff --git a/apple/changelog.d/4215.fixed.1.md b/apple/changelog.d/4215.fixed.1.md new file mode 100644 index 0000000000..853119454b --- /dev/null +++ b/apple/changelog.d/4215.fixed.1.md @@ -0,0 +1 @@ +On iOS, a PostgreSQL Roll Back or a typed SET search_path left the schema menu on a schema the session had left. diff --git a/apple/changelog.d/4215.fixed.2.md b/apple/changelog.d/4215.fixed.2.md new file mode 100644 index 0000000000..118102133a --- /dev/null +++ b/apple/changelog.d/4215.fixed.2.md @@ -0,0 +1 @@ +Paging an iOS PostgreSQL or ClickHouse table without a sort repeated and skipped rows. diff --git a/apple/changelog.d/4215.fixed.3.md b/apple/changelog.d/4215.fixed.3.md new file mode 100644 index 0000000000..7874f9d633 --- /dev/null +++ b/apple/changelog.d/4215.fixed.3.md @@ -0,0 +1 @@ +Copying rows as JSON on iOS turned text that looked like a number or true and false into numbers and booleans. diff --git a/apple/changelog.d/4215.fixed.4.md b/apple/changelog.d/4215.fixed.4.md new file mode 100644 index 0000000000..48c210f1ff --- /dev/null +++ b/apple/changelog.d/4215.fixed.4.md @@ -0,0 +1 @@ +Searching an iOS table for a name with an apostrophe found nothing with Smart Punctuation on. diff --git a/apple/changelog.d/4215.fixed.5.md b/apple/changelog.d/4215.fixed.5.md new file mode 100644 index 0000000000..6299555e57 --- /dev/null +++ b/apple/changelog.d/4215.fixed.5.md @@ -0,0 +1 @@ +Each query run on iOS paused the app while it reread and rewrote the whole query history. diff --git a/apple/changelog.d/4215.fixed.6.md b/apple/changelog.d/4215.fixed.6.md new file mode 100644 index 0000000000..2550548b61 --- /dev/null +++ b/apple/changelog.d/4215.fixed.6.md @@ -0,0 +1 @@ +On iPad, a row delete confirmed after another window switched schema deleted the same key in that schema. diff --git a/apple/changelog.d/4215.fixed.md b/apple/changelog.d/4215.fixed.md new file mode 100644 index 0000000000..12697fa658 --- /dev/null +++ b/apple/changelog.d/4215.fixed.md @@ -0,0 +1 @@ +A USE run in the iOS Query tab moved where Tables tab edits, deletes, truncates and drops landed. diff --git a/apple/changelog.d/4215.security.md b/apple/changelog.d/4215.security.md new file mode 100644 index 0000000000..1e93f7c022 --- /dev/null +++ b/apple/changelog.d/4215.security.md @@ -0,0 +1 @@ +Deleting a connection on iOS left its decrypted client private key in a file on the device.