Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ public protocol DatabaseDriver: AnyObject, Sendable {
func fetchForeignKeys(table: String, schema: String?) async throws -> [ForeignKeyInfo]
func fetchDatabases() async throws -> [String]

// The table in `database`, for an engine that names the database beside the schema (SQL Server's
// `[db].[schema].[table]`), so the read never follows a `USE` the session ran. Any other engine reads as above.
func fetchColumns(table: String, schema: String?, database: String?) async throws -> [ColumnInfo]
func fetchIndexes(table: String, schema: String?, database: String?) async throws -> [IndexInfo]
func fetchForeignKeys(table: String, schema: String?, database: String?) async throws -> [ForeignKeyInfo]

// Runs a statement sent with `StreamOptions.enforcesReadOnly` in the engine's read-only mode, or refuses it.
var enforcesReadOnlyMode: Bool { get }
// Whether the mode can run now: its own transaction would end a transaction or a table lock the session holds.
func entersReadOnlyMode() async -> Bool

func switchDatabase(to name: String) async throws
var supportsSchemas: Bool { get }
func switchSchema(to name: String) async throws
Expand Down Expand Up @@ -58,6 +69,25 @@ public extension DatabaseDriver {

func sessionLexicalFacts() async -> SQLSessionLexicalFacts? { nil }

func fetchColumns(table: String, schema: String?, database: String?) async throws -> [ColumnInfo] {
try await fetchColumns(table: table, schema: schema)
}

func fetchIndexes(table: String, schema: String?, database: String?) async throws -> [IndexInfo] {
try await fetchIndexes(table: table, schema: schema)
}

func fetchForeignKeys(table: String, schema: String?, database: String?) async throws -> [ForeignKeyInfo] {
try await fetchForeignKeys(table: table, schema: schema)
}

var enforcesReadOnlyMode: Bool { false }

func entersReadOnlyMode() async -> Bool {
guard enforcesReadOnlyMode else { return false }
return await sessionTransactionState() == .idle
}

func beginTransaction(mode: PluginTransactionAccessMode) async throws {
try await beginTransaction()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,24 @@ public struct StreamOptions: Sendable {
public let lazyContext: LazyContext?
// Long text with no ref stays whole while this admits it; nil cuts every long value.
public var textBudget: TextBudget?
// Safe Mode is Read-Only. A driver whose `enforcesReadOnlyMode` is true runs the statement in the engine's
// read-only mode or refuses it; any other driver runs it as it is.
public var enforcesReadOnly: Bool

public init(
textTruncationBytes: Int = Cell.previewByteLimit,
inlineBinary: Bool = false,
maxRows: Int = 100_000,
lazyContext: LazyContext? = nil,
textBudget: TextBudget? = nil
textBudget: TextBudget? = nil,
enforcesReadOnly: Bool = false
) {
self.textTruncationBytes = textTruncationBytes
self.inlineBinary = inlineBinary
self.maxRows = maxRows
self.lazyContext = lazyContext
self.textBudget = textBudget
self.enforcesReadOnly = enforcesReadOnly
}

public static let `default` = StreamOptions()
Expand Down
2 changes: 1 addition & 1 deletion apple/Plugins/MySQLDriverPlugin/MySQLLexicalFeatures.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import TableProPluginKit
///
/// The app's curated table is the authority for its gates; these are the same facts, held here because a plugin
/// cannot link the app's package, and `SQLLexicalFeatureMappingTests` holds the two equal.
enum MySQLLexicalFeatures {
nonisolated enum MySQLLexicalFeatures {
/// MySQL 8.4.11 and MariaDB 11.8.9, measured.
static let mySQL: SQLLexicalFeatures = [
.backslashEscapesInSingleQuotes, .backslashEscapesInDoubleQuotes, .backtickQuotes, .hashLineComments,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//
// MySQLReadOnlyTransaction+Statement.swift
// MySQLDriverPlugin
//

import Foundation
import TableProPluginKit

extension MySQLReadOnlyTransaction {
// The session state is read on the statement's own queue, so nothing queued behind it can open a transaction first.
struct Scope: Sendable {
let reason: Reason
let sessionState: @Sendable (Bool) -> PluginSessionTransactionState
}

static var sessionNotIdle: MariaDBPluginError {
MariaDBPluginError(code: 0, message: notIdleMessage(.externalClients), sqlState: nil)
}

static var safeModeSessionNotIdle: MariaDBPluginError {
MariaDBPluginError(code: 0, message: notIdleMessage(.safeMode), sqlState: nil)
}

static func reason(for context: PluginStatementContext, flavor: MySQLServerFlavor) -> Reason? {
guard flavor.enforcesReadOnlyTransactions else { return nil }
if context.readOnly, context.origin == .external { return .externalClients }
if context.enforcesReadOnly { return .safeMode }
return nil
}

static func applies(to context: PluginStatementContext, flavor: MySQLServerFlavor) -> Bool {
reason(for: context, flavor: flavor) != nil
}

// `START TRANSACTION` would commit the user's open transaction and release their `LOCK TABLES`.
static func run<Result>(
state: PluginSessionTransactionState,
reason: Reason,
send: (String) throws -> Void,
statement: () throws -> Result
) throws -> Result {
guard state == .idle else { throw notIdle(reason) }
do {
try send(begin)
} catch {
try? send(end)
throw error
}
let result: Result
do {
result = try statement()
} catch {
try? send(end)
throw refusal(from: error, reason: reason)
}
try send(end)
return result
}

static func notIdle(_ reason: Reason) -> MariaDBPluginError {
switch reason {
case .externalClients: sessionNotIdle
case .safeMode: safeModeSessionNotIdle
}
}

static func refusal(from error: Error, reason: Reason) -> Error {
guard let failure = error as? MariaDBPluginError, failure.code == refusalCode else { return error }
return MariaDBPluginError(code: failure.code, message: refusalMessage(reason), sqlState: failure.sqlState)
}
}
84 changes: 11 additions & 73 deletions apple/Plugins/MySQLDriverPlugin/MySQLReadOnlyTransaction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,97 +4,35 @@
//

import Foundation
import TableProPluginKit

internal enum MySQLReadOnlyTransaction {
// The iOS MySQL driver compiles this file too; the plugin's statement handling is in
// MySQLReadOnlyTransaction+Statement.swift.
nonisolated internal enum MySQLReadOnlyTransaction {
// Who asked for the read-only mode, which is what a refusal names.
enum Reason: Sendable, Equatable {
case externalClients
case safeMode
}

// The session state is read on the statement's own queue, so nothing queued behind it can open a transaction first.
struct Scope: Sendable {
let reason: Reason
let sessionState: @Sendable (Bool) -> PluginSessionTransactionState
}

// Not the `/*!50605 ... */` spelling: a server older than 5.6.5 would run that as a plain read-write transaction.
static let begin = "START TRANSACTION READ ONLY"
static let end = "ROLLBACK"

// ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION.
static let refusalCode: UInt32 = 1_792

static var sessionNotIdle: MariaDBPluginError {
MariaDBPluginError(
code: 0,
message: String(
localized: "This connection has a transaction open. Commit or roll it back in TablePro, then try again."
),
sqlState: nil
)
}

// Read-Only offers no Commit, so the way out is a rollback.
static var safeModeSessionNotIdle: MariaDBPluginError {
MariaDBPluginError(
code: 0,
message: String(
localized: "Safe Mode is set to Read-Only for this connection, and it has a transaction open. Roll it back, then try again."
),
sqlState: nil
)
}

static func reason(for context: PluginStatementContext, flavor: MySQLServerFlavor) -> Reason? {
guard flavor.enforcesReadOnlyTransactions else { return nil }
if context.readOnly, context.origin == .external { return .externalClients }
if context.enforcesReadOnly { return .safeMode }
return nil
}

static func applies(to context: PluginStatementContext, flavor: MySQLServerFlavor) -> Bool {
reason(for: context, flavor: flavor) != nil
}

// `START TRANSACTION` would commit the user's open transaction and release their `LOCK TABLES`.
static func run<Result>(
state: PluginSessionTransactionState,
reason: Reason,
send: (String) throws -> Void,
statement: () throws -> Result
) throws -> Result {
guard state == .idle else { throw notIdle(reason) }
do {
try send(begin)
} catch {
try? send(end)
throw error
}
let result: Result
do {
result = try statement()
} catch {
try? send(end)
throw refusal(from: error, reason: reason)
}
try send(end)
return result
}

static func notIdle(_ reason: Reason) -> MariaDBPluginError {
static func notIdleMessage(_ reason: Reason) -> String {
switch reason {
case .externalClients: sessionNotIdle
case .safeMode: safeModeSessionNotIdle
case .externalClients:
String(localized: "This connection has a transaction open. Commit or roll it back in TablePro, then try again.")
// Read-Only offers no Commit, so the way out is a rollback.
case .safeMode:
String(
localized: "Safe Mode is set to Read-Only for this connection, and it has a transaction open. Roll it back, then try again."
)
}
}

static func refusal(from error: Error, reason: Reason) -> Error {
guard let failure = error as? MariaDBPluginError, failure.code == refusalCode else { return error }
return MariaDBPluginError(code: failure.code, message: refusalMessage(reason), sqlState: failure.sqlState)
}

static func refusalMessage(_ reason: Reason) -> String {
switch reason {
case .externalClients:
Expand Down
13 changes: 13 additions & 0 deletions apple/Plugins/MySQLDriverPlugin/MySQLServerVersion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ nonisolated internal enum MySQLServerVersion {
flavor.isMariaDB && isAtLeast((10, 2, 7), banner: banner)
}

// MySQL 5.6.5 (WL #5968) and MariaDB 10.0.0 added `START TRANSACTION READ ONLY`. No other flavor is held to it, as
// `MySQLServerFlavor.enforcesReadOnlyTransactions` says.
static func hasReadOnlyTransactions(banner: String?, flavor: MySQLServerFlavor) -> Bool {
switch flavor {
case .mysql:
return !isLegacy(below: (5, 6, 5), banner: banner, flavor: flavor)
case .mariadb:
return !isLegacy(below: (10, 0, 0), banner: banner, flavor: flavor)
case .tidb, .oceanbase, .databend, .starrocks:
return false
}
}

// A binary default arrives as its bytes from MySQL 5.7.44, MariaDB and OceanBase, and as `0x` hex from MySQL 8.0.11 to 8.4.13.
static func reportsBinaryDefaultAsHex(banner: String?, flavor: MySQLServerFlavor) -> Bool {
switch flavor {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import TableProPluginKit
/// Every ambiguity resolves toward "the session is holding something". The cost of that is only
/// that a connection keeps its slot, which is what happens today; the cost of the opposite is
/// destroying a user's transaction or temporary table without telling them.
struct MySQLSessionFootprint: Equatable {
nonisolated struct MySQLSessionFootprint: Equatable {
private(set) var hasOpenTransaction = false
private(set) var hasTemporaryTables = false
private(set) var hasUserVariables = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Foundation
// MySQL 8.4.11 lists a session's temporary tables nowhere an ordinary user can read (`INNODB_TEMP_TABLE_INFO` needs
// PROCESS), so the names come from the statement text. Only the table part is kept: `SHOW CREATE TABLE name` on the
// session resolves it in the browsed database and answers `CREATE TEMPORARY TABLE` for one.
enum MySQLTemporaryTableNames {
nonisolated enum MySQLTemporaryTableNames {
static func created(by statement: String) -> String? {
var reader = Reader(statement)
guard reader.accept("CREATE") else { return nil }
Expand Down Expand Up @@ -53,7 +53,7 @@ enum MySQLTemporaryTableNames {
}
}

private enum NameToken: Equatable {
nonisolated private enum NameToken: Equatable {
case word(String)
case quoted(String)
case dot
Expand All @@ -62,7 +62,7 @@ private enum NameToken: Equatable {
}

// A string literal is one `other` token, so a keyword inside one is never read.
private struct Reader {
nonisolated private struct Reader {
private let scalars: [Unicode.Scalar]
private var index = 0
private var executableCommentDepth = 0
Expand Down
16 changes: 16 additions & 0 deletions apple/Plugins/MySQLDriverTests/MySQLServerVersionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ struct MySQLServerVersionTests {
#expect(!MySQLServerVersion.hasGenerationExpression(banner: "unknown", flavor: .mysql))
}

@Test("READ ONLY transactions start at MySQL 5.6.5 and MariaDB 10.0, an unreadable banner is not an old server, and no other flavor has them")
func readOnlyTransactionFloor() {
#expect(!MySQLServerVersion.hasReadOnlyTransactions(banner: "5.6.4-log", flavor: .mysql))
#expect(MySQLServerVersion.hasReadOnlyTransactions(banner: "5.6.5", flavor: .mysql))
#expect(MySQLServerVersion.hasReadOnlyTransactions(banner: "8.4.13", flavor: .mysql))
#expect(!MySQLServerVersion.hasReadOnlyTransactions(banner: "5.5.64-MariaDB", flavor: .mariadb))
#expect(MySQLServerVersion.hasReadOnlyTransactions(banner: "10.0.0-MariaDB", flavor: .mariadb))
#expect(MySQLServerVersion.hasReadOnlyTransactions(banner: "11.4.13-MariaDB", flavor: .mariadb))
#expect(MySQLServerVersion.hasReadOnlyTransactions(banner: nil, flavor: .mysql))
#expect(MySQLServerVersion.hasReadOnlyTransactions(banner: "unknown", flavor: .mariadb))
#expect(!MySQLServerVersion.hasReadOnlyTransactions(banner: "8.0.11-TiDB-v8.5.1", flavor: .tidb(version: nil)))
#expect(!MySQLServerVersion.hasReadOnlyTransactions(banner: "5.7.25", flavor: .oceanbase(version: nil)))
#expect(!MySQLServerVersion.hasReadOnlyTransactions(banner: "8.0.0", flavor: .databend))
#expect(!MySQLServerVersion.hasReadOnlyTransactions(banner: "8.0.33", flavor: .starrocks))
}

/// The other direction: a gate that picks legacy syntax has to hear a version before it does,
/// because the legacy statements are a 1064 on MySQL 8.
@Test("isKnownBelow answers false for a banner it cannot read")
Expand Down
Loading
Loading