diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md
index ffc9fefebf..b45b69f6e5 100644
--- a/.claude/rules/data-sync-storage.md
+++ b/.claude/rules/data-sync-storage.md
@@ -81,6 +81,7 @@ paths:
- "apple/TablePro/Core/RoutineDebugging/RoutineDebugOptionStore.swift"
- "apple/TablePro/Core/RowGeneration/RowGenerationModel.swift"
- "apple/TablePro/Core/SSH/HostKeyStore.swift"
+ - "apple/TableProMobile/TableProMobile/SSH/HostKeyStore.swift"
- "apple/TablePro/Core/Transfer/Shared/ImportColumnMatcher.swift"
- "apple/TablePro/Core/Services/Formatting/ValueDisplayFormat.swift"
- "apple/TablePro/Core/Services/TeamLibrary/TeamLibraryState.swift"
@@ -123,6 +124,7 @@ paths:
- "apple/Packages/TableProMacCore/Sources/TableProUtilities/File/FileTextEncoding.swift"
- "apple/Packages/TableProMacCore/Sources/TableProUtilities/UI/QuickSwitcherFrecencyStore.swift"
- "apple/Packages/TableProMacCore/Sources/TableProMCP/Outside/MCPServerConfiguration.swift"
+ - "apple/Packages/TableProCore/Sources/TableProSSHTransport/HostKeyStore.swift"
- "apple/Packages/TableProCore/Sources/TableProSSHTransport/PublishedSSHRoute.swift"
- "apple/Packages/TableProCore/Sources/TableProSSHTransport/TOTPConfiguration.swift"
- "apple/Packages/TableProCore/Sources/TableProConnectionLibrary/RecentConnectionsLedger.swift"
diff --git a/.claude/rules/plugin-system.md b/.claude/rules/plugin-system.md
index dc90c8595e..5c0d073ca3 100644
--- a/.claude/rules/plugin-system.md
+++ b/.claude/rules/plugin-system.md
@@ -54,6 +54,7 @@ TableProPluginKit is built with Library Evolution, so an already-built plugin ke
- The `TablePro` scheme builds only the bundled plugins, and a registry plugin's compile error still ends in `BUILD SUCCEEDED`. Run `verify.sh plugins` (the `AllPlugins` aggregate) after any change under `apple/Plugins/`.
- `apple/scripts/ci/verify-plugin-loads.sh
...` dlopens every built `.tableplugin` and names any that will not load. It does not instantiate the principal class.
+- The curated entry in `PluginMetadataRegistry` answers for a type until its plugin's code loads, so it declares what the plugin declares. `PluginMetadataCuratedParityTests` (Unit plan) loads every driver plugin built beside the test host, builds its snapshot as registration does and fails on each field that differs from the curated entry. CI builds `AllPlugins` before the Unit plan when the `plugins` suite runs, so the registry plugins are compared then; locally, run `verify.sh plugins` first. A variant keeps its own curated entry and is not compared.
## Column type corpus
diff --git a/.github/workflows/ci-lint.yml b/.github/workflows/ci-lint.yml
index 9a1dd9db99..aafaf83b7f 100644
--- a/.github/workflows/ci-lint.yml
+++ b/.github/workflows/ci-lint.yml
@@ -135,10 +135,6 @@ jobs:
- name: Check every plugin Info.plist declares the ids its class provides
run: python3 apple/scripts/ci/check-plugin-provides.py
- # The curated entry answers until the plugin loads, then the plugin's static replaces it (#2700).
- - name: Check curated driver capabilities match their plugins
- run: python3 apple/scripts/ci/check-capability-parity.py
-
# Import, export and sync drop a field the trust catalog does not classify.
- name: Check every connection field has a trust class
run: python3 apple/scripts/ci/check-connection-field-trust.py
@@ -184,6 +180,10 @@ jobs:
- name: Check the statement classifiers read words through the grammar's tokens
run: python3 apple/scripts/ci/check-classifier-text-matching.py
+ # A new engine belongs in a plugin (apple/AGENTS.md, Scope); a view reads services through injection.
+ - name: Check engine-name comparisons and view singleton reads do not grow
+ run: python3 apple/scripts/ci/check-source-ratchets.py
+
# The corpora run by hand against servers (scripts/probes/check-column-type-corpus.sh), so a type a driver
# starts listing is caught here.
- name: Check every listed column type has a corpus column
diff --git a/.github/workflows/macos-tests.yml b/.github/workflows/macos-tests.yml
index 6a480c3843..34d9e2664b 100644
--- a/.github/workflows/macos-tests.yml
+++ b/.github/workflows/macos-tests.yml
@@ -84,6 +84,7 @@ jobs:
scripts/build-dameng.sh arm64
scripts/build-hana.sh arm64
+ # Before the Unit plan, whose PluginMetadataCuratedParityTests loads the plugins built here.
- name: Compile every plugin
if: ${{ !cancelled() && steps.bridges.outcome == 'success' }}
run: |
diff --git a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalGrammar+Quoting.swift b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalGrammar+Quoting.swift
index a82415cc6c..7b4b5f536d 100644
--- a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalGrammar+Quoting.swift
+++ b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalGrammar+Quoting.swift
@@ -25,11 +25,14 @@ public extension SQLLexicalReadings {
// quote opens `'''`, has no such form and takes the execution reading.
static func stringEscapes(
databaseTypeId: String,
+ queryLanguage: String? = nil,
declared: SQLLexicalGrammar?,
session: SQLSessionLexicalFacts?
) -> SQLStringEscapes {
if databaseTypeId == "SQL Server" { return .sqlServer }
- let readings = resolve(databaseTypeId: databaseTypeId, declared: declared, session: session)
+ let readings = resolve(
+ databaseTypeId: databaseTypeId, queryLanguage: queryLanguage, declared: declared, session: session
+ )
if let session, session.determined.contains(.backslashEscapesInSingleQuotes) {
return readings.execution.stringEscapes
}
diff --git a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalProfile.swift b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalProfile.swift
index 8ec9f9526a..6634360533 100644
--- a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalProfile.swift
+++ b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalProfile.swift
@@ -56,6 +56,12 @@ public struct SQLLexicalProfile: Sendable, Hashable {
profiles[typeId]
}
+ /// A query language several engines share, named as a plugin's `EditorLanguage.custom` names it, so an engine
+ /// TablePro does not curate still lexes as its language does.
+ public static func curated(forQueryLanguage language: String) -> SQLLexicalProfile? {
+ language == "cypher" ? cypherProfile : nil
+ }
+
/// The database type ids the curated table covers.
public static var curatedDatabaseTypeIds: Set {
Set(profiles.keys)
@@ -221,6 +227,8 @@ public struct SQLLexicalProfile: Sendable, Hashable {
.withoutDashComments,
]
+ private static let cypherProfile = SQLLexicalProfile(grammar: cypher, undetermined: [.carriageReturnEndsLineComments])
+
/// DynamoDB, from the driver's statement forms: a request is ` {JSON}`, and a backslash escapes inside a
/// JSON string. PartiQL, the other form, documents only a doubled quote, so plain ANSI is kept as an alternative
/// and a gate reads both. Not measured.
@@ -350,7 +358,7 @@ public struct SQLLexicalProfile: Sendable, Hashable {
.backslashEscapesInBackticks, .backslashEscapesInAngleQuotes, .carriageReturnEndsLineComments,
]
),
- "Neo4j": SQLLexicalProfile(grammar: cypher, undetermined: [.carriageReturnEndsLineComments]),
+ "Neo4j": cypherProfile,
"InfluxDB": SQLLexicalProfile(
grammar: influxDB,
alternatives: [.ansi],
diff --git a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalReadings.swift b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalReadings.swift
index 8311a7f4b6..393806791a 100644
--- a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalReadings.swift
+++ b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLLexicalReadings.swift
@@ -49,15 +49,17 @@ public struct SQLLexicalReadings: Sendable, Hashable {
all.count > 1
}
- /// Resolves the readings for a connection: the curated profile when TablePro knows the engine, which wins over
- /// anything a plugin declares because a registry plugin may be built against an older kit; otherwise what the
- /// plugin declared; otherwise every grammar TablePro knows, split for execution as standard SQL.
+ /// Resolves the readings for a connection: the curated profile when TablePro knows the engine or the query language
+ /// its plugin names, which wins over anything a plugin declares because a registry plugin may be built against an
+ /// older kit; otherwise what the plugin declared; otherwise every grammar TablePro knows, split for execution as
+ /// standard SQL.
public static func resolve(
databaseTypeId: String,
+ queryLanguage: String? = nil,
declared: SQLLexicalGrammar?,
session: SQLSessionLexicalFacts?
) -> SQLLexicalReadings {
- let base = baseReadings(databaseTypeId: databaseTypeId, declared: declared)
+ let base = baseReadings(databaseTypeId: databaseTypeId, queryLanguage: queryLanguage, declared: declared)
guard let session else { return base }
let execution = session.applied(to: base.execution)
return SQLLexicalReadings(execution: execution, all: base.all)
@@ -96,8 +98,13 @@ public struct SQLLexicalReadings: Sendable, Hashable {
})
}
- private static func baseReadings(databaseTypeId: String, declared: SQLLexicalGrammar?) -> SQLLexicalReadings {
- if let profile = SQLLexicalProfile.curated(forDatabaseTypeId: databaseTypeId) {
+ private static func baseReadings(
+ databaseTypeId: String,
+ queryLanguage: String?,
+ declared: SQLLexicalGrammar?
+ ) -> SQLLexicalReadings {
+ if let profile = SQLLexicalProfile.curated(forDatabaseTypeId: databaseTypeId)
+ ?? queryLanguage.flatMap({ SQLLexicalProfile.curated(forQueryLanguage: $0) }) {
return SQLLexicalReadings(execution: profile.grammar, all: profile.readings)
}
if let declared {
diff --git a/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary+PostgreSQL.swift b/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary+PostgreSQL.swift
index d8113f4427..7b137179bc 100644
--- a/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary+PostgreSQL.swift
+++ b/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary+PostgreSQL.swift
@@ -9,13 +9,116 @@ public extension SQLEngineVocabulary {
],
dataTypes: PostgreSQLLists.dataTypes,
tableOptions: ["INHERITS", "PARTITION BY", "TABLESPACE", "WITH", "WITHOUT OIDS"],
- operators: PostgreSQLLists.operators
+ operators: PostgreSQLLists.operators,
+ keywords: PostgreSQLLists.keywords
)
}
private enum PostgreSQLLists {
typealias Operator = SQLEngineVocabulary.Operator
+ static let keywords: Set = reservedKeywords
+ .union(nonReservedKeywords)
+ .union(multiWordConstructs)
+
+ private static let reservedKeywords: Set = [
+ "ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "ASYMMETRIC", "BOTH",
+ "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE", "CURRENT_CATALOG",
+ "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER",
+ "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE",
+ "FETCH", "FOR", "FOREIGN", "FROM", "GRANT", "GROUP", "HAVING", "IN", "INITIALLY",
+ "INTERSECT", "INTO", "LATERAL", "LEADING", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP",
+ "NOT", "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", "PLACING", "PRIMARY", "REFERENCES",
+ "RETURNING", "SELECT", "SESSION_USER", "SOME", "SYMMETRIC", "SYSTEM_USER", "TABLE",
+ "THEN", "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC",
+ "WHEN", "WHERE", "WINDOW", "WITH",
+ "AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS", "CURRENT_SCHEMA",
+ "FREEZE", "FULL", "ILIKE", "INNER", "IS", "ISNULL", "JOIN", "LEFT", "LIKE", "NATURAL",
+ "NOTNULL", "OUTER", "OVERLAPS", "RIGHT", "SIMILAR", "TABLESAMPLE", "VERBOSE"
+ ]
+
+ private static let nonReservedKeywords: Set = [
+ "ABORT", "ABSENT", "ABSOLUTE", "ACCESS", "ACTION", "ADD", "ADMIN", "AFTER", "AGGREGATE",
+ "ALTER", "ALWAYS", "AT", "ATOMIC", "ATTACH", "ATTRIBUTE", "BACKWARD", "BEFORE", "BEGIN",
+ "BREADTH", "BY", "CACHE", "CALL", "CALLED", "CASCADE", "CASCADED", "CHAIN",
+ "CHARACTERISTICS", "CHECKPOINT", "CLASS", "CLOSE", "CLUSTER", "COLUMNS", "COMMENT",
+ "COMMENTS", "COMMIT", "COMMITTED", "COMPRESSION", "CONDITIONAL", "CONFIGURATION",
+ "CONFLICT", "CONNECTION", "CONSTRAINTS", "CONTENT", "CONTINUE", "CONVERSION", "COPY",
+ "COST", "CSV", "CUBE", "CURRENT", "CURSOR", "CYCLE", "DATA", "DATABASE", "DAY",
+ "DEALLOCATE", "DECLARE", "DEFAULTS", "DEFERRED", "DEFINER", "DELETE", "DELIMITER",
+ "DELIMITERS", "DEPENDS", "DEPTH", "DETACH", "DICTIONARY", "DISABLE", "DISCARD",
+ "DOCUMENT", "DOMAIN", "DOUBLE", "DROP", "EACH", "EMPTY", "ENABLE", "ENCODING",
+ "ENCRYPTED", "ENUM", "ERROR", "ESCAPE", "EVENT", "EXCLUDE", "EXCLUDING", "EXCLUSIVE",
+ "EXECUTE", "EXPLAIN", "EXPRESSION", "EXTENSION", "EXTERNAL", "FAMILY", "FILTER",
+ "FINALIZE", "FIRST", "FOLLOWING", "FORCE", "FORMAT", "FORWARD", "FUNCTION", "FUNCTIONS",
+ "GENERATED", "GLOBAL", "GRANTED", "GROUPS", "HANDLER", "HEADER", "HOLD", "HOUR",
+ "IDENTITY", "IF", "IMMEDIATE", "IMMUTABLE", "IMPLICIT", "IMPORT", "INCLUDE", "INCLUDING",
+ "INCREMENT", "INDENT", "INDEX", "INDEXES", "INHERIT", "INHERITS", "INPUT", "INSENSITIVE",
+ "INSERT", "INSTEAD", "INVOKER", "ISOLATION", "KEEP", "KEY", "KEYS", "LABEL", "LANGUAGE",
+ "LARGE", "LAST", "LEAKPROOF", "LEVEL", "LISTEN", "LOAD", "LOCAL", "LOCATION", "LOCK",
+ "LOCKED", "LOGGED", "MAPPING", "MATCH", "MATCHED", "MATERIALIZED", "MAXVALUE", "MERGE",
+ "METHOD", "MINUTE", "MINVALUE", "MODE", "MONTH", "MOVE", "NAME", "NAMES", "NESTED",
+ "NEW", "NEXT", "NO", "NORMALIZED", "NOTHING", "NOTIFY", "NOWAIT", "NULLS", "OBJECT",
+ "OF", "OFF", "OLD", "OMIT", "OPERATOR", "OPTION", "OPTIONS", "ORDINALITY", "OTHERS",
+ "OVER", "OVERRIDING", "OWNED", "OWNER", "PARALLEL", "PARAMETER", "PARSER", "PARTIAL",
+ "PARTITION", "PASSING", "PASSWORD", "PATH", "POLICY", "PRECEDING", "PREPARE", "PREPARED",
+ "PRESERVE", "PRIOR", "PRIVILEGES", "PROCEDURE", "PROCEDURES", "PROGRAM", "PUBLICATION",
+ "QUOTE", "QUOTES", "RANGE", "READ", "REASSIGN", "RECURSIVE", "REFERENCING", "REFRESH",
+ "REINDEX", "RELATIVE", "RELEASE", "RENAME", "REPEATABLE", "REPLACE", "REPLICA", "RESET",
+ "RESTART", "RESTRICT", "RETURN", "RETURNS", "REVOKE", "ROLE", "ROLLBACK", "ROLLUP",
+ "ROUTINE", "ROUTINES", "ROWS", "RULE", "SAVEPOINT", "SCALAR", "SCHEMA", "SCHEMAS",
+ "SCROLL", "SEARCH", "SECOND", "SECURITY", "SEQUENCE", "SEQUENCES", "SERIALIZABLE",
+ "SERVER", "SESSION", "SET", "SETS", "SHARE", "SHOW", "SIMPLE", "SKIP", "SNAPSHOT",
+ "SOURCE", "SQL", "STABLE", "STANDALONE", "START", "STATEMENT", "STATISTICS", "STDIN",
+ "STDOUT", "STORAGE", "STORED", "STRICT", "STRING", "STRIP", "SUBSCRIPTION", "SUPPORT",
+ "SYSTEM", "TABLES", "TABLESPACE", "TARGET", "TEMP", "TEMPLATE", "TEMPORARY", "TEXT",
+ "TIES", "TRANSACTION", "TRANSFORM", "TRIGGER", "TRUNCATE", "TRUSTED", "TYPE", "TYPES",
+ "UNBOUNDED", "UNCOMMITTED", "UNCONDITIONAL", "UNENCRYPTED", "UNKNOWN", "UNLISTEN",
+ "UNLOGGED", "UNTIL", "UPDATE", "VACUUM", "VALID", "VALIDATE", "VALIDATOR", "VALUE",
+ "VARYING", "VERSION", "VIEW", "VIEWS", "VOLATILE", "WHITESPACE", "WITHIN", "WITHOUT",
+ "WORK", "WRAPPER", "WRITE", "XML", "YEAR", "YES", "ZONE",
+ "BETWEEN", "COALESCE", "EXISTS", "GREATEST", "GROUPING", "LEAST", "MERGE_ACTION",
+ "NULLIF", "OVERLAY", "POSITION", "SETOF", "SUBSTRING", "TREAT", "TRIM", "VALUES"
+ ]
+
+ private static let multiWordConstructs: Set = [
+ "ON CONFLICT", "ON CONFLICT DO NOTHING", "ON CONFLICT DO UPDATE SET", "ON CONSTRAINT",
+ "DO NOTHING", "DO UPDATE SET", "DEFAULT VALUES", "OVERRIDING SYSTEM VALUE",
+ "OVERRIDING USER VALUE", "RETURNING *",
+ "SELECT DISTINCT", "SELECT DISTINCT ON", "DISTINCT ON", "GROUP BY", "GROUP BY ALL",
+ "GROUP BY DISTINCT", "GROUPING SETS", "ORDER BY", "NULLS FIRST", "NULLS LAST",
+ "UNION ALL", "UNION DISTINCT", "INTERSECT ALL", "EXCEPT ALL", "LIMIT ALL",
+ "FETCH FIRST", "FETCH NEXT", "WITH TIES", "FOR UPDATE", "FOR NO KEY UPDATE",
+ "FOR SHARE", "FOR KEY SHARE", "SKIP LOCKED", "TABLESAMPLE SYSTEM",
+ "TABLESAMPLE BERNOULLI", "WITH ORDINALITY", "ROWS FROM",
+ "INNER JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "RIGHT JOIN", "RIGHT OUTER JOIN",
+ "FULL JOIN", "FULL OUTER JOIN", "CROSS JOIN", "NATURAL JOIN",
+ "WITH RECURSIVE", "AS MATERIALIZED", "AS NOT MATERIALIZED",
+ "SEARCH BREADTH FIRST BY", "SEARCH DEPTH FIRST BY",
+ "CREATE TABLE IF NOT EXISTS", "CREATE TEMP TABLE", "CREATE UNLOGGED TABLE",
+ "NOT NULL", "PRIMARY KEY", "FOREIGN KEY", "UNIQUE NULLS DISTINCT",
+ "UNIQUE NULLS NOT DISTINCT", "GENERATED ALWAYS AS", "GENERATED ALWAYS AS IDENTITY",
+ "GENERATED BY DEFAULT AS IDENTITY", "MATCH FULL", "MATCH PARTIAL", "MATCH SIMPLE",
+ "ON DELETE CASCADE", "ON DELETE RESTRICT", "ON DELETE SET NULL", "ON DELETE NO ACTION",
+ "ON UPDATE CASCADE", "ON UPDATE RESTRICT", "ON UPDATE SET NULL",
+ "DEFERRABLE INITIALLY DEFERRED", "INITIALLY IMMEDIATE", "EXCLUDE USING",
+ "PARTITION BY RANGE", "PARTITION BY LIST", "PARTITION BY HASH", "PARTITION OF",
+ "FOR VALUES IN", "FOR VALUES FROM", "FOR VALUES WITH",
+ "ON COMMIT PRESERVE ROWS", "ON COMMIT DELETE ROWS", "ON COMMIT DROP",
+ "OVER", "PARTITION BY", "FILTER", "WITHIN GROUP", "ROWS BETWEEN", "RANGE BETWEEN",
+ "GROUPS BETWEEN", "UNBOUNDED PRECEDING", "UNBOUNDED FOLLOWING", "CURRENT ROW",
+ "EXCLUDE CURRENT ROW", "EXCLUDE GROUP", "EXCLUDE TIES", "EXCLUDE NO OTHERS",
+ "MERGE INTO", "WHEN MATCHED THEN", "WHEN MATCHED THEN UPDATE SET",
+ "WHEN MATCHED THEN DELETE", "WHEN NOT MATCHED THEN INSERT",
+ "WHEN NOT MATCHED BY TARGET THEN", "WHEN NOT MATCHED BY SOURCE THEN",
+ "CREATE INDEX CONCURRENTLY", "CREATE MATERIALIZED VIEW", "REFRESH MATERIALIZED VIEW",
+ "CREATE TYPE", "CREATE EXTENSION", "IF NOT EXISTS", "IF EXISTS", "CASCADE", "RESTRICT",
+ "IS NULL", "IS NOT NULL", "IS TRUE", "IS NOT TRUE", "IS FALSE", "IS NOT FALSE",
+ "IS UNKNOWN", "IS NOT UNKNOWN", "IS DISTINCT FROM", "IS NOT DISTINCT FROM",
+ "BETWEEN SYMMETRIC", "NOT BETWEEN", "NOT BETWEEN SYMMETRIC", "NOT LIKE", "NOT ILIKE",
+ "SIMILAR TO", "NOT SIMILAR TO", "AT TIME ZONE", "AT LOCAL"
+ ]
+
static let functions: Set = aggregateFunctions
.union(windowFunctions)
.union(stringFunctions)
diff --git a/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary.swift b/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary.swift
index cf7aeecfa0..2a414c8387 100644
--- a/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary.swift
+++ b/apple/Packages/TableProCore/Sources/TableProSQLVocabulary/SQLEngineVocabulary.swift
@@ -33,6 +33,8 @@ public struct SQLEngineVocabulary: Sendable, Hashable {
public let dataTypes: Set
public let tableOptions: [String]
public let operators: [Operator]
+ // Empty for an engine whose plugin still lists its own.
+ public let keywords: Set
public init(
functions: Set,
@@ -40,7 +42,8 @@ public struct SQLEngineVocabulary: Sendable, Hashable {
functionNamesAreCaseInsensitive: Bool = true,
dataTypes: Set,
tableOptions: [String] = [],
- operators: [Operator] = []
+ operators: [Operator] = [],
+ keywords: Set = []
) {
self.functions = functions
self.bareFunctions = bareFunctions
@@ -48,6 +51,7 @@ public struct SQLEngineVocabulary: Sendable, Hashable {
self.dataTypes = dataTypes
self.tableOptions = tableOptions
self.operators = operators
+ self.keywords = keywords
}
public static func curated(forDatabaseTypeId typeId: String) -> SQLEngineVocabulary? {
diff --git a/apple/Packages/TableProCore/Sources/TableProSSHTransport/HostKeyStore.swift b/apple/Packages/TableProCore/Sources/TableProSSHTransport/HostKeyStore.swift
new file mode 100644
index 0000000000..bb185f0bd1
--- /dev/null
+++ b/apple/Packages/TableProCore/Sources/TableProSSHTransport/HostKeyStore.swift
@@ -0,0 +1,122 @@
+import CryptoKit
+import Foundation
+import os
+
+public final class HostKeyStore: @unchecked Sendable {
+ private static let logger = Logger(subsystem: "com.TablePro", category: "HostKeyStore")
+
+ public enum VerificationResult: Equatable, Sendable {
+ case trusted
+ case unknown(fingerprint: String, keyType: String)
+ case mismatch(expected: String, actual: String)
+ // The file is one entry per line split on spaces, so a host with a line break would plant
+ // an entry for another host.
+ case invalidHost(SSHDestinationName.Problem)
+ // The saved keys could not be read, so a changed key would look like a new host.
+ case unreadable
+ }
+
+ public let filePath: String
+ private let lock = NSLock()
+
+ public init(filePath: String) {
+ self.filePath = filePath
+ }
+
+ public func verify(keyData: Data, keyType: String, hostname: String, port: Int) -> VerificationResult {
+ lock.lock()
+ defer { lock.unlock() }
+
+ guard let hostKey = hostIdentifier(hostname, port) else {
+ return .invalidHost(.host(hostname))
+ }
+ guard let file = loadFile() else { return .unreadable }
+
+ switch file.match(host: hostKey, keyType: keyType, keyData: keyData) {
+ case .trusted:
+ Self.logger.debug("Host key trusted for \(hostKey)")
+ return .trusted
+ case .unknown:
+ Self.logger.info("Unknown host key for \(hostKey)")
+ return .unknown(fingerprint: Self.fingerprint(of: keyData), keyType: keyType)
+ case .changed(let storedKey):
+ Self.logger.warning("Host key mismatch for \(hostKey)")
+ return .mismatch(expected: Self.fingerprint(of: storedKey), actual: Self.fingerprint(of: keyData))
+ case .unreadable:
+ Self.logger.error("The saved host key for \(hostKey) could not be parsed")
+ return .unreadable
+ }
+ }
+
+ public func trust(hostname: String, port: Int, key: Data, keyType: String) {
+ lock.lock()
+ defer { lock.unlock() }
+
+ guard let hostKey = hostIdentifier(hostname, port), var file = loadFile() else { return }
+ file.trust(host: hostKey, keyType: keyType, keyData: key)
+ saveFile(file)
+
+ Self.logger.info("Trusted host key for \(hostKey) (\(keyType))")
+ }
+
+ public func remove(hostname: String, port: Int) {
+ lock.lock()
+ defer { lock.unlock() }
+
+ guard let hostKey = hostIdentifier(hostname, port), var file = loadFile() else { return }
+ if file.remove(host: hostKey) {
+ saveFile(file)
+ Self.logger.info("Removed host key for \(hostKey)")
+ }
+ }
+
+ public func trustedHosts() -> [String] {
+ lock.lock()
+ defer { lock.unlock() }
+ return Array(Set((loadFile()?.entries ?? []).map(\.host))).sorted()
+ }
+
+ public static func keyTypeName(_ type: Int32) -> String {
+ switch type {
+ case 1: return "ssh-rsa"
+ case 2: return "ssh-dss"
+ case 3: return "ecdsa-sha2-nistp256"
+ case 4: return "ecdsa-sha2-nistp384"
+ case 5: return "ecdsa-sha2-nistp521"
+ case 6: return "ssh-ed25519"
+ default: return "unknown"
+ }
+ }
+
+ // The OpenSSH form `ssh-keygen -l` prints: SHA-256, base64 without padding.
+ public static func fingerprint(of key: Data) -> String {
+ let digest = SHA256.hash(data: key)
+ return "SHA256:" + Data(digest).base64EncodedString().replacingOccurrences(of: "=", with: "")
+ }
+
+ private func hostIdentifier(_ hostname: String, _ port: Int) -> String? {
+ guard SSHDestinationName.isValidHost(hostname) else {
+ Self.logger.warning("Refusing a host key entry for a host ssh would refuse")
+ return nil
+ }
+ return "[\(hostname)]:\(port)"
+ }
+
+ // nil means the file is there but unreadable, and nothing may be written over it.
+ private func loadFile() -> KnownHostsFile? {
+ do {
+ return try KnownHostsFile.load(from: URL(fileURLWithPath: filePath))
+ } catch {
+ Self.logger.error("Failed to read known_hosts file: \(error.localizedDescription)")
+ return nil
+ }
+ }
+
+ private func saveFile(_ file: KnownHostsFile) {
+ do {
+ try file.contents.write(toFile: filePath, atomically: true, encoding: .utf8)
+ } catch {
+ Self.logger.error("Failed to write known_hosts file: \(error.localizedDescription)")
+ }
+ }
+}
diff --git a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLLexicalReadingsTests.swift b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLLexicalReadingsTests.swift
index 0ae5b53a6c..f37edb7084 100644
--- a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLLexicalReadingsTests.swift
+++ b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLLexicalReadingsTests.swift
@@ -45,6 +45,31 @@ struct SQLLexicalReadingsTests {
#expect(readings.all == [declared])
}
+ @Test("An engine TablePro does not know lexes as the query language its plugin names")
+ func queryLanguageServesUnknownEngines() {
+ let neo4j = SQLLexicalReadings.resolve(databaseTypeId: "Neo4j", declared: nil, session: nil)
+ let graph = SQLLexicalReadings.resolve(
+ databaseTypeId: "Nonesuch", queryLanguage: "cypher", declared: [.hashLineComments], session: nil
+ )
+ #expect(graph == neo4j)
+ let text = "MATCH (a)-- (b) RETURN a; MATCH (n) RETURN n"
+ for grammar in graph.distinct(for: text) {
+ #expect(SQLStatementScanner.executableStatements(in: text, grammar: grammar).count == 2)
+ }
+ }
+
+ @Test("A curated engine keeps its own grammar whatever language its plugin names")
+ func curatedEngineWinsOverQueryLanguage() {
+ #expect(
+ SQLLexicalReadings.resolve(databaseTypeId: "PostgreSQL", queryLanguage: "cypher", declared: nil, session: nil)
+ == SQLLexicalReadings.resolve(databaseTypeId: "PostgreSQL", declared: nil, session: nil)
+ )
+ #expect(
+ SQLLexicalReadings.resolve(databaseTypeId: "Nonesuch", queryLanguage: "kafkaql", declared: nil, session: nil)
+ == SQLLexicalReadings.resolve(databaseTypeId: "Nonesuch", declared: nil, session: nil)
+ )
+ }
+
@Test("An engine nobody declared is split as standard SQL and read under every grammar TablePro knows")
func undeclaredUnknownEngineReadsEverything() {
let readings = SQLLexicalReadings.resolve(databaseTypeId: "Nonesuch", declared: nil, session: nil)
diff --git a/apple/Packages/TableProCore/Tests/TableProSSHTransportTests/HostKeyStoreTests.swift b/apple/Packages/TableProCore/Tests/TableProSSHTransportTests/HostKeyStoreTests.swift
new file mode 100644
index 0000000000..b50f6ad4cd
--- /dev/null
+++ b/apple/Packages/TableProCore/Tests/TableProSSHTransportTests/HostKeyStoreTests.swift
@@ -0,0 +1,238 @@
+import Foundation
+import Testing
+
+@testable import TableProSSHTransport
+
+struct HostKeyStoreTests {
+ private func key(_ seed: UInt8, length: Int = 32) -> Data {
+ Data(repeating: seed, count: length)
+ }
+
+ private func temporaryPath() -> String {
+ FileManager.default.temporaryDirectory.appendingPathComponent("known_hosts_\(UUID().uuidString)").path
+ }
+
+ @Test("An unseen host is unknown, with the presented key's fingerprint and type")
+ func unknownHost() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+
+ #expect(
+ store.verify(keyData: key(0xAA), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22)
+ == .unknown(fingerprint: HostKeyStore.fingerprint(of: key(0xAA)), keyType: "ssh-ed25519")
+ )
+ }
+
+ @Test("A trusted key verifies on the next connect")
+ func trustedKeyVerifies() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+
+ store.trust(hostname: "db.example.com", port: 22, key: key(0xBB), keyType: "ssh-ed25519")
+
+ #expect(store.verify(keyData: key(0xBB), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .trusted)
+ }
+
+ @Test("A changed key is a mismatch naming both fingerprints")
+ func changedKeyIsMismatch() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ let trusted = key(0xCC)
+ let presented = key(0xDD)
+
+ store.trust(hostname: "db.example.com", port: 22, key: trusted, keyType: "ssh-ed25519")
+
+ #expect(
+ store.verify(keyData: presented, keyType: "ssh-ed25519", hostname: "db.example.com", port: 22)
+ == .mismatch(expected: HostKeyStore.fingerprint(of: trusted), actual: HostKeyStore.fingerprint(of: presented))
+ )
+ }
+
+ @Test("A different key type for a known host is a mismatch, not a first-use prompt")
+ func differentKeyTypeIsMismatch() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ let trusted = key(0xEE)
+ let attacker = key(0xEF)
+
+ store.trust(hostname: "db.example.com", port: 22, key: trusted, keyType: "ssh-ed25519")
+
+ #expect(
+ store.verify(keyData: attacker, keyType: "ssh-rsa", hostname: "db.example.com", port: 22)
+ == .mismatch(expected: HostKeyStore.fingerprint(of: trusted), actual: HostKeyStore.fingerprint(of: attacker))
+ )
+ }
+
+ @Test("A host trusted under two key types verifies either one")
+ func eitherTrustedKeyTypeVerifies() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+
+ store.trust(hostname: "db.example.com", port: 22, key: key(0x11), keyType: "ssh-rsa")
+ store.trust(hostname: "db.example.com", port: 22, key: key(0x22), keyType: "ssh-ed25519")
+
+ #expect(store.verify(keyData: key(0x11), keyType: "ssh-rsa", hostname: "db.example.com", port: 22) == .trusted)
+ #expect(store.verify(keyData: key(0x22), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .trusted)
+ }
+
+ @Test("Trusting the same host and key type again replaces the stored key")
+ func trustReplacesKeyOfSameType() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ let old = key(0x66)
+ let new = key(0x77)
+
+ store.trust(hostname: "db.example.com", port: 22, key: old, keyType: "ssh-rsa")
+ store.trust(hostname: "db.example.com", port: 22, key: new, keyType: "ssh-rsa")
+
+ #expect(store.verify(keyData: new, keyType: "ssh-rsa", hostname: "db.example.com", port: 22) == .trusted)
+ #expect(
+ store.verify(keyData: old, keyType: "ssh-rsa", hostname: "db.example.com", port: 22)
+ == .mismatch(expected: HostKeyStore.fingerprint(of: new), actual: HostKeyStore.fingerprint(of: old))
+ )
+ }
+
+ @Test("Removing a host clears every key type stored for it")
+ func removeClearsAllKeyTypes() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ store.trust(hostname: "db.example.com", port: 22, key: key(0x21), keyType: "ssh-rsa")
+ store.trust(hostname: "db.example.com", port: 22, key: key(0x22), keyType: "ssh-ed25519")
+ #expect(store.trustedHosts() == ["[db.example.com]:22"])
+
+ store.remove(hostname: "db.example.com", port: 22)
+
+ #expect(store.trustedHosts().isEmpty)
+ #expect(
+ store.verify(keyData: key(0x21), keyType: "ssh-rsa", hostname: "db.example.com", port: 22)
+ == .unknown(fingerprint: HostKeyStore.fingerprint(of: key(0x21)), keyType: "ssh-rsa")
+ )
+ }
+
+ @Test("Hosts are stored, listed and removed independently")
+ func multipleHosts() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+
+ store.trust(hostname: "host-c.com", port: 22, key: key(0x33), keyType: "ecdsa-sha2-nistp256")
+ store.trust(hostname: "host-a.com", port: 22, key: key(0x11), keyType: "ssh-rsa")
+ store.trust(hostname: "host-b.com", port: 22, key: key(0x22), keyType: "ssh-ed25519")
+
+ #expect(store.trustedHosts() == ["[host-a.com]:22", "[host-b.com]:22", "[host-c.com]:22"])
+ #expect(store.verify(keyData: key(0x11), keyType: "ssh-rsa", hostname: "host-a.com", port: 22) == .trusted)
+ #expect(store.verify(keyData: key(0x22), keyType: "ssh-ed25519", hostname: "host-b.com", port: 22) == .trusted)
+ #expect(store.verify(keyData: key(0x33), keyType: "ecdsa-sha2-nistp256", hostname: "host-c.com", port: 22) == .trusted)
+
+ store.remove(hostname: "host-b.com", port: 22)
+
+ #expect(store.trustedHosts() == ["[host-a.com]:22", "[host-c.com]:22"])
+ #expect(store.verify(keyData: key(0x11), keyType: "ssh-rsa", hostname: "host-a.com", port: 22) == .trusted)
+ #expect(store.verify(keyData: key(0x33), keyType: "ecdsa-sha2-nistp256", hostname: "host-c.com", port: 22) == .trusted)
+ }
+
+ @Test("The same host on another port is a separate entry")
+ func portsAreSeparateEntries() {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ let key22 = key(0x44)
+ let key2222 = key(0x55)
+
+ store.trust(hostname: "db.example.com", port: 22, key: key22, keyType: "ssh-rsa")
+ #expect(
+ store.verify(keyData: key22, keyType: "ssh-rsa", hostname: "db.example.com", port: 2_222)
+ == .unknown(fingerprint: HostKeyStore.fingerprint(of: key22), keyType: "ssh-rsa")
+ )
+
+ store.trust(hostname: "db.example.com", port: 2_222, key: key2222, keyType: "ssh-ed25519")
+
+ #expect(store.verify(keyData: key22, keyType: "ssh-rsa", hostname: "db.example.com", port: 22) == .trusted)
+ #expect(store.verify(keyData: key2222, keyType: "ssh-ed25519", hostname: "db.example.com", port: 2_222) == .trusted)
+ #expect(
+ store.verify(keyData: key22, keyType: "ssh-rsa", hostname: "db.example.com", port: 2_222)
+ == .mismatch(expected: HostKeyStore.fingerprint(of: key2222), actual: HostKeyStore.fingerprint(of: key22))
+ )
+ }
+
+ @Test("A saved key file that cannot be read checks no key and is never written over")
+ func unreadableFileChecksNothing() throws {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ store.trust(hostname: "db.example.com", port: 22, key: key(0x31), keyType: "ssh-ed25519")
+ let saved = try String(contentsOfFile: path, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: path)
+
+ #expect(store.verify(keyData: key(0x32), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .unreadable)
+ store.trust(hostname: "other.example.com", port: 22, key: key(0x33), keyType: "ssh-ed25519")
+ store.remove(hostname: "db.example.com", port: 22)
+
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)
+ #expect(try String(contentsOfFile: path, encoding: .utf8) == saved)
+ #expect(store.verify(keyData: key(0x31), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .trusted)
+ }
+
+ @Test("A saved line that cannot be parsed keeps its host from looking new, and stays in the file")
+ func unparsedLineIsKept() throws {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let unparsed = "[db.example.com]:22 ssh-ed25519 !!not-base64!!"
+ try (unparsed + "\n").write(toFile: path, atomically: true, encoding: .utf8)
+ let store = HostKeyStore(filePath: path)
+
+ #expect(store.verify(keyData: key(0x41), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .unreadable)
+ store.trust(hostname: "other.example.com", port: 22, key: key(0x42), keyType: "ssh-ed25519")
+
+ #expect(try String(contentsOfFile: path, encoding: .utf8).hasPrefix(unparsed + "\n"))
+ #expect(store.verify(keyData: key(0x42), keyType: "ssh-ed25519", hostname: "other.example.com", port: 22) == .trusted)
+ }
+
+ @Test("A host with a line break plants no key for another host", arguments: [
+ "replica.attacker.example\n[prod.corp.example",
+ "replica.attacker.example\r\n[prod.corp.example",
+ "replica.attacker.example [prod.corp.example",
+ ])
+ func lineBreakInHostPlantsNoEntry(hostile: String) {
+ let path = temporaryPath()
+ defer { try? FileManager.default.removeItem(atPath: path) }
+ let store = HostKeyStore(filePath: path)
+ let real = key(0x01)
+ let forged = key(0x02)
+ store.trust(hostname: "prod.corp.example", port: 22, key: real, keyType: "ssh-ed25519")
+
+ #expect(store.verify(keyData: forged, keyType: "ssh-ed25519", hostname: hostile, port: 22) == .invalidHost(.host(hostile)))
+ store.trust(hostname: hostile, port: 22, key: forged, keyType: "ssh-ed25519")
+
+ #expect(
+ store.verify(keyData: forged, keyType: "ssh-ed25519", hostname: "prod.corp.example", port: 22)
+ == .mismatch(expected: HostKeyStore.fingerprint(of: real), actual: HostKeyStore.fingerprint(of: forged))
+ )
+ #expect(store.verify(keyData: real, keyType: "ssh-ed25519", hostname: "prod.corp.example", port: 22) == .trusted)
+ }
+
+ @Test("Fingerprints use the OpenSSH SHA256 form, base64 without padding")
+ func fingerprintFormat() {
+ #expect(HostKeyStore.fingerprint(of: Data("tablepro".utf8)) == "SHA256:LFI08RUW/kZD9NjQQxyWL4XFlFJ2S/kXkoDufgqg10w")
+ #expect(HostKeyStore.fingerprint(of: key(0xFF, length: 64)) != HostKeyStore.fingerprint(of: key(0x00, length: 64)))
+ }
+
+ @Test("libssh2 key type constants map to OpenSSH key type names")
+ func keyTypeNames() {
+ #expect(HostKeyStore.keyTypeName(1) == "ssh-rsa")
+ #expect(HostKeyStore.keyTypeName(2) == "ssh-dss")
+ #expect(HostKeyStore.keyTypeName(3) == "ecdsa-sha2-nistp256")
+ #expect(HostKeyStore.keyTypeName(4) == "ecdsa-sha2-nistp384")
+ #expect(HostKeyStore.keyTypeName(5) == "ecdsa-sha2-nistp521")
+ #expect(HostKeyStore.keyTypeName(6) == "ssh-ed25519")
+ #expect(HostKeyStore.keyTypeName(0) == "unknown")
+ #expect(HostKeyStore.keyTypeName(99) == "unknown")
+ }
+}
diff --git a/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift b/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift
index 69b6a98efd..656b156340 100644
--- a/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift
+++ b/apple/Plugins/ClickHouseDriverPlugin/ClickHousePlugin.swift
@@ -26,6 +26,7 @@ nonisolated final class ClickHousePlugin: NSObject, TableProPlugin, DriverPlugin
// MARK: - UI/Capability Metadata
static let isDownloadable = true
+ static let urlSchemes: [String] = ["clickhouse", "ch"]
static let explainVariants: [ExplainVariant] = [
ExplainVariant(id: "plan", label: "Plan", sqlPrefix: "EXPLAIN", format: .indentedText),
ExplainVariant(id: "pipeline", label: "Pipeline", sqlPrefix: "EXPLAIN PIPELINE", format: .indentedText),
diff --git a/apple/Plugins/MSSQLDriverPlugin/MSSQLPlugin.swift b/apple/Plugins/MSSQLDriverPlugin/MSSQLPlugin.swift
index 30ea7331d0..56c86e1641 100644
--- a/apple/Plugins/MSSQLDriverPlugin/MSSQLPlugin.swift
+++ b/apple/Plugins/MSSQLDriverPlugin/MSSQLPlugin.swift
@@ -187,6 +187,7 @@ final class MSSQLPlugin: NSObject, TableProPlugin, DriverPlugin {
// MARK: - UI/Capability Metadata
static let supportsSchemaSwitching = true
+ static let urlSchemes: [String] = ["sqlserver", "mssql"]
static let postConnectActions: [PostConnectAction] = [.selectDatabaseFromLastSession, .selectSchemaFromLastSession]
static let brandColorHex = "#E34517"
static let systemDatabaseNames: [String] = ["master", "tempdb", "model", "msdb"]
diff --git a/apple/Plugins/OracleDriverPlugin/OraclePlugin.swift b/apple/Plugins/OracleDriverPlugin/OraclePlugin.swift
index ba529fd00f..9e5e01bf8e 100644
--- a/apple/Plugins/OracleDriverPlugin/OraclePlugin.swift
+++ b/apple/Plugins/OracleDriverPlugin/OraclePlugin.swift
@@ -104,6 +104,7 @@ final class OraclePlugin: NSObject, TableProPlugin, DriverPlugin, PluginDiagnost
// MARK: - UI/Capability Metadata
static let isDownloadable = true
+ static let urlSchemes: [String] = ["oracle"]
static let supportsTriggers = true
static let supportsRoutines = true
static let supportsDatabaseTriggerBrowse = true
diff --git a/apple/Plugins/PostgreSQLDriverPlugin/PostgreSQLDialect.swift b/apple/Plugins/PostgreSQLDriverPlugin/PostgreSQLDialect.swift
index 510f7ce268..76b153cba6 100644
--- a/apple/Plugins/PostgreSQLDriverPlugin/PostgreSQLDialect.swift
+++ b/apple/Plugins/PostgreSQLDriverPlugin/PostgreSQLDialect.swift
@@ -5,7 +5,7 @@ import TableProSQLVocabulary
enum PostgreSQLDialect {
static let descriptor = SQLDialectDescriptor(
identifierQuote: "\"",
- keywords: keywords,
+ keywords: SQLEngineVocabulary.postgreSQL.keywords,
functions: SQLEngineVocabulary.postgreSQL.functions,
dataTypes: SQLEngineVocabulary.postgreSQL.dataTypes,
tableOptions: SQLEngineVocabulary.postgreSQL.tableOptions,
@@ -19,108 +19,6 @@ enum PostgreSQLDialect {
functionNamesAreCaseInsensitive: SQLEngineVocabulary.postgreSQL.functionNamesAreCaseInsensitive,
typeNamesAreCaseInsensitive: true
)
-
- static let keywords: Set = reservedKeywords
- .union(nonReservedKeywords)
- .union(multiWordConstructs)
-
- private static let reservedKeywords: Set = [
- "ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "ASYMMETRIC", "BOTH",
- "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE", "CURRENT_CATALOG",
- "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER",
- "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE",
- "FETCH", "FOR", "FOREIGN", "FROM", "GRANT", "GROUP", "HAVING", "IN", "INITIALLY",
- "INTERSECT", "INTO", "LATERAL", "LEADING", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP",
- "NOT", "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", "PLACING", "PRIMARY", "REFERENCES",
- "RETURNING", "SELECT", "SESSION_USER", "SOME", "SYMMETRIC", "SYSTEM_USER", "TABLE",
- "THEN", "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC",
- "WHEN", "WHERE", "WINDOW", "WITH",
- "AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS", "CURRENT_SCHEMA",
- "FREEZE", "FULL", "ILIKE", "INNER", "IS", "ISNULL", "JOIN", "LEFT", "LIKE", "NATURAL",
- "NOTNULL", "OUTER", "OVERLAPS", "RIGHT", "SIMILAR", "TABLESAMPLE", "VERBOSE"
- ]
-
- private static let nonReservedKeywords: Set = [
- "ABORT", "ABSENT", "ABSOLUTE", "ACCESS", "ACTION", "ADD", "ADMIN", "AFTER", "AGGREGATE",
- "ALTER", "ALWAYS", "AT", "ATOMIC", "ATTACH", "ATTRIBUTE", "BACKWARD", "BEFORE", "BEGIN",
- "BREADTH", "BY", "CACHE", "CALL", "CALLED", "CASCADE", "CASCADED", "CHAIN",
- "CHARACTERISTICS", "CHECKPOINT", "CLASS", "CLOSE", "CLUSTER", "COLUMNS", "COMMENT",
- "COMMENTS", "COMMIT", "COMMITTED", "COMPRESSION", "CONDITIONAL", "CONFIGURATION",
- "CONFLICT", "CONNECTION", "CONSTRAINTS", "CONTENT", "CONTINUE", "CONVERSION", "COPY",
- "COST", "CSV", "CUBE", "CURRENT", "CURSOR", "CYCLE", "DATA", "DATABASE", "DAY",
- "DEALLOCATE", "DECLARE", "DEFAULTS", "DEFERRED", "DEFINER", "DELETE", "DELIMITER",
- "DELIMITERS", "DEPENDS", "DEPTH", "DETACH", "DICTIONARY", "DISABLE", "DISCARD",
- "DOCUMENT", "DOMAIN", "DOUBLE", "DROP", "EACH", "EMPTY", "ENABLE", "ENCODING",
- "ENCRYPTED", "ENUM", "ERROR", "ESCAPE", "EVENT", "EXCLUDE", "EXCLUDING", "EXCLUSIVE",
- "EXECUTE", "EXPLAIN", "EXPRESSION", "EXTENSION", "EXTERNAL", "FAMILY", "FILTER",
- "FINALIZE", "FIRST", "FOLLOWING", "FORCE", "FORMAT", "FORWARD", "FUNCTION", "FUNCTIONS",
- "GENERATED", "GLOBAL", "GRANTED", "GROUPS", "HANDLER", "HEADER", "HOLD", "HOUR",
- "IDENTITY", "IF", "IMMEDIATE", "IMMUTABLE", "IMPLICIT", "IMPORT", "INCLUDE", "INCLUDING",
- "INCREMENT", "INDENT", "INDEX", "INDEXES", "INHERIT", "INHERITS", "INPUT", "INSENSITIVE",
- "INSERT", "INSTEAD", "INVOKER", "ISOLATION", "KEEP", "KEY", "KEYS", "LABEL", "LANGUAGE",
- "LARGE", "LAST", "LEAKPROOF", "LEVEL", "LISTEN", "LOAD", "LOCAL", "LOCATION", "LOCK",
- "LOCKED", "LOGGED", "MAPPING", "MATCH", "MATCHED", "MATERIALIZED", "MAXVALUE", "MERGE",
- "METHOD", "MINUTE", "MINVALUE", "MODE", "MONTH", "MOVE", "NAME", "NAMES", "NESTED",
- "NEW", "NEXT", "NO", "NORMALIZED", "NOTHING", "NOTIFY", "NOWAIT", "NULLS", "OBJECT",
- "OF", "OFF", "OLD", "OMIT", "OPERATOR", "OPTION", "OPTIONS", "ORDINALITY", "OTHERS",
- "OVER", "OVERRIDING", "OWNED", "OWNER", "PARALLEL", "PARAMETER", "PARSER", "PARTIAL",
- "PARTITION", "PASSING", "PASSWORD", "PATH", "POLICY", "PRECEDING", "PREPARE", "PREPARED",
- "PRESERVE", "PRIOR", "PRIVILEGES", "PROCEDURE", "PROCEDURES", "PROGRAM", "PUBLICATION",
- "QUOTE", "QUOTES", "RANGE", "READ", "REASSIGN", "RECURSIVE", "REFERENCING", "REFRESH",
- "REINDEX", "RELATIVE", "RELEASE", "RENAME", "REPEATABLE", "REPLACE", "REPLICA", "RESET",
- "RESTART", "RESTRICT", "RETURN", "RETURNS", "REVOKE", "ROLE", "ROLLBACK", "ROLLUP",
- "ROUTINE", "ROUTINES", "ROWS", "RULE", "SAVEPOINT", "SCALAR", "SCHEMA", "SCHEMAS",
- "SCROLL", "SEARCH", "SECOND", "SECURITY", "SEQUENCE", "SEQUENCES", "SERIALIZABLE",
- "SERVER", "SESSION", "SET", "SETS", "SHARE", "SHOW", "SIMPLE", "SKIP", "SNAPSHOT",
- "SOURCE", "SQL", "STABLE", "STANDALONE", "START", "STATEMENT", "STATISTICS", "STDIN",
- "STDOUT", "STORAGE", "STORED", "STRICT", "STRING", "STRIP", "SUBSCRIPTION", "SUPPORT",
- "SYSTEM", "TABLES", "TABLESPACE", "TARGET", "TEMP", "TEMPLATE", "TEMPORARY", "TEXT",
- "TIES", "TRANSACTION", "TRANSFORM", "TRIGGER", "TRUNCATE", "TRUSTED", "TYPE", "TYPES",
- "UNBOUNDED", "UNCOMMITTED", "UNCONDITIONAL", "UNENCRYPTED", "UNKNOWN", "UNLISTEN",
- "UNLOGGED", "UNTIL", "UPDATE", "VACUUM", "VALID", "VALIDATE", "VALIDATOR", "VALUE",
- "VARYING", "VERSION", "VIEW", "VIEWS", "VOLATILE", "WHITESPACE", "WITHIN", "WITHOUT",
- "WORK", "WRAPPER", "WRITE", "XML", "YEAR", "YES", "ZONE",
- "BETWEEN", "COALESCE", "EXISTS", "GREATEST", "GROUPING", "LEAST", "MERGE_ACTION",
- "NULLIF", "OVERLAY", "POSITION", "SETOF", "SUBSTRING", "TREAT", "TRIM", "VALUES"
- ]
-
- private static let multiWordConstructs: Set = [
- "ON CONFLICT", "ON CONFLICT DO NOTHING", "ON CONFLICT DO UPDATE SET", "ON CONSTRAINT",
- "DO NOTHING", "DO UPDATE SET", "DEFAULT VALUES", "OVERRIDING SYSTEM VALUE",
- "OVERRIDING USER VALUE", "RETURNING *",
- "SELECT DISTINCT", "SELECT DISTINCT ON", "DISTINCT ON", "GROUP BY", "GROUP BY ALL",
- "GROUP BY DISTINCT", "GROUPING SETS", "ORDER BY", "NULLS FIRST", "NULLS LAST",
- "UNION ALL", "UNION DISTINCT", "INTERSECT ALL", "EXCEPT ALL", "LIMIT ALL",
- "FETCH FIRST", "FETCH NEXT", "WITH TIES", "FOR UPDATE", "FOR NO KEY UPDATE",
- "FOR SHARE", "FOR KEY SHARE", "SKIP LOCKED", "TABLESAMPLE SYSTEM",
- "TABLESAMPLE BERNOULLI", "WITH ORDINALITY", "ROWS FROM",
- "INNER JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "RIGHT JOIN", "RIGHT OUTER JOIN",
- "FULL JOIN", "FULL OUTER JOIN", "CROSS JOIN", "NATURAL JOIN",
- "WITH RECURSIVE", "AS MATERIALIZED", "AS NOT MATERIALIZED",
- "SEARCH BREADTH FIRST BY", "SEARCH DEPTH FIRST BY",
- "CREATE TABLE IF NOT EXISTS", "CREATE TEMP TABLE", "CREATE UNLOGGED TABLE",
- "NOT NULL", "PRIMARY KEY", "FOREIGN KEY", "UNIQUE NULLS DISTINCT",
- "UNIQUE NULLS NOT DISTINCT", "GENERATED ALWAYS AS", "GENERATED ALWAYS AS IDENTITY",
- "GENERATED BY DEFAULT AS IDENTITY", "MATCH FULL", "MATCH PARTIAL", "MATCH SIMPLE",
- "ON DELETE CASCADE", "ON DELETE RESTRICT", "ON DELETE SET NULL", "ON DELETE NO ACTION",
- "ON UPDATE CASCADE", "ON UPDATE RESTRICT", "ON UPDATE SET NULL",
- "DEFERRABLE INITIALLY DEFERRED", "INITIALLY IMMEDIATE", "EXCLUDE USING",
- "PARTITION BY RANGE", "PARTITION BY LIST", "PARTITION BY HASH", "PARTITION OF",
- "FOR VALUES IN", "FOR VALUES FROM", "FOR VALUES WITH",
- "ON COMMIT PRESERVE ROWS", "ON COMMIT DELETE ROWS", "ON COMMIT DROP",
- "OVER", "PARTITION BY", "FILTER", "WITHIN GROUP", "ROWS BETWEEN", "RANGE BETWEEN",
- "GROUPS BETWEEN", "UNBOUNDED PRECEDING", "UNBOUNDED FOLLOWING", "CURRENT ROW",
- "EXCLUDE CURRENT ROW", "EXCLUDE GROUP", "EXCLUDE TIES", "EXCLUDE NO OTHERS",
- "MERGE INTO", "WHEN MATCHED THEN", "WHEN MATCHED THEN UPDATE SET",
- "WHEN MATCHED THEN DELETE", "WHEN NOT MATCHED THEN INSERT",
- "WHEN NOT MATCHED BY TARGET THEN", "WHEN NOT MATCHED BY SOURCE THEN",
- "CREATE INDEX CONCURRENTLY", "CREATE MATERIALIZED VIEW", "REFRESH MATERIALIZED VIEW",
- "CREATE TYPE", "CREATE EXTENSION", "IF NOT EXISTS", "IF EXISTS", "CASCADE", "RESTRICT",
- "IS NULL", "IS NOT NULL", "IS TRUE", "IS NOT TRUE", "IS FALSE", "IS NOT FALSE",
- "IS UNKNOWN", "IS NOT UNKNOWN", "IS DISTINCT FROM", "IS NOT DISTINCT FROM",
- "BETWEEN SYMMETRIC", "NOT BETWEEN", "NOT BETWEEN SYMMETRIC", "NOT LIKE", "NOT ILIKE",
- "SIMILAR TO", "NOT SIMILAR TO", "AT TIME ZONE", "AT LOCAL"
- ]
}
private extension SQLOperatorDescriptor {
diff --git a/apple/Plugins/RedisDriverPlugin/RedisPlugin.swift b/apple/Plugins/RedisDriverPlugin/RedisPlugin.swift
index aa0d4cb71f..7ef4cb818d 100644
--- a/apple/Plugins/RedisDriverPlugin/RedisPlugin.swift
+++ b/apple/Plugins/RedisDriverPlugin/RedisPlugin.swift
@@ -116,7 +116,7 @@ final class RedisPlugin: NSObject, TableProPlugin, DriverPlugin {
static let pathFieldRole: PathFieldRole = .databaseIndex
static let postConnectActions: [PostConnectAction] = [.selectDatabaseFromConnectionField(fieldId: "redisDatabase")]
static let requiresAuthentication = false
- static let urlSchemes: [String] = ["redis"]
+ static let urlSchemes: [String] = ["redis", "rediss"]
static let brandColorHex = "#DC382D"
static let queryLanguageName = "Redis CLI"
static let editorLanguage: EditorLanguage = .bash
diff --git a/apple/Plugins/SurrealDBDriverPlugin/SurrealDBPlugin.swift b/apple/Plugins/SurrealDBDriverPlugin/SurrealDBPlugin.swift
index 48e498e8f5..85731fcdd9 100644
--- a/apple/Plugins/SurrealDBDriverPlugin/SurrealDBPlugin.swift
+++ b/apple/Plugins/SurrealDBDriverPlugin/SurrealDBPlugin.swift
@@ -63,6 +63,23 @@ final class SurrealDBPlugin: NSObject, TableProPlugin, DriverPlugin {
"Structured": ["object", "array", "set", "geometry", "record", "any"]
]
+ static let statementCompletions: [CompletionEntry] = [
+ CompletionEntry(label: "SELECT", insertText: "SELECT * FROM table LIMIT 100"),
+ CompletionEntry(label: "CREATE", insertText: "CREATE table SET field = value"),
+ CompletionEntry(label: "UPDATE", insertText: "UPDATE table:id SET field = value"),
+ CompletionEntry(label: "UPSERT", insertText: "UPSERT table:id SET field = value"),
+ CompletionEntry(label: "DELETE", insertText: "DELETE table:id"),
+ CompletionEntry(label: "RELATE", insertText: "RELATE from:id->edge->to:id SET field = value"),
+ CompletionEntry(label: "USE", insertText: "USE NS namespace DB database"),
+ CompletionEntry(label: "INFO FOR DB", insertText: "INFO FOR DB"),
+ CompletionEntry(label: "INFO FOR TABLE", insertText: "INFO FOR TABLE table"),
+ CompletionEntry(label: "DEFINE TABLE", insertText: "DEFINE TABLE table SCHEMAFULL"),
+ CompletionEntry(label: "DEFINE FIELD", insertText: "DEFINE FIELD field ON table TYPE string"),
+ CompletionEntry(label: "DEFINE INDEX", insertText: "DEFINE INDEX name ON table FIELDS field UNIQUE"),
+ CompletionEntry(label: "REMOVE TABLE", insertText: "REMOVE TABLE table"),
+ CompletionEntry(label: "count", insertText: "SELECT count() AS total FROM table GROUP ALL"),
+ ]
+
static let sqlDialect: SQLDialectDescriptor? = SQLDialectDescriptor(
identifierQuote: "`",
keywords: [
diff --git a/apple/Plugins/TeradataDriverPlugin/TeradataPlugin.swift b/apple/Plugins/TeradataDriverPlugin/TeradataPlugin.swift
index f3c5c8b7ac..e47e599d65 100644
--- a/apple/Plugins/TeradataDriverPlugin/TeradataPlugin.swift
+++ b/apple/Plugins/TeradataDriverPlugin/TeradataPlugin.swift
@@ -54,6 +54,7 @@ final class TeradataPlugin: NSObject, TableProPlugin, DriverPlugin {
]
static let brandColorHex = "#F37440"
+ static let urlSchemes: [String] = ["teradata"]
static let queryLanguageName = "SQL"
static let supportsDatabaseSwitching = true
static let supportsSchemaSwitching = false
diff --git a/apple/Plugins/TrinoDriverPlugin/TrinoPlugin.swift b/apple/Plugins/TrinoDriverPlugin/TrinoPlugin.swift
index 053c4ee98d..923849cdcd 100644
--- a/apple/Plugins/TrinoDriverPlugin/TrinoPlugin.swift
+++ b/apple/Plugins/TrinoDriverPlugin/TrinoPlugin.swift
@@ -20,6 +20,7 @@ final class TrinoPlugin: NSObject, TableProPlugin, DriverPlugin {
static let isDownloadable = true
static let connectionMode: ConnectionMode = .network
+ static let urlSchemes: [String] = ["trino"]
static let pathFieldRole: PathFieldRole = .database
static let requiresAuthentication = false
static let brandColorHex = "#DD5F3B"
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+BigtableDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+BigtableDefaults.swift
index 87a4fba493..4edc496b88 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+BigtableDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+BigtableDefaults.swift
@@ -10,7 +10,7 @@ extension PluginMetadataRegistry {
("Bigtable", PluginMetadataSnapshot(
displayName: "Google Cloud Bigtable", iconName: "bigtable-icon", defaultPort: 0,
requiresAuthentication: true, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "bigtable", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#4285F4",
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CloudDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CloudDefaults.swift
index eac5b9dcdd..aa7f6fa2c2 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CloudDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CloudDefaults.swift
@@ -13,7 +13,7 @@ extension PluginMetadataRegistry {
("DynamoDB", PluginMetadataSnapshot(
displayName: "Amazon DynamoDB", iconName: "dynamodb-icon", defaultPort: 0,
requiresAuthentication: true, supportsForeignKeys: false, supportsSchemaEditing: true,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "dynamodb", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [],
pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
@@ -43,7 +43,7 @@ extension PluginMetadataRegistry {
supportsRawFilter: false
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "main",
tableEntityName: "Tables",
containerEntityName: "Database",
@@ -70,7 +70,7 @@ extension PluginMetadataRegistry {
("BigQuery", PluginMetadataSnapshot(
displayName: "Google BigQuery", iconName: "bigquery-icon", defaultPort: 0,
requiresAuthentication: true, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "bigquery", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [
ExplainVariant(id: "dryrun", label: "Dry Run (Cost)", sqlPrefix: "EXPLAIN")
],
@@ -91,7 +91,10 @@ extension PluginMetadataRegistry {
supportsReadOnlyMode: true,
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
- supportsDropDatabase: true
+ supportsDropDatabase: true,
+ supportsRenameTable: true,
+ supportsRenameView: true,
+ supportsRoutines: true
),
schema: PluginMetadataSnapshot.SchemaInfo(
defaultSchemaName: "",
@@ -272,7 +275,7 @@ extension PluginMetadataRegistry {
("Spanner", PluginMetadataSnapshot(
displayName: "Google Cloud Spanner", iconName: "spanner-icon", defaultPort: 0,
requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "spanner", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [
ExplainVariant(id: "plan", label: "Plan", sqlPrefix: "EXPLAIN", format: .indentedText)
],
@@ -464,7 +467,7 @@ extension PluginMetadataRegistry {
("Snowflake", PluginMetadataSnapshot(
displayName: "Snowflake", iconName: "snowflake-icon", defaultPort: 443,
requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: true,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "snowflake", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [
ExplainVariant(id: "text", label: "Explain (Text)", sqlPrefix: "EXPLAIN USING TEXT")
],
@@ -486,6 +489,13 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: true,
+ supportsRenameTable: true,
+ supportsRenameView: true,
+ supportsRenameSchema: true,
+ supportsRenameColumn: true,
+ supportsAddIndex: false,
+ supportsDropIndex: false,
+ supportsRoutines: true,
pooledDriversShareOneSession: true
),
schema: PluginMetadataSnapshot.SchemaInfo(
@@ -660,7 +670,8 @@ extension PluginMetadataRegistry {
CompletionEntry(label: "ZEROIFNULL", insertText: "ZEROIFNULL"),
CompletionEntry(label: "IFF", insertText: "IFF"),
CompletionEntry(label: "NVL", insertText: "NVL"),
- CompletionEntry(label: "DECODE", insertText: "DECODE")
+ CompletionEntry(label: "DECODE", insertText: "DECODE"),
+ CompletionEntry(label: "CREATE TABLE", insertText: "CREATE TABLE")
],
columnTypesByCategory: [
"Number": ["NUMBER", "DECIMAL", "INT", "INTEGER", "BIGINT", "SMALLINT", "FLOAT", "DOUBLE", "REAL"],
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift
index 8f2bbbe41e..86051ceb74 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift
@@ -74,22 +74,7 @@ extension PluginMetadataRegistry {
let postgresqlDialect = SQLDialectDescriptor(
identifierQuote: "\"",
- keywords: [
- "SELECT", "FROM", "WHERE", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER", "CROSS", "FULL",
- "ON", "USING", "AND", "OR", "NOT", "IN", "LIKE", "ILIKE", "BETWEEN", "AS",
- "ORDER", "BY", "GROUP", "HAVING", "LIMIT", "OFFSET", "FETCH", "FIRST", "ROWS", "ONLY",
- "INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE",
- "CREATE", "ALTER", "DROP", "TABLE", "INDEX", "VIEW", "DATABASE", "SCHEMA",
- "PRIMARY", "KEY", "FOREIGN", "REFERENCES", "UNIQUE", "CONSTRAINT",
- "ADD", "MODIFY", "COLUMN", "RENAME",
- "NULL", "IS", "ASC", "DESC", "DISTINCT", "ALL", "ANY", "SOME",
- "CASE", "WHEN", "THEN", "ELSE", "END", "COALESCE", "NULLIF",
- "UNION", "INTERSECT", "EXCEPT",
- "RETURNING", "WITH", "RECURSIVE", "MATERIALIZED",
- "EXPLAIN", "ANALYZE", "VERBOSE",
- "WINDOW", "OVER", "PARTITION",
- "LATERAL", "ORDINALITY"
- ],
+ keywords: SQLEngineVocabulary.postgreSQL.keywords,
functions: SQLEngineVocabulary.postgreSQL.functions,
dataTypes: SQLEngineVocabulary.postgreSQL.dataTypes,
tableOptions: SQLEngineVocabulary.postgreSQL.tableOptions,
@@ -99,7 +84,7 @@ extension PluginMetadataRegistry {
paginationStyle: .limit,
caseSensitivityStyle: .ilikeOperator,
operators: SQLEngineVocabulary.postgreSQL.operators.compactMap(SQLOperatorDescriptor.init(vocabulary:)),
- textCastTypeName: nil,
+ textCastTypeName: "TEXT",
functionNamesAreCaseInsensitive: SQLEngineVocabulary.postgreSQL.functionNamesAreCaseInsensitive,
typeNamesAreCaseInsensitive: true
)
@@ -255,7 +240,6 @@ extension PluginMetadataRegistry {
supportsRenameView: true,
supportsRenameDatabase: false,
supportsRenameSchema: false,
- supportsRenameColumn: true,
supportsTriggers: true,
supportsTriggerEditing: true,
supportsCheckConstraints: true,
@@ -406,7 +390,6 @@ extension PluginMetadataRegistry {
supportsCreateSchema: true,
supportsSchemaOwner: true,
supportsSchemaPrivileges: true,
- supportsRenameColumn: true,
supportsTriggers: true,
supportsTriggerEditing: true,
supportsCheckConstraints: true,
@@ -442,7 +425,7 @@ extension PluginMetadataRegistry {
columnTypesByCategory: postgresqlColumnTypes
),
connection: PluginMetadataSnapshot.ConnectionConfig(
- additionalConnectionFields: [pgpassField, connectionOptionsField] + postgresqlAuthFields,
+ additionalConnectionFields: [pgpassField] + postgresqlAuthFields + [connectionOptionsField],
category: .relational,
tagline: String(localized: "Advanced object-relational SQL"),
defaultUnixSocketPath: "/var/run/postgresql/.s.PGSQL.5432",
@@ -687,12 +670,11 @@ extension PluginMetadataRegistry {
supportsRenameView: false,
supportsRenameDatabase: false,
supportsRenameSchema: false,
- supportsModifyColumn: false,
- supportsRenameColumn: true,
- supportsModifyPrimaryKey: false,
supportsTriggers: true,
supportsTriggerEditing: true,
supportsCheckConstraints: true,
+ // The plugin's SQLite (scripts/build-sqlite.sh) is 3.53 or later, which edits CHECK constraints.
+ supportsCheckConstraintEditing: true,
supportsGeneratedColumns: true,
supportsDatabaseTriggerBrowse: true,
localFilePathField: .database,
@@ -714,8 +696,7 @@ extension PluginMetadataRegistry {
fileSignatures: [.magic("SQLite format 3\u{0}")],
databaseGroupingStrategy: .flat,
structureColumnFields: [
- .name, .type, .nullable, .defaultValue, .generated, .generationExpression,
- .autoIncrement, .comment
+ .name, .type, .nullable, .defaultValue, .generated, .generationExpression, .autoIncrement
]
),
editor: PluginMetadataSnapshot.EditorConfig(
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+DuckDBDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+DuckDBDefaults.swift
index 6e29479517..ceb7052f3d 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+DuckDBDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+DuckDBDefaults.swift
@@ -42,7 +42,9 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
- supportsRenameColumn: true,
+ supportsRenameTable: true,
+ supportsRenameView: true,
+ supportsRoutines: true,
// httpfs checks a server against the system CA bundle when no CA is given, so a URL asking
// for TLS with no mode means a verified connection, never Required's unchecked one.
verifiesServerWithSystemTrust: true,
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+ElasticsearchDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+ElasticsearchDefaults.swift
index 8335a590d7..abe6c1b132 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+ElasticsearchDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+ElasticsearchDefaults.swift
@@ -12,7 +12,7 @@ extension PluginMetadataRegistry {
("Elasticsearch", PluginMetadataSnapshot(
displayName: "Elasticsearch", iconName: "elasticsearch-icon", defaultPort: 9_200,
requiresAuthentication: false, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "elasticsearch", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#FEC514",
@@ -30,15 +30,21 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
+ supportsAddColumn: false,
+ supportsModifyColumn: false,
+ supportsDropColumn: false,
+ supportsAddIndex: false,
+ supportsDropIndex: false,
+ supportsModifyPrimaryKey: false,
supportsOpportunisticTLS: false,
dataCommands: elasticsearchDataCommands
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "default",
tableEntityName: "Indices",
containerEntityName: "Cluster",
- defaultPrimaryKeyColumn: "_id",
+ defaultPrimaryKeyColumn: nil,
immutableColumns: ["_id", "_index", "_score"],
systemDatabaseNames: [],
systemSchemaNames: [],
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+FirebaseDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+FirebaseDefaults.swift
index aac3f6a0e0..0ecb392660 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+FirebaseDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+FirebaseDefaults.swift
@@ -9,7 +9,7 @@ extension PluginMetadataRegistry {
("Firestore", PluginMetadataSnapshot(
displayName: "Cloud Firestore", iconName: "firebase-icon", defaultPort: 0,
requiresAuthentication: true, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "firestore", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#FFA000",
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+InfluxDBDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+InfluxDBDefaults.swift
index 1d53334883..47f6c33de9 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+InfluxDBDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+InfluxDBDefaults.swift
@@ -8,7 +8,7 @@ extension PluginMetadataRegistry {
("InfluxDB", PluginMetadataSnapshot(
displayName: "InfluxDB", iconName: "influxdb-icon", defaultPort: 8_086,
requiresAuthentication: false, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "influxdb", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#22ADF6",
@@ -37,7 +37,7 @@ extension PluginMetadataRegistry {
supportsPrincipalConnectionLimit: false
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "default",
tableEntityName: "Measurements",
containerEntityName: "Database",
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KafkaDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KafkaDefaults.swift
index 57d569afc9..c57f0c4aaa 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KafkaDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KafkaDefaults.swift
@@ -38,6 +38,12 @@ extension PluginMetadataRegistry {
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
supportsDropSchema: false,
+ supportsAddColumn: false,
+ supportsModifyColumn: false,
+ supportsDropColumn: false,
+ supportsAddIndex: false,
+ supportsDropIndex: false,
+ supportsModifyPrimaryKey: false,
defaultSSLMode: .disabled,
supportsOpportunisticTLS: false,
verifiesServerWithSystemTrust: true,
@@ -80,9 +86,16 @@ private let kafkaCompletions: [CompletionEntry] = [
CompletionEntry(label: "CONSUME", insertText: "CONSUME \"topic\" FROM NEWEST LIMIT 100"),
CompletionEntry(label: "CONSUME FROM OLDEST", insertText: "CONSUME \"topic\" FROM OLDEST LIMIT 100"),
CompletionEntry(label: "CONSUME FROM OFFSET", insertText: "CONSUME \"topic\" FROM OFFSET 0 LIMIT 100"),
+ CompletionEntry(
+ label: "CONSUME FROM TIME",
+ insertText: "CONSUME \"topic\" FROM TIME \"2026-01-01T00:00:00Z\" LIMIT 100"
+ ),
+ CompletionEntry(label: "CONSUME PARTITION", insertText: "CONSUME \"topic\" PARTITION (0) FROM NEWEST LIMIT 100"),
CompletionEntry(label: "PRODUCE", insertText: "PRODUCE INTO \"topic\" KEY \"k\" VALUE \"v\""),
CompletionEntry(label: "SHOW TOPICS", insertText: "SHOW TOPICS"),
+ CompletionEntry(label: "SHOW BROKERS", insertText: "SHOW BROKERS"),
CompletionEntry(label: "SHOW GROUPS", insertText: "SHOW GROUPS"),
+ CompletionEntry(label: "SHOW CLUSTER", insertText: "SHOW CLUSTER"),
CompletionEntry(label: "DESCRIBE GROUP", insertText: "DESCRIBE GROUP \"group\""),
CompletionEntry(label: "DESCRIBE TOPIC", insertText: "DESCRIBE TOPIC \"topic\"")
]
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift
index 7e42690355..04b2757831 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+KingbaseESDefaults.swift
@@ -31,8 +31,15 @@ extension PluginMetadataRegistry {
capabilities: postgreSQL.capabilities, schema: postgreSQL.schema, editor: postgreSQL.editor,
connection: PluginMetadataSnapshot.ConnectionConfig(
additionalConnectionFields: postgreSQL.connection.additionalConnectionFields.filter {
- ["usePgpass", "connectionOptions"].contains($0.id)
- },
+ $0.id == "usePgpass"
+ } + [
+ ConnectionField(
+ id: "connectionOptions",
+ label: String(localized: "Connection Options"),
+ fieldType: .text,
+ section: .advanced
+ )
+ ],
category: .relational,
tagline: String(localized: "PostgreSQL and Oracle compatible SQL")
)
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+MemcachedDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+MemcachedDefaults.swift
index 1d58c1df50..eeba63f122 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+MemcachedDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+MemcachedDefaults.swift
@@ -32,12 +32,12 @@ extension PluginMetadataRegistry {
dataCommands: memcachedDataCommands
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "default",
tableEntityName: "Keys",
containerEntityName: "Server",
defaultPrimaryKeyColumn: "Key",
- immutableColumns: ["Key"],
+ immutableColumns: [],
systemDatabaseNames: [],
systemSchemaNames: [],
fileExtensions: [],
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+OracleSystemSchemas.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+OracleSystemSchemas.swift
index e420806f98..f1d4c0ada1 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+OracleSystemSchemas.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+OracleSystemSchemas.swift
@@ -6,17 +6,16 @@
import Foundation
extension PluginMetadataRegistry {
- /// The schemas Oracle creates and maintains itself. The core is the `ORACLE_MAINTAINED = 'Y'` set measured from
- /// `ALL_USERS` on Oracle AI Database 26ai Free; the rest are the predefined accounts the 19c and 11.2 Security
- /// Guides list for options that image leaves out, since `ORACLE_MAINTAINED` only exists from 12.1.0.2. Schemas
- /// named with a release number, such as `APEX_240200`, cannot be listed by name.
+ // ORACLE_MAINTAINED on 26ai Free plus the 19c and 11.2 predefined accounts; APEX_240200-style names can't be listed.
+ // OraclePlugin's seven lead, in its order, since registration puts a plugin's names before the curated ones.
static let oracleSystemSchemaNames: [String] = [
- "ANONYMOUS", "APEX_PUBLIC_USER", "APPQOSSYS", "ASMSNMP", "AUDSYS", "BAASSYS", "CTXSYS",
- "DBSFWUSER", "DBSNMP", "DGPDB_INT", "DIP", "DVF", "DVSYS", "EXFSYS", "FLOWS_FILES",
+ "SYS", "SYSTEM", "OUTLN", "DBSNMP", "APPQOSSYS", "WMSYS", "XDB",
+ "ANONYMOUS", "APEX_PUBLIC_USER", "ASMSNMP", "AUDSYS", "BAASSYS", "CTXSYS",
+ "DBSFWUSER", "DGPDB_INT", "DIP", "DVF", "DVSYS", "EXFSYS", "FLOWS_FILES",
"GGSHAREDCAP", "GGSYS", "GSMADMIN_INTERNAL", "GSMCATUSER", "GSMROOTUSER", "GSMUSER", "LBACSYS",
"MDDATA", "MDSYS", "MGMT_VIEW", "OJVMSYS", "OLAPSYS", "ORACLE_OCM", "ORDDATA", "ORDPLUGINS",
- "ORDSYS", "OUTLN", "OWBSYS", "REMOTE_SCHEDULER_AGENT", "SI_INFORMTN_SCHEMA", "SPATIAL_CSW_ADMIN_USR",
- "SPATIAL_WFS_ADMIN_USR", "SYS", "SYS$UMF", "SYSBACKUP", "SYSDG", "SYSKM", "SYSMAN", "SYSRAC",
- "SYSTEM", "VECSYS", "WKPROXY", "WKSYS", "WK_TEST", "WMSYS", "XDB", "XS$NULL"
+ "ORDSYS", "OWBSYS", "REMOTE_SCHEDULER_AGENT", "SI_INFORMTN_SCHEMA", "SPATIAL_CSW_ADMIN_USR",
+ "SPATIAL_WFS_ADMIN_USR", "SYS$UMF", "SYSBACKUP", "SYSDG", "SYSKM", "SYSMAN", "SYSRAC",
+ "VECSYS", "WKPROXY", "WKSYS", "WK_TEST", "XS$NULL"
]
}
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+QdrantDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+QdrantDefaults.swift
index 162405890a..1c623aab6b 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+QdrantDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+QdrantDefaults.swift
@@ -7,7 +7,7 @@ extension PluginMetadataRegistry {
("Qdrant", PluginMetadataSnapshot(
displayName: "Qdrant", iconName: "qdrant-icon", defaultPort: 6_333,
requiresAuthentication: false, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "qdrant", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#DC244C",
@@ -39,7 +39,7 @@ extension PluginMetadataRegistry {
dataCommands: qdrantDataCommands
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "default",
tableEntityName: "Collections",
containerEntityName: "Cluster",
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+R2SQLDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+R2SQLDefaults.swift
index 4aeb4672bf..0d340bf4a1 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+R2SQLDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+R2SQLDefaults.swift
@@ -12,7 +12,7 @@ extension PluginMetadataRegistry {
("Cloudflare R2 SQL", PluginMetadataSnapshot(
displayName: "Cloudflare R2 SQL", iconName: "cloudflare-r2-sql-icon", defaultPort: 0,
requiresAuthentication: true, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "cloudflare r2 sql", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: r2SQLExplainVariants,
pathFieldRole: .database,
supportsHealthMonitor: false, urlSchemes: [],
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryDefaults.swift
index 584ebcece6..32954a8b4b 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryDefaults.swift
@@ -67,6 +67,7 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: true,
+ supportsRenameTable: true,
supportsDocumentEditing: true,
supportsFieldRemoval: true,
supportsAddColumn: false,
@@ -112,13 +113,6 @@ extension PluginMetadataRegistry {
ConnectionField(
id: "mongoAuthSource", label: "Auth Database", placeholder: "admin"
),
- ConnectionField(
- id: "mongoAWSSessionToken",
- label: "AWS Session Token",
- fieldType: .secure,
- section: .authentication,
- visibleWhen: FieldVisibilityRule(fieldId: "mongoAuthMechanism", values: ["MONGODB-AWS"])
- ),
ConnectionField(
id: "mongoReadPreference",
label: "Read Preference",
@@ -142,6 +136,37 @@ extension PluginMetadataRegistry {
.init(value: "3", label: "3")
])
),
+ ConnectionField(
+ id: "mongoUseSrv",
+ label: "Use SRV Record",
+ defaultValue: "false",
+ fieldType: .toggle,
+ section: .advanced
+ ),
+ ConnectionField(
+ id: "mongoAuthMechanism",
+ label: "Auth Mechanism",
+ fieldType: .dropdown(options: [
+ .init(value: "", label: "Default"),
+ .init(value: "SCRAM-SHA-1", label: "SCRAM-SHA-1"),
+ .init(value: "SCRAM-SHA-256", label: "SCRAM-SHA-256"),
+ .init(value: "MONGODB-X509", label: "X.509"),
+ .init(value: "MONGODB-AWS", label: "AWS IAM")
+ ]),
+ section: .authentication
+ ),
+ ConnectionField(
+ id: "mongoAWSSessionToken",
+ label: "AWS Session Token",
+ fieldType: .secure,
+ section: .authentication,
+ visibleWhen: FieldVisibilityRule(fieldId: "mongoAuthMechanism", values: ["MONGODB-AWS"])
+ ),
+ ConnectionField(
+ id: "mongoReplicaSet",
+ label: "Replica Set",
+ section: .advanced
+ ),
ConnectionField(
id: "mongoUuidRepresentation",
label: String(localized: "Legacy UUID Encoding"),
@@ -188,10 +213,10 @@ extension PluginMetadataRegistry {
schema: PluginMetadataSnapshot.SchemaInfo(
defaultSchemaName: "public",
defaultGroupName: "db0",
- tableEntityName: "Keys",
+ tableEntityName: "Databases",
containerEntityName: "Database",
defaultPrimaryKeyColumn: "Key",
- immutableColumns: ["Length"],
+ immutableColumns: [],
systemDatabaseNames: [],
systemSchemaNames: [],
fileExtensions: [],
@@ -303,8 +328,16 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: true,
+ supportsRenameTable: true,
+ supportsRenameView: true,
supportsDropSchema: true,
- supportsRenameColumn: true,
+ supportsTriggers: true,
+ supportsTriggerEditing: true,
+ supportsCheckConstraints: true,
+ supportsCheckConstraintEditing: true,
+ supportsRoutines: true,
+ supportsDatabaseTriggerBrowse: true,
+ supportsUserDefinedTypeBrowse: true,
defaultSSLMode: .preferred,
supportsPerConnectionCertificatePaths: false,
supportsPrincipalConnectionLimit: false,
@@ -374,7 +407,7 @@ extension PluginMetadataRegistry {
explainVariants: [ExplainVariant(id: "explain", label: "EXPLAIN", sqlPrefix: "EXPLAIN", format: .plainText)],
pathFieldRole: .database,
supportsHealthMonitor: false, urlSchemes: ["teradata"],
- postConnectActions: [.selectDatabaseFromLastSession],
+ postConnectActions: [],
brandColorHex: "#F37440",
queryLanguageName: "SQL", editorLanguage: .sql,
connectionMode: .network, supportsDatabaseSwitching: true,
@@ -390,42 +423,61 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
+ supportsRenameTable: true,
+ supportsRenameView: true,
supportsRenameColumn: false,
+ supportsRoutines: true,
+ supportsDatabaseTriggerBrowse: true,
defaultSSLMode: .disabled
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "main",
tableEntityName: "Tables",
containerEntityName: "Database",
defaultPrimaryKeyColumn: nil,
immutableColumns: [],
- systemDatabaseNames: ["DBC", "Sys", "SysAdmin", "SystemFe", "SYSLIB", "SYSUDTLIB", "TDStats", "PUBLIC", "All", "Default"],
+ systemDatabaseNames: [
+ "DBC", "Sys", "SysAdmin", "SystemFe", "SYSLIB", "SYSUDTLIB", "SYSSPATIAL",
+ "TD_SYSFNLIB", "TD_SERVER_DB", "TDStats", "TDMaps", "TDQCD", "SQLJ",
+ "Sys_Calendar", "dbcmngr", "tdwm", "viewpoint", "console", "PUBLIC", "All", "Default",
+ ],
systemSchemaNames: [],
fileExtensions: [],
databaseGroupingStrategy: .byDatabase,
- structureColumnFields: [.name, .type, .nullable, .defaultValue],
+ structureColumnFields: [.name, .type, .nullable, .defaultValue, .autoIncrement, .comment],
systemDatabaseNamesIgnoreCase: true
),
editor: PluginMetadataSnapshot.EditorConfig(
sqlDialect: SQLDialectDescriptor(
identifierQuote: "\"",
keywords: [
- "SELECT", "FROM", "WHERE", "GROUP", "BY", "HAVING", "ORDER", "TOP", "QUALIFY",
- "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "OUTER", "ON", "AND", "OR", "NOT",
- "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP", "TABLE", "VIEW",
- "DATABASE", "USER", "MACRO", "VOLATILE", "MULTISET", "SET", "AS", "SAMPLE",
- "HELP", "SHOW", "EXPLAIN", "COLLECT", "STATISTICS", "LOCKING", "FOR", "ACCESS",
+ "SELECT", "FROM", "WHERE", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER", "CROSS", "FULL",
+ "ON", "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN", "AS", "SAMPLE",
+ "ORDER", "BY", "GROUP", "HAVING", "TOP", "QUALIFY", "WITH", "RECURSIVE",
+ "INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE",
+ "CREATE", "ALTER", "DROP", "TABLE", "INDEX", "VIEW", "DATABASE", "USER", "MACRO",
+ "PROCEDURE", "PRIMARY", "KEY", "UNIQUE", "INDEX", "PARTITION", "BY", "HASH", "RANGE_N",
+ "CASE_N", "NULL", "IS", "ASC", "DESC", "DISTINCT", "ALL", "ANY",
+ "CASE", "WHEN", "THEN", "ELSE", "END", "COALESCE", "NULLIF",
+ "UNION", "INTERSECT", "EXCEPT", "MINUS",
+ "OVER", "ROW_NUMBER", "RANK", "DENSE_RANK", "HELP", "SHOW", "EXPLAIN", "COLLECT",
+ "STATISTICS", "VOLATILE", "MULTISET", "SET", "GLOBAL", "TEMPORARY", "AS", "LOCKING",
+ "FOR", "ACCESS",
],
functions: [
- "COUNT", "SUM", "AVG", "MIN", "MAX", "CAST", "TRIM", "SUBSTRING",
- "COALESCE", "NULLIFZERO", "ZEROIFNULL", "OREPLACE", "OTRANSLATE",
- "CURRENT_DATE", "CURRENT_TIMESTAMP", "EXTRACT", "ADD_MONTHS",
+ "COUNT", "SUM", "AVG", "MIN", "MAX", "CAST", "TRIM", "SUBSTRING", "SUBSTR",
+ "CHARACTER_LENGTH", "CHAR_LENGTH", "COALESCE", "NULLIFZERO", "ZEROIFNULL",
+ "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "EXTRACT", "ADD_MONTHS",
+ "UPPER", "LOWER", "OREPLACE", "OTRANSLATE", "INDEX", "POSITION", "SOUNDEX",
],
dataTypes: [
- "BYTEINT", "SMALLINT", "INTEGER", "BIGINT", "DECIMAL", "NUMBER", "FLOAT",
- "CHAR", "VARCHAR", "CLOB", "BYTE", "VARBYTE", "BLOB",
- "DATE", "TIME", "TIMESTAMP", "INTERVAL", "PERIOD", "JSON", "XML",
+ "BYTEINT", "SMALLINT", "INTEGER", "BIGINT", "DECIMAL", "NUMERIC", "NUMBER",
+ "FLOAT", "REAL", "DOUBLE PRECISION",
+ "CHAR", "VARCHAR", "LONG VARCHAR", "CLOB",
+ "BYTE", "VARBYTE", "BLOB",
+ "DATE", "TIME", "TIMESTAMP", "INTERVAL", "PERIOD",
+ "JSON", "XML", "ST_GEOMETRY",
],
autoLimitStyle: .top,
caseSensitivityStyle: .unsupported,
@@ -436,10 +488,15 @@ extension PluginMetadataRegistry {
statementCompletions: [],
columnTypesByCategory: [
"Integer": ["BYTEINT", "SMALLINT", "INTEGER", "BIGINT"],
- "Float": ["FLOAT", "DECIMAL", "NUMBER"],
- "String": ["CHAR", "VARCHAR", "CLOB"],
- "Date": ["DATE", "TIME", "TIMESTAMP"],
+ "Float": ["FLOAT", "REAL", "DOUBLE PRECISION", "DECIMAL", "NUMERIC", "NUMBER"],
+ "String": ["CHAR", "VARCHAR", "LONG VARCHAR", "CLOB"],
+ "Date": ["DATE", "TIME", "TIMESTAMP", "TIME WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE"],
"Binary": ["BYTE", "VARBYTE", "BLOB"],
+ "Interval": [
+ "INTERVAL YEAR", "INTERVAL MONTH", "INTERVAL DAY", "INTERVAL HOUR", "INTERVAL MINUTE",
+ "INTERVAL SECOND",
+ ],
+ "Other": ["JSON", "XML", "PERIOD(DATE)", "PERIOD(TIMESTAMP)", "UDT"],
]
),
connection: PluginMetadataSnapshot.ConnectionConfig(
@@ -476,7 +533,12 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
- supportsRenameColumn: true,
+ supportsRenameTable: true,
+ supportsRenameView: true,
+ supportsTriggers: true,
+ supportsTriggerEditing: true,
+ supportsRoutines: true,
+ supportsDatabaseTriggerBrowse: true,
supportsOpportunisticTLS: false,
supportsPrincipalConnectionLimit: false,
supportsRoleLogin: false
@@ -502,11 +564,7 @@ extension PluginMetadataRegistry {
columnTypesByCategory: oracleColumnTypes
),
connection: PluginMetadataSnapshot.ConnectionConfig(
- additionalConnectionFields: [
- ConnectionField(
- id: "oracleServiceName", label: "Service Name", placeholder: "ORCL"
- )
- ],
+ additionalConnectionFields: Self.oracleConnectionFields,
category: .relational,
tagline: String(localized: "Enterprise SQL with PL/SQL")
)
@@ -537,8 +595,12 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
+ supportsRenameTable: true,
+ supportsRenameView: true,
supportsDropSchema: true,
supportsRenameColumn: true,
+ supportsRoutines: true,
+ supportsDatabaseTriggerBrowse: true,
supportsOpportunisticTLS: false
),
schema: PluginMetadataSnapshot.SchemaInfo(
@@ -600,7 +662,10 @@ extension PluginMetadataRegistry {
supportsQueryProgress: true,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: true,
- supportsModifyPrimaryKey: false,
+ supportsRenameTable: true,
+ supportsRenameView: true,
+ supportsRenameDatabase: true,
+ supportsRoutines: true,
supportsOpportunisticTLS: false,
tlsImpliedPorts: [8_443, 443],
verifiesServerWithSystemTrust: true,
@@ -652,13 +717,7 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
- supportsAddColumn: false,
- supportsModifyColumn: false,
- supportsDropColumn: false,
supportsRenameColumn: false,
- supportsAddIndex: false,
- supportsDropIndex: false,
- supportsModifyPrimaryKey: false,
isEngineReadOnly: true,
localFilePathField: .database
),
@@ -671,13 +730,14 @@ extension PluginMetadataRegistry {
immutableColumns: [
"id", "transaction_id", "date", "flag", "payee", "narration",
"account", "amount", "commodity", "cost_number", "cost_currency",
+ "cost_date", "cost_label", "price_number", "price_currency",
"currency", "currencies", "name", "open_date", "path"
],
systemDatabaseNames: [],
systemSchemaNames: [],
fileExtensions: ["beancount"],
databaseGroupingStrategy: .flat,
- structureColumnFields: [.name, .type, .nullable, .comment]
+ structureColumnFields: [.name, .type, .nullable, .defaultValue, .autoIncrement, .comment]
),
editor: PluginMetadataSnapshot.EditorConfig(
sqlDialect: SQLDialectDescriptor(
@@ -686,12 +746,16 @@ extension PluginMetadataRegistry {
"SELECT", "FROM", "WHERE", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER",
"ON", "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN", "AS",
"ORDER", "BY", "GROUP", "HAVING", "LIMIT", "OFFSET",
- "WITH", "UNION", "INTERSECT", "EXCEPT",
+ "WITH", "RECURSIVE", "UNION", "INTERSECT", "EXCEPT",
"CASE", "WHEN", "THEN", "ELSE", "END", "NULL", "IS",
"ASC", "DESC", "DISTINCT"
],
- functions: ["COUNT", "SUM", "AVG", "MAX", "MIN", "ROUND", "DATE", "STRFTIME"],
- dataTypes: ["INTEGER", "TEXT", "DATE", "DECIMAL"],
+ functions: [
+ "COUNT", "SUM", "AVG", "MAX", "MIN",
+ "COALESCE", "NULLIF", "ROUND", "ABS",
+ "DATE", "STRFTIME", "SUBSTR", "LOWER", "UPPER"
+ ],
+ dataTypes: ["INTEGER", "TEXT", "DATE"],
regexSyntax: .unsupported,
booleanLiteralStyle: .numeric,
likeEscapeStyle: .explicit,
@@ -702,8 +766,7 @@ extension PluginMetadataRegistry {
columnTypesByCategory: [
"Integer": ["INTEGER"],
"String": ["TEXT"],
- "Date": ["DATE"],
- "Decimal": ["DECIMAL"]
+ "Date": ["DATE"]
]
),
connection: PluginMetadataSnapshot.ConnectionConfig(
@@ -740,8 +803,8 @@ extension PluginMetadataRegistry {
defaultPrimaryKeyColumn: nil,
immutableColumns: [],
systemDatabaseNames: [
- "system", "system_schema", "system_auth", "system_distributed", "system_distributed_everywhere",
- "system_traces", "system_views", "system_virtual_schema", "system_replicated_keys"
+ "system", "system_schema", "system_auth", "system_distributed", "system_traces",
+ "system_virtual_schema", "system_distributed_everywhere", "system_views", "system_replicated_keys"
],
systemSchemaNames: [],
fileExtensions: [],
@@ -754,14 +817,7 @@ extension PluginMetadataRegistry {
columnTypesByCategory: cassandraColumnTypes
),
connection: PluginMetadataSnapshot.ConnectionConfig(
- additionalConnectionFields: AWSAuthFields.standard() + [
- ConnectionField(
- id: "sslCaCertPath",
- label: "CA Certificate",
- placeholder: "/path/to/ca-cert.pem",
- section: .advanced
- )
- ] + cassandraConsistencyFields(),
+ additionalConnectionFields: AWSAuthFields.standard() + cassandraConsistencyFields(),
category: .wideColumn,
tagline: String(localized: "Distributed wide-column store")
)
@@ -844,7 +900,7 @@ extension PluginMetadataRegistry {
tableEntityName: "Keys",
containerEntityName: "Database",
defaultPrimaryKeyColumn: "Key",
- immutableColumns: ["Version", "ModRevision", "CreateRevision"],
+ immutableColumns: [],
systemDatabaseNames: [],
systemSchemaNames: [],
fileExtensions: [],
@@ -902,7 +958,7 @@ extension PluginMetadataRegistry {
)),
("Cloudflare D1", PluginMetadataSnapshot(
displayName: "Cloudflare D1", iconName: "cloudflare-d1-icon", defaultPort: 0,
- requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: false,
+ requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: true,
isDownloadable: true, primaryUrlScheme: "d1", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [
ExplainVariant(
@@ -927,10 +983,14 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: true,
+ supportsRenameTable: true,
+ supportsTriggers: true,
+ supportsTriggerEditing: true,
+ supportsDatabaseTriggerBrowse: true,
exactRowCountIsFullScan: true
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "main",
+ defaultSchemaName: "public",
defaultGroupName: "main",
tableEntityName: "Tables",
containerEntityName: "Database",
@@ -988,13 +1048,15 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
- supportsModifyColumn: false,
- supportsRenameColumn: true,
+ supportsRenameTable: true,
+ supportsTriggers: true,
+ supportsTriggerEditing: true,
+ supportsDatabaseTriggerBrowse: true,
localFilePathField: .additionalField("libsqlFilePath"),
newDatabaseFileExtensions: Self.sqliteFileExtensions
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "main",
+ defaultSchemaName: "public",
defaultGroupName: "main",
tableEntityName: "Tables",
containerEntityName: "Database",
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryIngredients.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryIngredients.swift
index 8dc79aeb53..7f2f8fda18 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryIngredients.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+RegistryIngredients.swift
@@ -437,7 +437,13 @@ extension PluginMetadataRegistry {
CompletionEntry(label: ".findOneAndReplace", insertText: ".findOneAndReplace"),
CompletionEntry(label: ".findOneAndDelete", insertText: ".findOneAndDelete"),
CompletionEntry(label: ".countDocuments", insertText: ".countDocuments"),
- CompletionEntry(label: ".createIndex", insertText: ".createIndex")
+ CompletionEntry(label: ".createIndex", insertText: ".createIndex"),
+ CompletionEntry(label: "ObjectId", insertText: "ObjectId"),
+ CompletionEntry(label: "ISODate", insertText: "ISODate"),
+ CompletionEntry(label: "NumberLong", insertText: "NumberLong"),
+ CompletionEntry(label: "NumberDecimal", insertText: "NumberDecimal"),
+ CompletionEntry(label: "BinData", insertText: "BinData"),
+ CompletionEntry(label: "UUID", insertText: "UUID")
]
let mongoColumnTypes: [String: [String]] = [
@@ -483,45 +489,19 @@ extension PluginMetadataRegistry {
]
let redisCompletions: [CompletionEntry] = [
- CompletionEntry(label: "GET", insertText: "GET"),
- CompletionEntry(label: "SET", insertText: "SET"),
- CompletionEntry(label: "DEL", insertText: "DEL"),
- CompletionEntry(label: "EXISTS", insertText: "EXISTS"),
- CompletionEntry(label: "KEYS", insertText: "KEYS"),
- CompletionEntry(label: "HGET", insertText: "HGET"),
- CompletionEntry(label: "HSET", insertText: "HSET"),
- CompletionEntry(label: "HGETALL", insertText: "HGETALL"),
- CompletionEntry(label: "HDEL", insertText: "HDEL"),
- CompletionEntry(label: "LPUSH", insertText: "LPUSH"),
- CompletionEntry(label: "RPUSH", insertText: "RPUSH"),
- CompletionEntry(label: "LRANGE", insertText: "LRANGE"),
- CompletionEntry(label: "LLEN", insertText: "LLEN"),
- CompletionEntry(label: "SADD", insertText: "SADD"),
- CompletionEntry(label: "SMEMBERS", insertText: "SMEMBERS"),
- CompletionEntry(label: "SREM", insertText: "SREM"),
- CompletionEntry(label: "SCARD", insertText: "SCARD"),
- CompletionEntry(label: "ZADD", insertText: "ZADD"),
- CompletionEntry(label: "ZRANGE", insertText: "ZRANGE"),
- CompletionEntry(label: "ZREM", insertText: "ZREM"),
- CompletionEntry(label: "ZSCORE", insertText: "ZSCORE"),
- CompletionEntry(label: "EXPIRE", insertText: "EXPIRE"),
- CompletionEntry(label: "TTL", insertText: "TTL"),
- CompletionEntry(label: "PERSIST", insertText: "PERSIST"),
- CompletionEntry(label: "TYPE", insertText: "TYPE"),
- CompletionEntry(label: "SCAN", insertText: "SCAN"),
- CompletionEntry(label: "HSCAN", insertText: "HSCAN"),
- CompletionEntry(label: "SSCAN", insertText: "SSCAN"),
- CompletionEntry(label: "ZSCAN", insertText: "ZSCAN"),
- CompletionEntry(label: "INFO", insertText: "INFO"),
- CompletionEntry(label: "DBSIZE", insertText: "DBSIZE"),
- CompletionEntry(label: "FLUSHDB", insertText: "FLUSHDB"),
- CompletionEntry(label: "SELECT", insertText: "SELECT"),
- CompletionEntry(label: "INCR", insertText: "INCR"),
- CompletionEntry(label: "DECR", insertText: "DECR"),
- CompletionEntry(label: "APPEND", insertText: "APPEND"),
- CompletionEntry(label: "MGET", insertText: "MGET"),
- CompletionEntry(label: "MSET", insertText: "MSET")
- ]
+ "GET", "SET", "DEL", "EXISTS", "KEYS", "GETSET", "GETDEL", "GETEX", "MGET", "MSET",
+ "INCR", "DECR", "INCRBY", "DECRBY", "INCRBYFLOAT", "APPEND",
+ "EXPIRE", "PEXPIRE", "EXPIREAT", "PEXPIREAT", "TTL", "PTTL", "PERSIST", "TYPE", "RENAME", "SCAN",
+ "HGET", "HSET", "HGETALL", "HDEL", "HSCAN",
+ "LPUSH", "RPUSH", "LRANGE", "LLEN", "LPOP", "RPOP", "LSET", "LINSERT", "LREM", "LPOS", "LMOVE",
+ "SADD", "SMEMBERS", "SREM", "SCARD", "SPOP", "SRANDMEMBER", "SMOVE",
+ "SUNION", "SINTER", "SDIFF", "SUNIONSTORE", "SINTERSTORE", "SDIFFSTORE", "SSCAN",
+ "ZADD", "ZRANGE", "ZREM", "ZCARD", "ZSCORE", "ZRANGEBYSCORE", "ZREVRANGE", "ZREVRANGEBYSCORE",
+ "ZINCRBY", "ZCOUNT", "ZRANK", "ZREVRANK", "ZPOPMIN", "ZPOPMAX", "ZSCAN",
+ "XRANGE", "XREVRANGE", "XLEN", "XADD", "XREAD", "XDEL", "XTRIM", "XINFO", "XGROUP", "XACK",
+ "PING", "INFO", "DBSIZE", "FLUSHDB", "FLUSHALL", "SELECT", "CONFIG", "AUTH", "OBJECT",
+ "MULTI", "EXEC", "DISCARD",
+ ].map { CompletionEntry(label: $0, insertText: $0) }
let redisColumnTypes: [String: [String]] = [
"String": ["string"],
@@ -598,4 +578,50 @@ extension PluginMetadataRegistry {
)
}
// swiftlint:enable function_body_length large_tuple
+
+ // OraclePlugin's fields, spelled out: their ids and values come from TableProOracleCore, which the app does not link.
+ static let oracleConnectionFields: [ConnectionField] = [
+ ConnectionField(
+ id: "oracleConnectionType",
+ label: "Connection Type",
+ defaultValue: "service",
+ fieldType: .dropdown(options: [
+ .init(value: "service", label: "Service Name"),
+ .init(value: "sid", label: "SID")
+ ])
+ ),
+ ConnectionField(
+ id: "oracleServiceName",
+ label: "Service Name",
+ placeholder: "ORCL",
+ visibleWhen: FieldVisibilityRule(fieldId: "oracleConnectionType", values: ["service"])
+ ),
+ ConnectionField(
+ id: "oracleSID",
+ label: "SID",
+ placeholder: "XE",
+ visibleWhen: FieldVisibilityRule(fieldId: "oracleConnectionType", values: ["sid"])
+ ),
+ ConnectionField(
+ id: "oracleRole",
+ label: "Role",
+ defaultValue: "normal",
+ fieldType: .dropdown(options: [
+ .init(value: "normal", label: "Normal"),
+ .init(value: "sysdba", label: "SYSDBA"),
+ .init(value: "sysoper", label: "SYSOPER")
+ ])
+ ),
+ ConnectionField(
+ id: "oracleNetworkEncryption",
+ label: "Network Encryption",
+ defaultValue: "accepted",
+ fieldType: .dropdown(options: [
+ .init(value: "accepted", label: "Accepted"),
+ .init(value: "rejected", label: "Rejected"),
+ .init(value: "requested", label: "Requested"),
+ .init(value: "required", label: "Required")
+ ])
+ )
+ ]
}
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+SurrealDBDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+SurrealDBDefaults.swift
index b335af19ad..a960f1bf77 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+SurrealDBDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+SurrealDBDefaults.swift
@@ -54,7 +54,7 @@ extension PluginMetadataRegistry {
structureColumnFields: [.name, .type, .nullable]
),
editor: PluginMetadataSnapshot.EditorConfig(
- sqlDialect: nil,
+ sqlDialect: surrealDBDialect,
statementCompletions: surrealDBCompletions,
columnTypesByCategory: surrealDBColumnTypes
),
@@ -90,6 +90,46 @@ private let surrealDBCompletions: [CompletionEntry] = [
CompletionEntry(label: "count", insertText: "SELECT count() AS total FROM table GROUP ALL"),
]
+private let surrealDBDialect = SQLDialectDescriptor(
+ identifierQuote: "`",
+ keywords: [
+ "SELECT", "FROM", "WHERE", "ORDER", "BY", "GROUP", "ALL", "LIMIT", "START", "FETCH",
+ "SPLIT", "OMIT", "ONLY", "PARALLEL", "TIMEOUT", "EXPLAIN", "WITH", "INDEX",
+ "CREATE", "UPDATE", "UPSERT", "DELETE", "INSERT", "RELATE", "CONTENT", "MERGE",
+ "PATCH", "SET", "RETURN", "BEFORE", "AFTER", "DIFF", "NONE", "NULL", "TRUE", "FALSE",
+ "DEFINE", "REMOVE", "ALTER", "TABLE", "FIELD", "EVENT", "PARAM", "FUNCTION",
+ "NAMESPACE", "DATABASE", "USER", "ACCESS", "ANALYZER", "SCOPE", "TOKEN",
+ "SCHEMAFULL", "SCHEMALESS", "PERMISSIONS", "TYPE", "ASSERT", "DEFAULT", "VALUE",
+ "READONLY", "FLEXIBLE", "UNIQUE", "SEARCH", "MTREE", "HNSW", "COUNT",
+ "USE", "NS", "DB", "LET", "IF", "ELSE", "THEN", "END", "FOR", "IN", "CONTINUE", "BREAK",
+ "BEGIN", "COMMIT", "CANCEL", "TRANSACTION", "INFO", "LIVE", "KILL",
+ "AND", "OR", "NOT", "IS", "CONTAINS", "CONTAINSNOT", "INSIDE", "NOTINSIDE",
+ "OUTSIDE", "INTERSECTS", "ASC", "DESC", "AS", "ON", "IF NOT EXISTS",
+ ],
+ functions: [
+ "count", "math::sum", "math::mean", "math::min", "math::max", "math::abs",
+ "string::concat", "string::contains", "string::starts_with", "string::ends_with",
+ "string::len", "string::lowercase", "string::uppercase", "string::trim",
+ "string::split", "string::join", "string::replace", "string::slice",
+ "time::now", "time::floor", "time::group", "time::unix", "time::format",
+ "array::len", "array::distinct", "array::flatten", "array::group", "array::sort",
+ "array::append", "array::concat", "array::union", "array::first", "array::last",
+ "type::is_number", "type::is_string", "type::table", "type::field", "type::thing",
+ "rand::uuid", "rand::int", "rand::float", "object::keys", "object::values",
+ "meta::id", "meta::tb", "record::id", "record::table",
+ ],
+ dataTypes: [
+ "any", "array", "bool", "bytes", "datetime", "decimal", "duration", "float",
+ "geometry", "int", "number", "object", "option", "record", "set", "string", "uuid",
+ ],
+ regexSyntax: .unsupported,
+ booleanLiteralStyle: .truefalse,
+ likeEscapeStyle: .explicit,
+ paginationStyle: .limit,
+ autoLimitStyle: .limit,
+ caseSensitivityStyle: .unsupported
+)
+
private let surrealDBColumnTypes: [String: [String]] = [
"Integer": ["int"],
"Float": ["float", "decimal", "number"],
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TrinoDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TrinoDefaults.swift
index d147b1d00d..28e9901573 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TrinoDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TrinoDefaults.swift
@@ -33,7 +33,13 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
+ supportsRenameTable: true,
+ supportsRenameView: true,
+ supportsRenameSchema: true,
supportsRenameColumn: false,
+ supportsAddIndex: false,
+ supportsDropIndex: false,
+ supportsModifyPrimaryKey: false,
defaultSSLMode: .disabled,
supportsOpportunisticTLS: false,
tlsImpliedPorts: [443],
@@ -137,33 +143,49 @@ extension PluginMetadataRegistry {
"Floating": ["real", "double", "decimal"],
"String": ["varchar", "char"],
"Binary": ["varbinary"],
- "Date/Time": ["date", "time", "timestamp"],
+ "Date/Time": ["date", "time", "timestamp", "time with time zone", "timestamp with time zone"],
"Complex": ["array", "map", "row", "json"],
+ "Other": ["uuid", "ipaddress", "interval year to month", "interval day to second"],
]
private static func trinoDialect(paginationStyle: SQLDialectDescriptor.PaginationStyle) -> SQLDialectDescriptor {
SQLDialectDescriptor(
identifierQuote: "\"",
keywords: [
- "SELECT", "FROM", "WHERE", "GROUP", "BY", "HAVING", "ORDER", "LIMIT", "OFFSET",
- "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "ON", "USING", "AND", "OR", "NOT",
- "IN", "LIKE", "BETWEEN", "AS", "DISTINCT", "UNION", "INTERSECT", "EXCEPT", "WITH",
- "INSERT", "INTO", "UPDATE", "SET", "DELETE", "CREATE", "ALTER", "DROP", "TABLE",
- "VIEW", "SCHEMA", "CATALOG", "CASE", "WHEN", "THEN", "ELSE", "END", "CAST", "TRY_CAST",
+ "SELECT", "FROM", "WHERE", "GROUP", "BY", "HAVING", "ORDER", "LIMIT", "OFFSET", "FETCH",
+ "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "OUTER", "CROSS", "ON", "USING", "NATURAL",
+ "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN", "AS", "DISTINCT", "ALL",
+ "UNION", "INTERSECT", "EXCEPT", "WITH", "RECURSIVE", "VALUES", "UNNEST", "LATERAL",
+ "INSERT", "INTO", "UPDATE", "SET", "DELETE", "MERGE", "CREATE", "ALTER", "DROP",
+ "TABLE", "VIEW", "SCHEMA", "CATALOG", "IF", "EXISTS", "REPLACE", "COMMENT",
+ "CASE", "WHEN", "THEN", "ELSE", "END", "CAST", "TRY_CAST", "IS", "NULL", "TRUE", "FALSE",
+ "ASC", "DESC", "NULLS", "FIRST", "LAST", "OVER", "PARTITION", "WINDOW",
+ "ROWS", "RANGE", "GROUPS", "UNBOUNDED", "PRECEDING", "FOLLOWING", "CURRENT", "ROW",
+ "GROUPING", "SETS", "CUBE", "ROLLUP", "QUALIFY",
"SHOW", "CATALOGS", "SCHEMAS", "TABLES", "COLUMNS", "DESCRIBE", "EXPLAIN", "ANALYZE",
- "USE", "UNNEST", "OVER", "PARTITION", "QUALIFY",
+ "USE", "PREPARE", "EXECUTE", "DEALLOCATE", "RESET", "SESSION",
],
functions: [
- "COUNT", "SUM", "AVG", "MIN", "MAX", "ARRAY_AGG", "APPROX_DISTINCT", "CARDINALITY",
- "ELEMENT_AT", "JSON_EXTRACT", "JSON_EXTRACT_SCALAR", "REGEXP_LIKE", "REGEXP_REPLACE",
- "SUBSTR", "LENGTH", "LOWER", "UPPER", "TRIM", "SPLIT", "CONCAT", "COALESCE",
- "DATE_TRUNC", "DATE_DIFF", "DATE_FORMAT", "FROM_UNIXTIME", "TO_UNIXTIME",
- "ROW_NUMBER", "RANK", "DENSE_RANK", "LAG", "LEAD",
+ "COUNT", "SUM", "AVG", "MIN", "MAX", "ARRAY_AGG", "APPROX_DISTINCT", "ARBITRARY",
+ "CARDINALITY", "ELEMENT_AT", "CONTAINS", "FILTER", "TRANSFORM", "REDUCE", "ZIP",
+ "MAP", "MAP_KEYS", "MAP_VALUES", "MAP_FROM_ENTRIES", "SLICE", "SEQUENCE", "FLATTEN",
+ "JSON_EXTRACT", "JSON_EXTRACT_SCALAR", "JSON_PARSE", "JSON_FORMAT", "JSON_ARRAY_LENGTH",
+ "REGEXP_LIKE", "REGEXP_REPLACE", "REGEXP_EXTRACT", "REGEXP_EXTRACT_ALL", "REGEXP_SPLIT",
+ "SUBSTR", "SUBSTRING", "LENGTH", "LOWER", "UPPER", "TRIM", "LTRIM", "RTRIM", "SPLIT",
+ "SPLIT_PART", "CONCAT", "REPLACE", "REVERSE", "POSITION", "STRPOS", "FORMAT",
+ "COALESCE", "NULLIF", "GREATEST", "LEAST", "IF", "TRY", "NOW",
+ "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "AT_TIMEZONE", "WITH_TIMEZONE",
+ "DATE_TRUNC", "DATE_ADD", "DATE_DIFF", "DATE_FORMAT", "DATE_PARSE", "PARSE_DATETIME",
+ "FROM_UNIXTIME", "TO_UNIXTIME", "FROM_ISO8601_TIMESTAMP", "EXTRACT",
+ "ROW_NUMBER", "RANK", "DENSE_RANK", "PERCENT_RANK", "CUME_DIST", "NTILE",
+ "LAG", "LEAD", "FIRST_VALUE", "LAST_VALUE", "NTH_VALUE",
+ "ABS", "CEIL", "CEILING", "FLOOR", "ROUND", "POWER", "SQRT", "CBRT", "LN", "LOG10",
+ "LOG2", "EXP", "MOD", "SIGN", "TRUNCATE", "WIDTH_BUCKET",
],
dataTypes: [
- "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "REAL", "DOUBLE", "DECIMAL",
- "VARCHAR", "CHAR", "VARBINARY", "JSON", "DATE", "TIME", "TIMESTAMP", "INTERVAL",
- "ARRAY", "MAP", "ROW", "IPADDRESS", "UUID",
+ "BOOLEAN", "TINYINT", "SMALLINT", "INTEGER", "INT", "BIGINT", "REAL", "DOUBLE",
+ "DECIMAL", "VARCHAR", "CHAR", "VARBINARY", "JSON", "DATE", "TIME", "TIMESTAMP",
+ "INTERVAL", "ARRAY", "MAP", "ROW", "IPADDRESS", "UUID", "HYPERLOGLOG",
],
regexSyntax: .regexpLike,
booleanLiteralStyle: .truefalse,
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TypesenseDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TypesenseDefaults.swift
index 362ef7bfcb..fac0f78359 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TypesenseDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+TypesenseDefaults.swift
@@ -12,7 +12,7 @@ extension PluginMetadataRegistry {
("Typesense", PluginMetadataSnapshot(
displayName: "Typesense", iconName: "typesense-icon", defaultPort: 8_108,
requiresAuthentication: false, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "typesense", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#1035BC",
@@ -30,15 +30,21 @@ extension PluginMetadataRegistry {
supportsQueryProgress: false,
requiresReconnectForDatabaseSwitch: false,
supportsDropDatabase: false,
+ supportsAddColumn: false,
+ supportsModifyColumn: false,
+ supportsDropColumn: false,
+ supportsAddIndex: false,
+ supportsDropIndex: false,
+ supportsModifyPrimaryKey: false,
supportsOpportunisticTLS: false,
dataCommands: typesenseDataCommands
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "default",
tableEntityName: "Collections",
containerEntityName: "Cluster",
- defaultPrimaryKeyColumn: "id",
+ defaultPrimaryKeyColumn: nil,
immutableColumns: ["id"],
systemDatabaseNames: [],
systemSchemaNames: [],
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+WeaviateDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+WeaviateDefaults.swift
index 219b17658b..691573cc7f 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+WeaviateDefaults.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+WeaviateDefaults.swift
@@ -7,7 +7,7 @@ extension PluginMetadataRegistry {
("Weaviate", PluginMetadataSnapshot(
displayName: "Weaviate", iconName: "weaviate-icon", defaultPort: 8_080,
requiresAuthentication: false, supportsForeignKeys: false, supportsSchemaEditing: false,
- isDownloadable: true, primaryUrlScheme: "", parameterStyle: .questionMark,
+ isDownloadable: true, primaryUrlScheme: "weaviate", parameterStyle: .questionMark,
navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
supportsHealthMonitor: true, urlSchemes: [], postConnectActions: [],
brandColorHex: "#01B0D3",
@@ -37,7 +37,7 @@ extension PluginMetadataRegistry {
dataCommands: weaviateDataCommands
),
schema: PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "",
+ defaultSchemaName: "public",
defaultGroupName: "default",
tableEntityName: "Collections",
containerEntityName: "Cluster",
diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift
index 77b7e765db..39378ab8ba 100644
--- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift
+++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry.swift
@@ -584,16 +584,7 @@ final class PluginMetadataRegistry: @unchecked Sendable {
resolved = resolved.withBranding(from: existing)
}
if let registryDefault = defaultSnapshots[typeId] {
- resolved = resolved.withIsDownloadable(registryDefault.isDownloadable)
- Self.adoptCuratedCaseSensitivity(&resolved, registryDefault: registryDefault)
- Self.adoptCuratedSystemNames(&resolved, registryDefault: registryDefault)
- Self.adoptCuratedExplainVariants(&resolved, registryDefault: registryDefault)
- if Self.declaresLegacySchemaOnlyRouting(resolved, registryDefault: registryDefault) {
- Logger(subsystem: "com.TablePro", category: "PluginMetadataRegistry").notice(
- "Plugin '\(typeId, privacy: .public)' declares legacy two-tier switching for a schema-only engine; applying the app's switch routing"
- )
- resolved = resolved.withSwitchRouting(from: registryDefault)
- }
+ resolved = Self.adoptingCuratedEntry(resolved, registryDefault: registryDefault, typeId: typeId)
}
snapshots[typeId] = resolved
for scheme in resolved.urlSchemes {
@@ -601,6 +592,25 @@ final class PluginMetadataRegistry: @unchecked Sendable {
}
}
+ // What registration keeps from the type's curated entry over what a plugin declares.
+ static func adoptingCuratedEntry(
+ _ snapshot: PluginMetadataSnapshot,
+ registryDefault: PluginMetadataSnapshot,
+ typeId: String
+ ) -> PluginMetadataSnapshot {
+ var resolved = snapshot.withIsDownloadable(registryDefault.isDownloadable)
+ adoptCuratedCaseSensitivity(&resolved, registryDefault: registryDefault)
+ adoptCuratedSystemNames(&resolved, registryDefault: registryDefault)
+ adoptCuratedExplainVariants(&resolved, registryDefault: registryDefault)
+ if declaresLegacySchemaOnlyRouting(resolved, registryDefault: registryDefault) {
+ Logger(subsystem: "com.TablePro", category: "PluginMetadataRegistry").notice(
+ "Plugin '\(typeId, privacy: .public)' declares legacy two-tier switching for a schema-only engine; applying the app's switch routing"
+ )
+ resolved = resolved.withSwitchRouting(from: registryDefault)
+ }
+ return resolved
+ }
+
func unregister(typeId: String) {
lock.lock()
defer { lock.unlock() }
@@ -649,6 +659,12 @@ final class PluginMetadataRegistry: @unchecked Sendable {
return defaultSnapshots[databaseType.rawValue]
}
+ // The language a type's statements are read in. A curated entry's wins, so a loaded plugin cannot move an engine the
+ // app ships onto another language's looser classifier.
+ func queryLanguage(for databaseType: DatabaseType) -> EditorLanguage? {
+ (curatedSnapshot(for: databaseType) ?? snapshot(for: databaseType))?.editorLanguage
+ }
+
func snapshot(for databaseType: DatabaseType) -> PluginMetadataSnapshot? {
lock.lock()
defer { lock.unlock() }
@@ -713,6 +729,21 @@ final class PluginMetadataRegistry: @unchecked Sendable {
func buildMetadataSnapshot(
from driverType: any DriverPlugin.Type,
isDownloadable: Bool = false
+ ) -> PluginMetadataSnapshot {
+ Self.metadataSnapshot(
+ from: driverType,
+ isDownloadable: isDownloadable,
+ existing: snapshot(forRegisteredTypeId: driverType.databaseTypeId)
+ )
+ }
+
+ // A capability with no DriverPlugin static is curated per type, so `existing`, the snapshot registered for the type
+ // before this plugin, carries it over, or registration resets it to the struct default. The plugin cannot be asked:
+ // a stale one without the property crashes with EXC_BAD_INSTRUCTION (missing witness table entry).
+ static func metadataSnapshot(
+ from driverType: any DriverPlugin.Type,
+ isDownloadable: Bool,
+ existing existingSnapshot: PluginMetadataSnapshot?
) -> PluginMetadataSnapshot {
let parameterStyle = driverType.parameterStyle
let schemes = driverType.urlSchemes
@@ -724,12 +755,6 @@ final class PluginMetadataRegistry: @unchecked Sendable {
driverType.databaseTypeId != "Kafka" || $0.id != "kafkaConnectTimeout"
}
- // A capability with no DriverPlugin static is curated per type, so it has to be carried
- // over from the built-in snapshot or plugin registration silently resets it to the
- // struct default. Cannot read these from driverType directly: stale plugins without
- // the property crash with EXC_BAD_INSTRUCTION (missing witness table entry).
- let existingSnapshot = snapshot(forRegisteredTypeId: driverType.databaseTypeId)
-
// The app reads the Schema Registry fields itself, so an older bundle keeps the curated ones.
let declared = Set(pluginFields.map(\.id))
let additionalConnectionFields = pluginFields
diff --git a/apple/TablePro/Core/SSH/HostKeyStore.swift b/apple/TablePro/Core/SSH/HostKeyStore.swift
index 73d2b31ccb..7f4c393606 100644
--- a/apple/TablePro/Core/SSH/HostKeyStore.swift
+++ b/apple/TablePro/Core/SSH/HostKeyStore.swift
@@ -1,125 +1,10 @@
-import CryptoKit
import Foundation
-import os
import TableProSSHTransport
-internal final class HostKeyStore: @unchecked Sendable {
- static let shared = HostKeyStore()
-
- private static let logger = Logger(subsystem: "com.TablePro", category: "HostKeyStore")
-
- enum VerificationResult: Equatable {
- case trusted
- case unknown(fingerprint: String, keyType: String)
- case mismatch(expected: String, actual: String)
- // The file is one entry per line split on spaces, so a host with a line break would plant
- // an entry for another host.
- case invalidHost(SSHDestinationName.Problem)
- // The saved keys could not be read, so a changed key would look like a new host.
- case unreadable
- }
-
- let filePath: String
- private let lock = NSLock()
-
- private init() {
+extension HostKeyStore {
+ static let shared: HostKeyStore = {
let tableProDir = AppStorageEnvironment.shared.applicationSupportRoot.appendingPathComponent("TablePro")
try? FileManager.default.createDirectory(at: tableProDir, withIntermediateDirectories: true)
- self.filePath = tableProDir.appendingPathComponent("known_hosts").path
- }
-
- init(filePath: String) {
- self.filePath = filePath
- }
-
- func verify(keyData: Data, keyType: String, hostname: String, port: Int) -> VerificationResult {
- lock.lock()
- defer { lock.unlock() }
-
- guard let hostKey = hostIdentifier(hostname, port) else {
- return .invalidHost(.host(hostname))
- }
- guard let file = loadFile() else { return .unreadable }
-
- switch file.match(host: hostKey, keyType: keyType, keyData: keyData) {
- case .trusted:
- Self.logger.debug("Host key trusted for \(hostKey)")
- return .trusted
- case .unknown:
- Self.logger.info("Unknown host key for \(hostKey)")
- return .unknown(fingerprint: Self.fingerprint(of: keyData), keyType: keyType)
- case .changed(let storedKey):
- Self.logger.warning("Host key mismatch for \(hostKey)")
- return .mismatch(expected: Self.fingerprint(of: storedKey), actual: Self.fingerprint(of: keyData))
- case .unreadable:
- Self.logger.error("The saved host key for \(hostKey) could not be parsed")
- return .unreadable
- }
- }
-
- func trust(hostname: String, port: Int, key: Data, keyType: String) {
- lock.lock()
- defer { lock.unlock() }
-
- guard let hostKey = hostIdentifier(hostname, port), var file = loadFile() else { return }
- file.trust(host: hostKey, keyType: keyType, keyData: key)
- saveFile(file)
-
- Self.logger.info("Trusted host key for \(hostKey) (\(keyType))")
- }
-
- func remove(hostname: String, port: Int) {
- lock.lock()
- defer { lock.unlock() }
-
- guard let hostKey = hostIdentifier(hostname, port), var file = loadFile() else { return }
- if file.remove(host: hostKey) {
- saveFile(file)
- Self.logger.info("Removed host key for \(hostKey)")
- }
- }
-
- static func keyTypeName(_ type: Int32) -> String {
- switch type {
- case 1: return "ssh-rsa"
- case 2: return "ssh-dss"
- case 3: return "ecdsa-sha2-nistp256"
- case 4: return "ecdsa-sha2-nistp384"
- case 5: return "ecdsa-sha2-nistp521"
- case 6: return "ssh-ed25519"
- default: return "unknown"
- }
- }
-
- // The OpenSSH form `ssh-keygen -l` prints: SHA-256, base64 without padding.
- static func fingerprint(of key: Data) -> String {
- let digest = SHA256.hash(data: key)
- return "SHA256:" + Data(digest).base64EncodedString().replacingOccurrences(of: "=", with: "")
- }
-
- private func hostIdentifier(_ hostname: String, _ port: Int) -> String? {
- guard SSHDestinationName.isValidHost(hostname) else {
- Self.logger.warning("Refusing a host key entry for a host ssh would refuse")
- return nil
- }
- return "[\(hostname)]:\(port)"
- }
-
- // nil means the file is there but unreadable, and nothing may be written over it.
- private func loadFile() -> KnownHostsFile? {
- do {
- return try KnownHostsFile.load(from: URL(fileURLWithPath: filePath))
- } catch {
- Self.logger.error("Failed to read known_hosts file: \(error.localizedDescription)")
- return nil
- }
- }
-
- private func saveFile(_ file: KnownHostsFile) {
- do {
- try file.contents.write(toFile: filePath, atomically: true, encoding: .utf8)
- } catch {
- Self.logger.error("Failed to write known_hosts file: \(error.localizedDescription)")
- }
- }
+ return HostKeyStore(filePath: tableProDir.appendingPathComponent("known_hosts").path)
+ }()
}
diff --git a/apple/TablePro/Core/Utilities/SQL/CatalogChangeClassifier.swift b/apple/TablePro/Core/Utilities/SQL/CatalogChangeClassifier.swift
index dbcf8d5171..70c85c4081 100644
--- a/apple/TablePro/Core/Utilities/SQL/CatalogChangeClassifier.swift
+++ b/apple/TablePro/Core/Utilities/SQL/CatalogChangeClassifier.swift
@@ -29,7 +29,7 @@ enum CatalogChangeClassifier {
if databaseType == .redis {
return .none
}
- if documentStoreTypes.contains(databaseType) {
+ if documentStoreTypes.contains(databaseType) || QueryClassifier.speaksCypher(databaseType) {
let tier = QueryClassifier.classifyTier(trimmed, databaseType: databaseType)
return tier == .safe ? .none : .opaque
}
@@ -53,7 +53,7 @@ enum CatalogChangeClassifier {
// InfluxDB has no DDL: a write is what creates a measurement, so any statement that is not a read may change the list.
private static let documentStoreTypes: Set = [
- .mongodb, .elasticsearch, .typesense, .weaviate, .qdrant, .etcd, .firestore, .firebaseRealtimeDatabase, .bigtable, .neo4j,
+ .mongodb, .elasticsearch, .typesense, .weaviate, .qdrant, .etcd, .firestore, .firebaseRealtimeDatabase, .bigtable,
.influxdb,
]
}
diff --git a/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Cypher.swift b/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Cypher.swift
index 7eefed9d0a..4fa37e397a 100644
--- a/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Cypher.swift
+++ b/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Cypher.swift
@@ -4,9 +4,15 @@
//
import Foundation
+import TableProPluginKit
import TableProSQLGrammar
extension QueryClassifier {
+ // By the language the engine declares, so every graph engine that speaks Cypher is read as Cypher.
+ static func speaksCypher(_ databaseType: DatabaseType) -> Bool {
+ PluginMetadataRegistry.shared.queryLanguage(for: databaseType) == .custom("cypher")
+ }
+
static func cypherClassification(_ text: String) -> QueryClassification {
cypherReadings(of: text).reduce(.safe) { worst, code in
worst.escalated(with: cypherClassification(code: code))
diff --git a/apple/TablePro/Core/Utilities/SQL/QueryClassifier+DataStatements.swift b/apple/TablePro/Core/Utilities/SQL/QueryClassifier+DataStatements.swift
index 37798a7f54..1ad3a7e035 100644
--- a/apple/TablePro/Core/Utilities/SQL/QueryClassifier+DataStatements.swift
+++ b/apple/TablePro/Core/Utilities/SQL/QueryClassifier+DataStatements.swift
@@ -48,6 +48,7 @@ extension QueryClassifier {
databaseType: DatabaseType,
snapshot: PluginMetadataSnapshot?
) -> [DataCommand]? {
+ if speaksCypher(databaseType) { return cypherDataCommands(sql) }
switch databaseType {
case .redis:
return redisDataCommands(sql)
@@ -59,8 +60,6 @@ extension QueryClassifier {
return kafkaDataCommands(sql)
case .mongodb:
return mongoDataCommands(sql, systemDatabases: Set(snapshot?.schema.systemDatabaseNames ?? []))
- case .neo4j:
- return cypherDataCommands(sql)
case .elasticsearch:
return elasticsearchDataCommands(sql)
case .typesense:
diff --git a/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift b/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift
index 479213519e..e3bfe08abc 100644
--- a/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift
+++ b/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift
@@ -106,7 +106,7 @@ enum QueryClassifier {
if classification.tier == .destructive { return true }
// A MongoDB statement is JavaScript, where `delete d.x` removes a field from a local object.
guard databaseType != .redis, databaseType != .mongodb else { return false }
- if databaseType == .neo4j { return cypherDeletesUnfiltered(sql) }
+ if speaksCypher(databaseType) { return cypherDeletesUnfiltered(sql) }
// A request engine's own reading already tiers each delete of more than one item as destructive.
guard documentStoreClassification(sql, databaseType: databaseType, readings: readings) == nil else {
return false
@@ -287,6 +287,7 @@ extension QueryClassifier {
worst.escalated(with: classification(request))
}
}
+ if speaksCypher(databaseType) { return cypherClassification(sql) }
switch databaseType {
case .mongodb:
return mongoClassification(sql)
@@ -306,8 +307,6 @@ extension QueryClassifier {
return worstRequest { firebaseClassification($0, databaseType: databaseType) }
case .bigtable:
return worstRequest(bigtableClassification)
- case .neo4j:
- return cypherClassification(sql)
default:
return nil
}
diff --git a/apple/TablePro/Core/Utilities/SQL/SQLLexicalResolver.swift b/apple/TablePro/Core/Utilities/SQL/SQLLexicalResolver.swift
index 376eccca82..48df1c93ad 100644
--- a/apple/TablePro/Core/Utilities/SQL/SQLLexicalResolver.swift
+++ b/apple/TablePro/Core/Utilities/SQL/SQLLexicalResolver.swift
@@ -13,6 +13,7 @@ enum SQLLexicalResolver {
) -> SQLLexicalReadings {
SQLLexicalReadings.resolve(
databaseTypeId: databaseType.rawValue,
+ queryLanguage: queryLanguage(for: databaseType),
declared: declaredGrammar(for: databaseType),
session: session.map(SQLSessionLexicalFacts.init(pluginState:))
)
@@ -39,14 +40,17 @@ enum SQLLexicalResolver {
session: PluginSessionLexicalState? = nil
) -> SQLStringEscapes {
let declared = declaredGrammar(for: databaseType)
+ let language = queryLanguage(for: databaseType)
// An engine nobody described answers from its dialect's own backslash flag, not from an ANSI guess.
- if declared == nil, SQLLexicalProfile.curated(forDatabaseTypeId: databaseType.rawValue) == nil {
+ if declared == nil, SQLLexicalProfile.curated(forDatabaseTypeId: databaseType.rawValue) == nil,
+ language.flatMap({ SQLLexicalProfile.curated(forQueryLanguage: $0) }) == nil {
let backslash = PluginMetadataRegistry.shared.snapshot(for: databaseType)?.editor.sqlDialect?
.requiresBackslashEscaping ?? false
return SQLStringEscapes(backslashEscapes: backslash)
}
let escapes = SQLLexicalReadings.stringEscapes(
databaseTypeId: databaseType.rawValue,
+ queryLanguage: language,
declared: declared,
session: session.map(SQLSessionLexicalFacts.init(pluginState:))
)
@@ -90,6 +94,13 @@ enum SQLLexicalResolver {
DatabaseManager.shared.driver(for: connectionId)?.sessionLexicalState
}
+ private static func queryLanguage(for databaseType: DatabaseType) -> String? {
+ guard case .custom(let language)? = PluginMetadataRegistry.shared.queryLanguage(for: databaseType) else {
+ return nil
+ }
+ return language
+ }
+
private static func declaredGrammar(for databaseType: DatabaseType) -> SQLLexicalGrammar? {
PluginMetadataRegistry.shared.snapshot(for: databaseType)?.editor.sqlDialect?.lexicalFeatures
.map(SQLLexicalGrammar.init(pluginFeatures:))
diff --git a/apple/TableProMobile/TableProMobile/SSH/HostKeyStore.swift b/apple/TableProMobile/TableProMobile/SSH/HostKeyStore.swift
index cad6cd0f96..680e3445ff 100644
--- a/apple/TableProMobile/TableProMobile/SSH/HostKeyStore.swift
+++ b/apple/TableProMobile/TableProMobile/SSH/HostKeyStore.swift
@@ -1,131 +1,14 @@
-import CryptoKit
import Foundation
-import os
import TableProSSHTransport
-nonisolated final class HostKeyStore: @unchecked Sendable {
- static let shared = HostKeyStore()
-
- private static let logger = Logger(subsystem: "com.TablePro", category: "HostKeyStore")
-
- enum VerificationResult: Equatable {
- case trusted
- case unknown(fingerprint: String, keyType: String)
- case mismatch(expected: String, actual: String)
- // The file is one entry per line split on spaces, so a host with a line break would plant
- // an entry for another host.
- case invalidHost(SSHDestinationName.Problem)
- // The saved keys could not be read, so a changed key would look like a new host.
- case unreadable
- }
-
- private let filePath: String
- private let lock = NSLock()
-
- private init() {
+extension HostKeyStore {
+ nonisolated static let shared: HostKeyStore = {
guard let appSupport = FileManager.default.urls(
for: .applicationSupportDirectory, in: .userDomainMask
).first else {
- self.filePath = NSTemporaryDirectory() + "TablePro_known_hosts"
- return
+ return HostKeyStore(filePath: NSTemporaryDirectory() + "TablePro_known_hosts")
}
try? FileManager.default.createDirectory(at: appSupport, withIntermediateDirectories: true)
- self.filePath = appSupport.appendingPathComponent("known_hosts").path
- }
-
- init(filePath: String) {
- self.filePath = filePath
- }
-
- func verify(keyData: Data, keyType: String, hostname: String, port: Int) -> VerificationResult {
- lock.lock()
- defer { lock.unlock() }
-
- guard let hostKey = hostIdentifier(hostname, port) else {
- return .invalidHost(.host(hostname))
- }
- guard let file = loadFile() else { return .unreadable }
-
- switch file.match(host: hostKey, keyType: keyType, keyData: keyData) {
- case .trusted:
- return .trusted
- case .unknown:
- Self.logger.info("Unknown host key for \(hostKey)")
- return .unknown(fingerprint: Self.fingerprint(of: keyData), keyType: keyType)
- case .changed(let storedKey):
- Self.logger.warning("Host key mismatch for \(hostKey)")
- return .mismatch(expected: Self.fingerprint(of: storedKey), actual: Self.fingerprint(of: keyData))
- case .unreadable:
- Self.logger.error("The saved host key for \(hostKey) could not be parsed")
- return .unreadable
- }
- }
-
- func trust(hostname: String, port: Int, key: Data, keyType: String) {
- lock.lock()
- defer { lock.unlock() }
-
- guard let hostKey = hostIdentifier(hostname, port), var file = loadFile() else { return }
- file.trust(host: hostKey, keyType: keyType, keyData: key)
- saveFile(file)
- }
-
- func remove(hostname: String, port: Int) {
- lock.lock()
- defer { lock.unlock() }
-
- guard let hostKey = hostIdentifier(hostname, port), var file = loadFile() else { return }
- if file.remove(host: hostKey) {
- saveFile(file)
- }
- }
-
- func trustedHosts() -> [String] {
- lock.lock()
- defer { lock.unlock() }
- return Array(Set((loadFile()?.entries ?? []).map(\.host))).sorted()
- }
-
- static func keyTypeName(_ type: Int32) -> String {
- switch type {
- case 1: return "ssh-rsa"
- case 2: return "ssh-dss"
- case 3: return "ecdsa-sha2-nistp256"
- case 4: return "ecdsa-sha2-nistp384"
- case 5: return "ecdsa-sha2-nistp521"
- case 6: return "ssh-ed25519"
- default: return "unknown"
- }
- }
-
- static func fingerprint(of key: Data) -> String {
- let digest = SHA256.hash(data: key)
- return "SHA256:" + Data(digest).base64EncodedString().replacingOccurrences(of: "=", with: "")
- }
-
- private func hostIdentifier(_ hostname: String, _ port: Int) -> String? {
- guard SSHDestinationName.isValidHost(hostname) else {
- Self.logger.warning("Refusing a host key entry for a host ssh would refuse")
- return nil
- }
- return "[\(hostname)]:\(port)"
- }
-
- // nil means the file is there but unreadable, and nothing may be written over it.
- private func loadFile() -> KnownHostsFile? {
- do {
- return try KnownHostsFile.load(from: URL(fileURLWithPath: filePath))
- } catch {
- Self.logger.error("Failed to read known_hosts file: \(error.localizedDescription)")
- return nil
- }
- }
-
- private func saveFile(_ file: KnownHostsFile) {
- do {
- try file.contents.write(toFile: filePath, atomically: true, encoding: .utf8)
- } catch {
- Self.logger.error("Failed to write known_hosts file: \(error.localizedDescription)")
- }
- }
+ return HostKeyStore(filePath: appSupport.appendingPathComponent("known_hosts").path)
+ }()
}
diff --git a/apple/TableProMobile/TableProMobileTests/SSH/HostKeyStorePathTests.swift b/apple/TableProMobile/TableProMobileTests/SSH/HostKeyStorePathTests.swift
new file mode 100644
index 0000000000..8215867e57
--- /dev/null
+++ b/apple/TableProMobile/TableProMobileTests/SSH/HostKeyStorePathTests.swift
@@ -0,0 +1,14 @@
+import Foundation
+import TableProSSHTransport
+import Testing
+
+@testable import TableProMobile
+
+struct HostKeyStorePathTests {
+ @Test("Host keys stay in known_hosts in Application Support, where earlier releases read them")
+ func knownHostsPath() throws {
+ let appSupport = try #require(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)
+
+ #expect(HostKeyStore.shared.filePath == appSupport.appendingPathComponent("known_hosts").path)
+ }
+}
diff --git a/apple/TableProMobile/TableProMobileTests/SSH/HostKeyStoreTests.swift b/apple/TableProMobile/TableProMobileTests/SSH/HostKeyStoreTests.swift
deleted file mode 100644
index 2cd9ff8df5..0000000000
--- a/apple/TableProMobile/TableProMobileTests/SSH/HostKeyStoreTests.swift
+++ /dev/null
@@ -1,192 +0,0 @@
-import Foundation
-import TableProSSHTransport
-import Testing
-
-@testable import TableProMobile
-
-@Suite("HostKeyStore")
-struct HostKeyStoreTests {
- private func makeTempFilePath() -> String {
- (NSTemporaryDirectory() as NSString).appendingPathComponent("test_known_hosts_\(UUID().uuidString)")
- }
-
- private func makeTestKey(_ seed: UInt8) -> Data {
- Data(repeating: seed, count: 32)
- }
-
- @Test("An unseen host is unknown, not trusted")
- func unknownHostIsNotTrusted() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key = makeTestKey(0xAA)
-
- #expect(
- store.verify(keyData: key, keyType: "ssh-ed25519", hostname: "db.example.com", port: 22)
- == .unknown(fingerprint: HostKeyStore.fingerprint(of: key), keyType: "ssh-ed25519")
- )
- }
-
- @Test("A trusted key verifies on the next connect")
- func trustedKeyVerifies() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key = makeTestKey(0xBB)
-
- store.trust(hostname: "db.example.com", port: 22, key: key, keyType: "ssh-ed25519")
-
- #expect(store.verify(keyData: key, keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .trusted)
- }
-
- @Test("A changed key is a mismatch")
- func changedKeyIsMismatch() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let trusted = makeTestKey(0xCC)
- let presented = makeTestKey(0xDD)
-
- store.trust(hostname: "db.example.com", port: 22, key: trusted, keyType: "ssh-ed25519")
-
- #expect(
- store.verify(keyData: presented, keyType: "ssh-ed25519", hostname: "db.example.com", port: 22)
- == .mismatch(
- expected: HostKeyStore.fingerprint(of: trusted),
- actual: HostKeyStore.fingerprint(of: presented)
- )
- )
- }
-
- @Test("A different key type for a known host is a mismatch, not a first-use prompt")
- func differentKeyTypeIsMismatch() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let trusted = makeTestKey(0xEE)
- let attacker = makeTestKey(0xEF)
-
- store.trust(hostname: "db.example.com", port: 22, key: trusted, keyType: "ssh-ed25519")
-
- #expect(
- store.verify(keyData: attacker, keyType: "ssh-rsa", hostname: "db.example.com", port: 22)
- == .mismatch(
- expected: HostKeyStore.fingerprint(of: trusted),
- actual: HostKeyStore.fingerprint(of: attacker)
- )
- )
- }
-
- @Test("Hosts on different ports are tracked separately")
- func portsAreSeparateEntries() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key = makeTestKey(0x11)
-
- store.trust(hostname: "db.example.com", port: 22, key: key, keyType: "ssh-ed25519")
-
- #expect(store.verify(keyData: key, keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .trusted)
- if case .trusted = store.verify(
- keyData: key, keyType: "ssh-ed25519", hostname: "db.example.com", port: 2222
- ) {
- Issue.record("Port 2222 should not inherit trust from port 22")
- }
- }
-
- @Test("Removing a host clears every key type stored for it")
- func removeClearsAllKeyTypes() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- store.trust(hostname: "db.example.com", port: 22, key: makeTestKey(0x21), keyType: "ssh-rsa")
- store.trust(hostname: "db.example.com", port: 22, key: makeTestKey(0x22), keyType: "ssh-ed25519")
-
- store.remove(hostname: "db.example.com", port: 22)
-
- #expect(store.trustedHosts().isEmpty)
- }
-
- @Test("A saved key file that cannot be read checks no key and is never written over")
- func unreadableFileChecksNothing() throws {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- store.trust(hostname: "db.example.com", port: 22, key: makeTestKey(0x31), keyType: "ssh-ed25519")
- let saved = try String(contentsOfFile: path, encoding: .utf8)
- try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: path)
-
- #expect(
- store.verify(keyData: makeTestKey(0x32), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22)
- == .unreadable
- )
- store.trust(hostname: "other.example.com", port: 22, key: makeTestKey(0x33), keyType: "ssh-ed25519")
- store.remove(hostname: "db.example.com", port: 22)
-
- try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)
- let after = try String(contentsOfFile: path, encoding: .utf8)
- #expect(after == saved)
- #expect(store.verify(keyData: makeTestKey(0x31), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22) == .trusted)
- }
-
- @Test("A saved line that cannot be parsed keeps its host from looking new, and stays in the file")
- func unparsedLineIsKept() throws {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let unparsed = "[db.example.com]:22 ssh-ed25519 !!not-base64!!"
- try (unparsed + "\n").write(toFile: path, atomically: true, encoding: .utf8)
- let store = HostKeyStore(filePath: path)
-
- #expect(
- store.verify(keyData: makeTestKey(0x41), keyType: "ssh-ed25519", hostname: "db.example.com", port: 22)
- == .unreadable
- )
- store.trust(hostname: "other.example.com", port: 22, key: makeTestKey(0x42), keyType: "ssh-ed25519")
-
- let contents = try String(contentsOfFile: path, encoding: .utf8)
- #expect(contents.hasPrefix(unparsed + "\n"))
- #expect(store.verify(keyData: makeTestKey(0x42), keyType: "ssh-ed25519", hostname: "other.example.com", port: 22) == .trusted)
- }
-
- @Test("Fingerprints use the OpenSSH SHA256 form")
- func fingerprintFormat() {
- let fingerprint = HostKeyStore.fingerprint(of: Data("tablepro".utf8))
- #expect(fingerprint.hasPrefix("SHA256:"))
- #expect(!fingerprint.contains("="))
- }
-
- @Test("A host with a line break plants no key for another host", arguments: [
- "replica.attacker.example\n[prod.corp.example",
- "replica.attacker.example\r\n[prod.corp.example",
- "replica.attacker.example [prod.corp.example",
- ])
- func lineBreakInHostPlantsNoEntry(hostile: String) {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let real = makeTestKey(0x01)
- let forged = makeTestKey(0x02)
- store.trust(hostname: "prod.corp.example", port: 22, key: real, keyType: "ssh-ed25519")
-
- #expect(
- store.verify(keyData: forged, keyType: "ssh-ed25519", hostname: hostile, port: 22)
- == .invalidHost(.host(hostile))
- )
- store.trust(hostname: hostile, port: 22, key: forged, keyType: "ssh-ed25519")
-
- #expect(
- store.verify(keyData: forged, keyType: "ssh-ed25519", hostname: "prod.corp.example", port: 22)
- == .mismatch(expected: HostKeyStore.fingerprint(of: real), actual: HostKeyStore.fingerprint(of: forged))
- )
- #expect(store.verify(keyData: real, keyType: "ssh-ed25519", hostname: "prod.corp.example", port: 22) == .trusted)
- }
-}
diff --git a/apple/TableProMobile/TableProMobileTests/SSH/HostKeyVerifierTests.swift b/apple/TableProMobile/TableProMobileTests/SSH/HostKeyVerifierTests.swift
index 015811f074..1988aa8b30 100644
--- a/apple/TableProMobile/TableProMobileTests/SSH/HostKeyVerifierTests.swift
+++ b/apple/TableProMobile/TableProMobileTests/SSH/HostKeyVerifierTests.swift
@@ -1,6 +1,7 @@
import Foundation
import TableProDatabase
@testable import TableProMobile
+import TableProSSHTransport
import Testing
@MainActor
diff --git a/apple/TableProTests/Core/Plugins/ClickHouseDialectParityTests.swift b/apple/TableProTests/Core/Plugins/ClickHouseDialectParityTests.swift
index 5f3c529b80..8ec724caca 100644
--- a/apple/TableProTests/Core/Plugins/ClickHouseDialectParityTests.swift
+++ b/apple/TableProTests/Core/Plugins/ClickHouseDialectParityTests.swift
@@ -2,10 +2,9 @@
// ClickHouseDialectParityTests.swift
// TableProTests
//
-// The ClickHouse dialect is declared twice: once on the plugin, and once in the app's curated
-// pre-load table, which is what a completion service gets before the lazy driver bundle activates.
-// Nothing at runtime makes the two agree, and both shipped the same 18 uppercase function names
-// that the server rejects with UNKNOWN_FUNCTION.
+// The app's curated pre-load table is what a completion service gets before the lazy driver bundle
+// activates. It shipped 18 uppercase function names the server rejects with UNKNOWN_FUNCTION.
+// PluginMetadataCuratedParityTests keeps it equal to the plugin's dialect.
//
import Foundation
@@ -42,25 +41,6 @@ struct ClickHouseDialectParityTests {
#expect(try #require(curatedClickHouseDialect()).functionNamesAreCaseInsensitive == false)
}
- @Test("The plugin and the curated table declare the same function vocabulary")
- func pluginAndCuratedTableAgree() throws {
- let curatedDialect = try #require(curatedClickHouseDialect())
- let pluginDialect = try #require(try BundledPlugin.driver("ClickHouseDriver").sqlDialect)
- let curated = curatedDialect.functions
- let declared = pluginDialect.functions
-
- #expect(!declared.isEmpty, "The ClickHouse plugin declares a function list")
- #expect(pluginDialect.functionNamesAreCaseInsensitive == curatedDialect.functionNamesAreCaseInsensitive)
- #expect(
- declared == curated,
- """
- ClickHousePlugin.swift and PluginMetadataRegistry+RegistryIngredients.swift declare \
- different function vocabularies. Only in plugin: \(declared.subtracting(curated).sorted()). \
- Only in the curated table: \(curated.subtracting(declared).sorted()).
- """
- )
- }
-
private func curatedClickHouseDialect() -> SQLDialectDescriptor? {
PluginMetadataRegistry.shared.builtInDefaults()
.first { $0.typeId == DatabaseType.clickhouse.rawValue }?
diff --git a/apple/TableProTests/Core/Plugins/MySQLConnectionEncodingParityTests.swift b/apple/TableProTests/Core/Plugins/MySQLConnectionEncodingParityTests.swift
index da942d59a4..289647941a 100644
--- a/apple/TableProTests/Core/Plugins/MySQLConnectionEncodingParityTests.swift
+++ b/apple/TableProTests/Core/Plugins/MySQLConnectionEncodingParityTests.swift
@@ -9,13 +9,14 @@ import TableProPluginKit
import Testing
struct MySQLConnectionEncodingParityTests {
- @Test("MySQL and MariaDB curate the same encoding field the plugin declares")
+ // MySQL's own entry is PluginMetadataCuratedParityTests'; a variant keeps its curated fields after the plugin loads.
+ @Test("MariaDB curates the encoding field the MySQL plugin declares")
func curatedFieldsMatchThePlugin() throws {
let declared = try BundledPlugin.driver("MySQLDriver").additionalConnectionFields
let pluginField = try #require(declared.first { $0.id == "mysqlConnectionEncoding" })
let expected = try Self.encoded(pluginField)
let curated = PluginMetadataRegistry.curatedDefaults()
- for typeId in ["MySQL", "MariaDB"] {
+ for typeId in ["MariaDB"] {
let snapshot = try #require(curated.first { $0.typeId == typeId }?.snapshot)
let field = try #require(
snapshot.connection.additionalConnectionFields.first { $0.id == pluginField.id },
diff --git a/apple/TableProTests/Core/Plugins/PluginMetadataCuratedParityTests.swift b/apple/TableProTests/Core/Plugins/PluginMetadataCuratedParityTests.swift
new file mode 100644
index 0000000000..5fa181f061
--- /dev/null
+++ b/apple/TableProTests/Core/Plugins/PluginMetadataCuratedParityTests.swift
@@ -0,0 +1,187 @@
+//
+// PluginMetadataCuratedParityTests.swift
+// TableProTests
+//
+
+import Foundation
+@testable import TablePro
+import TableProPluginKit
+import Testing
+
+// Until a plugin's code loads, the app answers from the type's curated entry; registration then replaces the entry with
+// what the plugin declares, so a field the two disagree on changes the app at the first connect of a launch. Every
+// driver plugin built beside the test host is compared: the bundled ones on every run, the registry ones once AllPlugins
+// built them, which CI's macOS Tests job does before the Unit plan.
+struct PluginMetadataCuratedParityTests {
+ @Test("Each built driver plugin registers exactly the entry the app curates for its type")
+ func pluginsRegisterTheirCuratedEntries() throws {
+ let curated = Dictionary(
+ PluginMetadataRegistry.shared.builtInDefaults().map { ($0.typeId, $0.snapshot) },
+ uniquingKeysWith: { first, _ in first }
+ )
+ var compared: [String] = []
+ for url in BuiltPlugins.bundleURLs() {
+ let name = url.deletingPathExtension().lastPathComponent
+ guard let bundle = Bundle(url: url) else {
+ Issue.record("\(name) is not a bundle")
+ continue
+ }
+ do {
+ try bundle.loadAndReturnError()
+ } catch {
+ Issue.record("\(name) does not load: \(error)")
+ continue
+ }
+ guard let driver = bundle.principalClass as? any DriverPlugin.Type else {
+ let provides = bundle.object(forInfoDictionaryKey: "TableProProvidesDatabaseTypeIds") as? [String] ?? []
+ if !provides.isEmpty {
+ Issue.record("\(name) provides \(provides) but its principal class is no DriverPlugin")
+ }
+ continue
+ }
+ let typeId = driver.databaseTypeId
+ guard let entry = curated[typeId] else {
+ Issue.record("\(name) serves \(typeId), which has no curated entry")
+ continue
+ }
+ compared.append(typeId)
+ let built = PluginMetadataRegistry.metadataSnapshot(
+ from: driver,
+ isDownloadable: driver.isDownloadable,
+ existing: entry
+ )
+ let registered = PluginMetadataRegistry.adoptingCuratedEntry(
+ built.withBranding(from: entry),
+ registryDefault: entry,
+ typeId: typeId
+ )
+ // A curated explain list is only the fallback for a plugin that declares none, and Oracle and SQL Server keep
+ // it empty so a plugin without its own plans offers no Explain.
+ let checked = entry.explainVariants.isEmpty ? registered.withExplainVariants([]) : registered
+ for difference in SnapshotDifferences.between(curated: entry, registered: checked) {
+ Issue.record("\(typeId) \(difference)")
+ }
+ }
+ let bundledDrivers: Set = ["MySQL", "PostgreSQL", "SQLite", "ClickHouse", "Redis"]
+ #expect(bundledDrivers.isSubset(of: Set(compared)), "Compared only \(compared)")
+ }
+}
+
+private enum BuiltPlugins {
+ // The products folder holds every plugin the last build made. A bundled one loads from the app's own PlugIns, as
+ // BundledPlugin loads it, so its classes are never loaded from two images.
+ static func bundleURLs() -> [URL] {
+ let embedded = Bundle.main.builtInPlugInsURL
+ let products = Bundle.main.bundleURL.deletingLastPathComponent()
+ var byName: [String: URL] = [:]
+ for folder in [products, embedded].compactMap({ $0 }) {
+ let contents = (try? FileManager.default.contentsOfDirectory(
+ at: folder, includingPropertiesForKeys: nil
+ )) ?? []
+ for url in contents where url.pathExtension == "tableplugin" {
+ byName[url.deletingPathExtension().lastPathComponent] = url
+ }
+ }
+ return byName.keys.sorted().compactMap { byName[$0] }
+ }
+}
+
+// Each stored field, by its path, whose value reads differently in the two snapshots.
+private enum SnapshotDifferences {
+ static func between(curated: Any, registered: Any) -> [String] {
+ differences(curated, registered, path: "")
+ }
+
+ private static func differences(_ curated: Any, _ registered: Any, path: String) -> [String] {
+ let left = Mirror(reflecting: curated)
+ let right = Mirror(reflecting: registered)
+ if left.displayStyle == .struct, right.displayStyle == .struct, left.children.count == right.children.count {
+ return zip(left.children, right.children).flatMap { pair in
+ differences(pair.0.value, pair.1.value, path: joined(path, pair.0.label ?? "?"))
+ }
+ }
+ if left.displayStyle == .optional, right.displayStyle == .optional,
+ let wrappedLeft = left.children.first?.value, let wrappedRight = right.children.first?.value {
+ return differences(wrappedLeft, wrappedRight, path: path)
+ }
+ if left.displayStyle == .dictionary, right.displayStyle == .dictionary {
+ let curatedEntries = entries(left)
+ let registeredEntries = entries(right)
+ return Set(curatedEntries.keys).union(registeredEntries.keys).sorted().flatMap { key -> [String] in
+ let entryPath = "\(path)[\(key)]"
+ switch (curatedEntries[key], registeredEntries[key]) {
+ case let (curatedValue?, registeredValue?):
+ return differences(curatedValue, registeredValue, path: entryPath)
+ case (nil, _):
+ return ["\(entryPath): only the plugin has it"]
+ case (_, nil):
+ return ["\(entryPath): only the curated entry has it"]
+ }
+ }
+ }
+ if left.displayStyle == .collection, right.displayStyle == .collection,
+ left.children.count == right.children.count {
+ return zip(left.children, right.children).enumerated().flatMap { index, pair in
+ differences(pair.0.value, pair.1.value, path: "\(path)[\(index)]")
+ }
+ }
+ let curatedText = canonical(curated)
+ let registeredText = canonical(registered)
+ guard curatedText != registeredText else { return [] }
+ if [left.displayStyle, right.displayStyle].allSatisfy({ $0 == .set || $0 == .collection }) {
+ let curatedElements = left.children.map { canonical($0.value) }
+ let registeredElements = right.children.map { canonical($0.value) }
+ let onlyCurated = curatedElements.filter { !registeredElements.contains($0) }.sorted()
+ let onlyPlugin = registeredElements.filter { !curatedElements.contains($0) }.sorted()
+ return [
+ "\(path): only the curated entry has \(clipped(onlyCurated.joined(separator: ", "))); "
+ + "only the plugin has \(clipped(onlyPlugin.joined(separator: ", ")))"
+ + (onlyCurated.isEmpty && onlyPlugin.isEmpty ? " (same elements, another order)" : "")
+ ]
+ }
+ return ["\(path): curated \(clipped(curatedText)), plugin \(clipped(registeredText))"]
+ }
+
+ private static func entries(_ mirror: Mirror) -> [String: Any] {
+ var result: [String: Any] = [:]
+ for child in mirror.children {
+ let pair = Array(Mirror(reflecting: child.value).children)
+ guard pair.count == 2 else { continue }
+ result[canonical(pair[0].value)] = pair[1].value
+ }
+ return result
+ }
+
+ // The same text for equal values: a set's or a dictionary's elements are sorted.
+ static func canonical(_ value: Any) -> String {
+ let mirror = Mirror(reflecting: value)
+ let children = mirror.children.map { child in
+ (label: child.label, text: canonical(child.value))
+ }
+ switch mirror.displayStyle {
+ case .set?, .dictionary?:
+ return "{" + children.map { $0.text }.sorted().joined(separator: ", ") + "}"
+ case .optional?:
+ return children.first?.text ?? "nil"
+ case .collection?:
+ return "[" + children.map { $0.text }.joined(separator: ", ") + "]"
+ case .enum?:
+ guard let payload = children.first else { return String(describing: value) }
+ return "\(payload.label ?? "?")(\(payload.text))"
+ case .struct?, .class?, .tuple?:
+ guard !children.isEmpty else { return String(describing: value) }
+ let fields = children.map { child in child.label.map { "\($0): \(child.text)" } ?? child.text }
+ return "\(mirror.subjectType)(" + fields.joined(separator: ", ") + ")"
+ default:
+ return String(reflecting: value)
+ }
+ }
+
+ private static func joined(_ path: String, _ label: String) -> String {
+ path.isEmpty ? label : "\(path).\(label)"
+ }
+
+ private static func clipped(_ text: String) -> String {
+ text.count <= 600 ? text : String(text.prefix(600)) + "..."
+ }
+}
diff --git a/apple/TableProTests/Core/SSH/HostKeyStorePathTests.swift b/apple/TableProTests/Core/SSH/HostKeyStorePathTests.swift
new file mode 100644
index 0000000000..600833d6f6
--- /dev/null
+++ b/apple/TableProTests/Core/SSH/HostKeyStorePathTests.swift
@@ -0,0 +1,17 @@
+import Foundation
+import TableProSSHTransport
+import Testing
+
+@testable import TablePro
+
+struct HostKeyStorePathTests {
+ @Test("Host keys stay in TablePro/known_hosts under the storage root, where earlier releases read them")
+ func knownHostsPath() {
+ let expected = AppStorageEnvironment.shared.applicationSupportRoot
+ .appendingPathComponent("TablePro")
+ .appendingPathComponent("known_hosts")
+ .path
+
+ #expect(HostKeyStore.shared.filePath == expected)
+ }
+}
diff --git a/apple/TableProTests/Core/SSH/HostKeyStoreTests.swift b/apple/TableProTests/Core/SSH/HostKeyStoreTests.swift
deleted file mode 100644
index 3b0ede681d..0000000000
--- a/apple/TableProTests/Core/SSH/HostKeyStoreTests.swift
+++ /dev/null
@@ -1,283 +0,0 @@
-import Foundation
-import TableProPluginKit
-import TableProSSHTransport
-import Testing
-
-@testable import TablePro
-
-struct HostKeyStoreTests {
- private func makeTempFilePath() -> String {
- let tempDir = NSTemporaryDirectory()
- return (tempDir as NSString).appendingPathComponent("test_known_hosts_\(UUID().uuidString)")
- }
-
- private func makeTestKey(_ seed: UInt8 = 0x42, length: Int = 32) -> Data {
- Data(repeating: seed, count: length)
- }
-
- @Test("Trust a host and verify returns .trusted")
- func testTrustAndVerify() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key = makeTestKey(0xAA)
-
- store.trust(hostname: "example.com", port: 22, key: key, keyType: "ssh-rsa")
-
- let result = store.verify(keyData: key, keyType: "ssh-rsa", hostname: "example.com", port: 22)
- #expect(result == .trusted)
- }
-
- @Test("Verify unknown host returns .unknown with fingerprint and key type")
- func testUnknownHost() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key = makeTestKey(0xBB)
- let expectedFingerprint = HostKeyStore.fingerprint(of: key)
-
- let result = store.verify(keyData: key, keyType: "ssh-ed25519", hostname: "unknown.host", port: 22)
- #expect(result == .unknown(fingerprint: expectedFingerprint, keyType: "ssh-ed25519"))
- }
-
- @Test("Changed key returns .mismatch with expected and actual fingerprints")
- func testMismatch() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let originalKey = makeTestKey(0xCC)
- let changedKey = makeTestKey(0xDD)
-
- store.trust(hostname: "example.com", port: 22, key: originalKey, keyType: "ssh-rsa")
-
- let expectedFingerprint = HostKeyStore.fingerprint(of: originalKey)
- let actualFingerprint = HostKeyStore.fingerprint(of: changedKey)
-
- let result = store.verify(keyData: changedKey, keyType: "ssh-rsa", hostname: "example.com", port: 22)
- #expect(result == .mismatch(expected: expectedFingerprint, actual: actualFingerprint))
- }
-
- @Test("A different key type for a known host is a mismatch, not a first-use prompt")
- func testDifferentKeyTypeForKnownHostIsMismatch() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let trustedKey = makeTestKey(0xEE)
- let attackerKey = makeTestKey(0xEF)
-
- store.trust(hostname: "example.com", port: 22, key: trustedKey, keyType: "ssh-ed25519")
-
- let result = store.verify(keyData: attackerKey, keyType: "ssh-rsa", hostname: "example.com", port: 22)
- #expect(
- result == .mismatch(
- expected: HostKeyStore.fingerprint(of: trustedKey),
- actual: HostKeyStore.fingerprint(of: attackerKey)
- )
- )
- }
-
- @Test("A host trusted under two key types verifies either one")
- func testTrustedKeyOfEitherTypeVerifies() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let rsaKey = makeTestKey(0x11)
- let edKey = makeTestKey(0x22)
-
- store.trust(hostname: "example.com", port: 22, key: rsaKey, keyType: "ssh-rsa")
- store.trust(hostname: "example.com", port: 22, key: edKey, keyType: "ssh-ed25519")
-
- #expect(store.verify(keyData: rsaKey, keyType: "ssh-rsa", hostname: "example.com", port: 22) == .trusted)
- #expect(store.verify(keyData: edKey, keyType: "ssh-ed25519", hostname: "example.com", port: 22) == .trusted)
- }
-
- @Test("Remove a host key then verify returns .unknown")
- func testRemove() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key = makeTestKey(0xEE)
-
- store.trust(hostname: "example.com", port: 22, key: key, keyType: "ssh-rsa")
- #expect(store.verify(keyData: key, keyType: "ssh-rsa", hostname: "example.com", port: 22) == .trusted)
-
- store.remove(hostname: "example.com", port: 22)
-
- let result = store.verify(keyData: key, keyType: "ssh-rsa", hostname: "example.com", port: 22)
- guard case .unknown = result else {
- Issue.record("Expected .unknown after removal, got \(result)")
- return
- }
- }
-
- @Test("SHA256 fingerprint format is correct")
- func testFingerprint() {
- let key = makeTestKey(0xFF, length: 64)
- let fingerprint = HostKeyStore.fingerprint(of: key)
-
- #expect(fingerprint.hasPrefix("SHA256:"))
- #expect(!fingerprint.contains("="))
-
- let fingerprint2 = HostKeyStore.fingerprint(of: key)
- #expect(fingerprint == fingerprint2)
-
- let otherKey = makeTestKey(0x00, length: 64)
- let otherFingerprint = HostKeyStore.fingerprint(of: otherKey)
- #expect(fingerprint != otherFingerprint)
- }
-
- @Test("Multiple hosts are stored and verified independently")
- func testMultipleHosts() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key1 = makeTestKey(0x11)
- let key2 = makeTestKey(0x22)
- let key3 = makeTestKey(0x33)
-
- store.trust(hostname: "host-a.com", port: 22, key: key1, keyType: "ssh-rsa")
- store.trust(hostname: "host-b.com", port: 22, key: key2, keyType: "ssh-ed25519")
- store.trust(hostname: "host-c.com", port: 22, key: key3, keyType: "ecdsa-sha2-nistp256")
-
- #expect(store.verify(keyData: key1, keyType: "ssh-rsa", hostname: "host-a.com", port: 22) == .trusted)
- #expect(store.verify(keyData: key2, keyType: "ssh-ed25519", hostname: "host-b.com", port: 22) == .trusted)
- #expect(store.verify(keyData: key3, keyType: "ecdsa-sha2-nistp256", hostname: "host-c.com", port: 22) == .trusted)
-
- store.remove(hostname: "host-b.com", port: 22)
- #expect(store.verify(keyData: key1, keyType: "ssh-rsa", hostname: "host-a.com", port: 22) == .trusted)
- #expect(store.verify(keyData: key3, keyType: "ecdsa-sha2-nistp256", hostname: "host-c.com", port: 22) == .trusted)
- }
-
- @Test("Same hostname with different ports are separate entries")
- func testPortDifferentiation() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let key22 = makeTestKey(0x44)
- let key2222 = makeTestKey(0x55)
-
- store.trust(hostname: "example.com", port: 22, key: key22, keyType: "ssh-rsa")
- store.trust(hostname: "example.com", port: 2222, key: key2222, keyType: "ssh-ed25519")
-
- #expect(store.verify(keyData: key22, keyType: "ssh-rsa", hostname: "example.com", port: 22) == .trusted)
- #expect(store.verify(keyData: key2222, keyType: "ssh-ed25519", hostname: "example.com", port: 2222) == .trusted)
-
- let result = store.verify(keyData: key22, keyType: "ssh-rsa", hostname: "example.com", port: 2222)
- guard case .mismatch = result else {
- Issue.record("Expected .mismatch when using wrong port's key, got \(result)")
- return
- }
- }
-
- @Test("Key type name mapping from numeric constants")
- func testKeyTypeName() {
- #expect(HostKeyStore.keyTypeName(1) == "ssh-rsa")
- #expect(HostKeyStore.keyTypeName(2) == "ssh-dss")
- #expect(HostKeyStore.keyTypeName(3) == "ecdsa-sha2-nistp256")
- #expect(HostKeyStore.keyTypeName(4) == "ecdsa-sha2-nistp384")
- #expect(HostKeyStore.keyTypeName(5) == "ecdsa-sha2-nistp521")
- #expect(HostKeyStore.keyTypeName(6) == "ssh-ed25519")
- #expect(HostKeyStore.keyTypeName(0) == "unknown")
- #expect(HostKeyStore.keyTypeName(99) == "unknown")
- }
-
- @Test("Trusting the same host and key type again updates the stored key")
- func testTrustUpdatesExistingEntry() {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let oldKey = makeTestKey(0x66)
- let newKey = makeTestKey(0x77)
-
- store.trust(hostname: "example.com", port: 22, key: oldKey, keyType: "ssh-rsa")
- #expect(store.verify(keyData: oldKey, keyType: "ssh-rsa", hostname: "example.com", port: 22) == .trusted)
-
- store.trust(hostname: "example.com", port: 22, key: newKey, keyType: "ssh-rsa")
- #expect(store.verify(keyData: newKey, keyType: "ssh-rsa", hostname: "example.com", port: 22) == .trusted)
-
- let result = store.verify(keyData: oldKey, keyType: "ssh-rsa", hostname: "example.com", port: 22)
- guard case .mismatch = result else {
- Issue.record("Expected .mismatch for old key after update, got \(result)")
- return
- }
- }
-
- @Test("A saved key file that cannot be read checks no key and is never written over")
- func testUnreadableFileChecksNothing() throws {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- store.trust(hostname: "example.com", port: 22, key: makeTestKey(0x31), keyType: "ssh-ed25519")
- let saved = try String(contentsOfFile: path, encoding: .utf8)
- try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: path)
-
- #expect(
- store.verify(keyData: makeTestKey(0x32), keyType: "ssh-ed25519", hostname: "example.com", port: 22)
- == .unreadable
- )
- store.trust(hostname: "other.example.com", port: 22, key: makeTestKey(0x33), keyType: "ssh-ed25519")
- store.remove(hostname: "example.com", port: 22)
-
- try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path)
- let after = try String(contentsOfFile: path, encoding: .utf8)
- #expect(after == saved)
- #expect(store.verify(keyData: makeTestKey(0x31), keyType: "ssh-ed25519", hostname: "example.com", port: 22) == .trusted)
- }
-
- @Test("A saved line that cannot be parsed keeps its host from looking new, and stays in the file")
- func testUnparsedLineIsKept() throws {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let unparsed = "[example.com]:22 ssh-ed25519 !!not-base64!!"
- try (unparsed + "\n").write(toFile: path, atomically: true, encoding: .utf8)
- let store = HostKeyStore(filePath: path)
-
- #expect(
- store.verify(keyData: makeTestKey(0x41), keyType: "ssh-ed25519", hostname: "example.com", port: 22)
- == .unreadable
- )
- store.trust(hostname: "other.example.com", port: 22, key: makeTestKey(0x42), keyType: "ssh-ed25519")
-
- let contents = try String(contentsOfFile: path, encoding: .utf8)
- #expect(contents.hasPrefix(unparsed + "\n"))
- #expect(store.verify(keyData: makeTestKey(0x42), keyType: "ssh-ed25519", hostname: "other.example.com", port: 22) == .trusted)
- }
-
- @Test("A host with a line break plants no key for another host", arguments: [
- "replica.attacker.example\n[prod.corp.example",
- "replica.attacker.example\r\n[prod.corp.example",
- "replica.attacker.example [prod.corp.example",
- ])
- func lineBreakInHostPlantsNoEntry(hostile: String) {
- let path = makeTempFilePath()
- defer { try? FileManager.default.removeItem(atPath: path) }
-
- let store = HostKeyStore(filePath: path)
- let real = makeTestKey(0x01)
- let forged = makeTestKey(0x02)
- store.trust(hostname: "prod.corp.example", port: 22, key: real, keyType: "ssh-ed25519")
-
- #expect(
- store.verify(keyData: forged, keyType: "ssh-ed25519", hostname: hostile, port: 22)
- == .invalidHost(.host(hostile))
- )
- store.trust(hostname: hostile, port: 22, key: forged, keyType: "ssh-ed25519")
-
- #expect(
- store.verify(keyData: forged, keyType: "ssh-ed25519", hostname: "prod.corp.example", port: 22)
- == .mismatch(expected: HostKeyStore.fingerprint(of: real), actual: HostKeyStore.fingerprint(of: forged))
- )
- #expect(store.verify(keyData: real, keyType: "ssh-ed25519", hostname: "prod.corp.example", port: 22) == .trusted)
- }
-}
diff --git a/apple/TableProTests/Core/Utilities/SQL/QueryClassifierCypherLanguageTests.swift b/apple/TableProTests/Core/Utilities/SQL/QueryClassifierCypherLanguageTests.swift
new file mode 100644
index 0000000000..1df12058d4
--- /dev/null
+++ b/apple/TableProTests/Core/Utilities/SQL/QueryClassifierCypherLanguageTests.swift
@@ -0,0 +1,111 @@
+//
+// QueryClassifierCypherLanguageTests.swift
+// TableProTests
+//
+
+import Foundation
+@testable import TablePro
+import TableProPluginKit
+import TableProSQLGrammar
+import Testing
+
+// A registry plugin for a graph engine other than Neo4j declares Cypher as its editor language.
+struct QueryClassifierCypherLanguageTests {
+ private func registerEngine(language: EditorLanguage) -> DatabaseType {
+ let typeId = "CypherLanguageFake-\(UUID().uuidString)"
+ PluginMetadataRegistry.shared.register(snapshot: snapshot(typeId: typeId, language: language), forTypeId: typeId)
+ return DatabaseType(rawValue: typeId)
+ }
+
+ private func snapshot(typeId: String, language: EditorLanguage) -> PluginMetadataSnapshot {
+ PluginMetadataSnapshot(
+ displayName: typeId, iconName: "cylinder", defaultPort: 7_687,
+ requiresAuthentication: true, supportsForeignKeys: false, supportsSchemaEditing: false,
+ isDownloadable: true, primaryUrlScheme: "cypherlanguagefake", parameterStyle: .dollar,
+ navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
+ supportsHealthMonitor: false, urlSchemes: [], postConnectActions: [],
+ brandColorHex: "#000000", queryLanguageName: "Cypher", editorLanguage: language,
+ connectionMode: .network, supportsDatabaseSwitching: true,
+ capabilities: .defaults, schema: .defaults, editor: .defaults, connection: .defaults
+ )
+ }
+
+ private func unregister(_ type: DatabaseType) {
+ PluginMetadataRegistry.shared.unregister(typeId: type.rawValue)
+ }
+
+ @Test("Cypher reads are reads on any engine that declares Cypher", arguments: [
+ "MATCH (n:Person) RETURN n LIMIT 25",
+ "MATCH (a)--(b) RETURN a, b",
+ "OPTIONAL MATCH (n)-[r]->(m) RETURN n, r, m",
+ "CALL db.labels()",
+ ])
+ func readsAreReads(query: String) {
+ let type = registerEngine(language: .custom("cypher"))
+ defer { unregister(type) }
+
+ #expect(QueryClassifier.classifyTier(query, databaseType: type) == .safe)
+ #expect(!QueryClassifier.isWriteQuery(query, databaseType: type))
+ #expect(QueryClassifier.isDataStatement(query, databaseType: type))
+ #expect(CatalogChangeClassifier.effect(of: query, databaseType: type) == .none)
+ }
+
+ @Test("Cypher writes are tiered as they are on Neo4j")
+ func writesAreTieredAsOnNeo4j() {
+ let type = registerEngine(language: .custom("cypher"))
+ defer { unregister(type) }
+
+ for query in ["MATCH (n) SET n.seen = true", "CREATE (n:Person {id: 1})", "DROP DATABASE sales"] {
+ #expect(
+ QueryClassifier.classifyTier(query, databaseType: type)
+ == QueryClassifier.classifyTier(query, databaseType: .neo4j),
+ "\(query)"
+ )
+ }
+ #expect(CatalogChangeClassifier.effect(of: "CREATE (n:Person)", databaseType: type) == .opaque)
+ #expect(!QueryClassifier.isDataStatement("CREATE INDEX FOR (n:Person) ON (n.id)", databaseType: type))
+ }
+
+ @Test("An unfiltered Cypher delete is dangerous and a filtered one is not")
+ func unfilteredDeleteIsDangerous() {
+ let type = registerEngine(language: .custom("cypher"))
+ defer { unregister(type) }
+
+ #expect(QueryClassifier.isDangerousQuery("MATCH (n) DETACH DELETE n", databaseType: type))
+ #expect(!QueryClassifier.isDangerousQuery("MATCH (n) WHERE n.id = 1 DELETE n", databaseType: type))
+ }
+
+ @Test("A Cypher engine is split as Neo4j is, so `--` in a pattern is no comment")
+ func lexesAsNeo4j() {
+ let type = registerEngine(language: .custom("cypher"))
+ defer { unregister(type) }
+
+ #expect(type.lexicalReadings == DatabaseType.neo4j.lexicalReadings)
+ let script = "MATCH (a)--(b) RETURN a; MATCH (c) RETURN c"
+ #expect(QueryClassifier.statements(of: script, grammar: type.lexicalGrammar).count == 2)
+ }
+
+ @Test("A plugin that declares Cypher for an engine the app curates as SQL keeps the SQL gates")
+ func curatedLanguageWins() {
+ let queries = ["TRUNCATE orders", "DELETE FROM orders", "MATCH (n) RETURN n"]
+ let before = queries.map { QueryClassifier.classifyTier($0, databaseType: .postgresql) }
+ let readings = DatabaseType.postgresql.lexicalReadings
+ PluginMetadataRegistry.shared.register(
+ snapshot: snapshot(typeId: DatabaseType.postgresql.rawValue, language: .custom("cypher")),
+ forTypeId: DatabaseType.postgresql.rawValue
+ )
+ defer { unregister(.postgresql) }
+
+ #expect(queries.map { QueryClassifier.classifyTier($0, databaseType: .postgresql) } == before)
+ #expect(QueryClassifier.isDangerousQuery("DELETE FROM orders", databaseType: .postgresql))
+ #expect(DatabaseType.postgresql.lexicalReadings == readings)
+ }
+
+ @Test("The same text on an engine that declares SQL takes the SQL reading")
+ func sqlEngineIsNotReadAsCypher() {
+ let type = registerEngine(language: .sql)
+ defer { unregister(type) }
+
+ #expect(QueryClassifier.classifyTier("MATCH (n:Person) RETURN n", databaseType: type) == .write)
+ }
+}
diff --git a/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift b/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift
index eb7cf76f0d..b39cb3df8f 100644
--- a/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift
+++ b/apple/TableProTests/Services/SchemaRefreshCommitCostTests.swift
@@ -254,8 +254,8 @@ struct SchemaRefreshCommitCostTests {
await refreshService.refreshAfterWrite(connection: connection)
- #expect(Set(driver.perSchemaReads) == ["tables:S0", "routines:S0"])
- #expect(driver.perSchemaReads.count == 2)
+ #expect(Set(driver.perSchemaReads) == ["tables:S0", "routines:S0", "triggers:S0"])
+ #expect(driver.perSchemaReads.count == 3)
#expect(schemaService.tables(for: connectionId, schema: "S199").map(\.name) == ["S199_ORDERS"])
}
}
diff --git a/apple/TableProTests/Services/SchemaServiceStaleSchemaTests.swift b/apple/TableProTests/Services/SchemaServiceStaleSchemaTests.swift
index e02c7675c1..4dd359f9c6 100644
--- a/apple/TableProTests/Services/SchemaServiceStaleSchemaTests.swift
+++ b/apple/TableProTests/Services/SchemaServiceStaleSchemaTests.swift
@@ -72,7 +72,7 @@ struct SchemaServiceStaleSchemaTests {
await service.refreshLoadedSchemaObjects(in: scope, fetchingNow: ["S0", "NEVER_LOADED"], driver: driver)
- #expect(Set(driver.perSchemaReads) == ["tables:S0", "routines:S0"])
+ #expect(Set(driver.perSchemaReads) == ["tables:S0", "routines:S0", "triggers:S0"])
#expect(service.schemasWithCurrentTables(for: connectionId) == ["S0"])
#expect(!service.schemaObjectsNeedFetch(for: connectionId, schema: "S0"))
#expect(service.schemaObjectsNeedFetch(for: connectionId, schema: "S1"))
diff --git a/apple/TableProTests/Views/Sidebar/HierarchicalSchemaSearchTests.swift b/apple/TableProTests/Views/Sidebar/HierarchicalSchemaSearchTests.swift
index 43b201f232..a2fc1a78e2 100644
--- a/apple/TableProTests/Views/Sidebar/HierarchicalSchemaSearchTests.swift
+++ b/apple/TableProTests/Views/Sidebar/HierarchicalSchemaSearchTests.swift
@@ -208,7 +208,7 @@ struct HierarchicalSchemaSearchTests {
}
/// The measured case behind the change: a search over 200 schemas, three of which hold a match.
-/// Before it, the first keystroke loaded every schema, two queries each here and three on Oracle.
+/// Before it, the first keystroke loaded every schema, three queries each on Oracle.
@MainActor
struct HierarchicalSchemaSearchCostTests {
private let connectionId = UUID()
@@ -275,7 +275,7 @@ struct HierarchicalSchemaSearchCostTests {
#expect(matched == ["S1", "S71", "S141"])
#expect(driver.reads.filter { $0 == "allSchemaTables" }.count == 1)
- let matchReads = 3 * 2
+ let matchReads = 3 * 3
#expect(driver.reads.count == 1 + matchReads)
}
@@ -286,7 +286,7 @@ struct HierarchicalSchemaSearchCostTests {
let matched = try await search(schemas, driver: driver)
let listingReads = 1 + 1 + 200
- let matchReads = 3 * 2
+ let matchReads = 3 * 3
#expect(matched == ["S1", "S71", "S141"])
#expect(driver.reads.filter { $0.hasPrefix("routines") }.count == 3)
#expect(driver.reads.count == listingReads + matchReads)
diff --git a/apple/changelog.d/4399.added.md b/apple/changelog.d/4399.added.md
new file mode 100644
index 0000000000..e485d110e5
--- /dev/null
+++ b/apple/changelog.d/4399.added.md
@@ -0,0 +1 @@
+SurrealDB statement completions in the editor once connected.
diff --git a/apple/changelog.d/4399.fixed.md b/apple/changelog.d/4399.fixed.md
new file mode 100644
index 0000000000..83d1cf4a6a
--- /dev/null
+++ b/apple/changelog.d/4399.fixed.md
@@ -0,0 +1 @@
+Copied SQL Server connection URLs started with `sql server://` once the driver had loaded.
diff --git a/apple/scripts/ci/check-capability-parity.py b/apple/scripts/ci/check-capability-parity.py
deleted file mode 100644
index 98b40aec87..0000000000
--- a/apple/scripts/ci/check-capability-parity.py
+++ /dev/null
@@ -1,552 +0,0 @@
-#!/usr/bin/env python3
-"""Fail when a driver capability the app reads before the plugin loads differs from the plugin's own value.
-
-Until a plugin's code loads, the app answers from its curated entry in
-TablePro/Core/Plugins/PluginMetadataRegistry*.swift. PluginMetadataRegistry.buildMetadataSnapshot then copies
-these capabilities straight off the DriverPlugin type, where one the plugin does not declare is PluginKit's
-default. So a value the two sides disagree on changes the UI at the first connect of a launch (#2700).
-
-Only a plugin's primary databaseTypeId is compared: registerVariant keeps a variant's curated entry.
-A value counts only as a literal, written in place or reached through a reference to a declaration that
-holds one, such as HanaMetadata.containerEntityName, cassandraCapabilities or postgreSQL.capabilities.
-Any other expression, and an entry or static the check cannot find or read, is a failure.
-
-Usage:
- check-capability-parity.py [--apple ]
-"""
-
-import argparse
-import re
-import sys
-from pathlib import Path
-
-APPLE_DIR = Path(__file__).resolve().parents[2]
-REGISTRY_GLOB = "TablePro/Core/Plugins/PluginMetadataRegistry*.swift"
-PLUGINKIT_DIR = "TableProPluginKit"
-
-# The app reads these before a plugin loads, from the curated snapshot at this path.
-CAPABILITIES = {
- "supportsHealthMonitor": ("supportsHealthMonitor",),
- "supportsSSH": ("capabilities", "supportsSSH"),
- "supportsSSL": ("capabilities", "supportsSSL"),
- "supportsForeignKeyDisable": ("capabilities", "supportsForeignKeyDisable"),
- "containerEntityName": ("schema", "containerEntityName"),
-}
-
-CONSTRUCTED_TYPES = {"PluginMetadataSnapshot", "CapabilityFlags", "SchemaInfo"}
-# These copy every capability above unchanged. withSwitchRouting takes another snapshot's container name.
-KEEPS_CAPABILITIES = {"withIconName", "withExplainVariants", "withSystemNames", "withBranding", "withIsDownloadable"}
-MAX_HOPS = 16
-
-OPEN, CLOSE = "([{", ")]}"
-TOP_TOKEN = re.compile(r'//|/\*|(#*)("""|")')
-CODE_TOKEN = re.compile(r'//|/\*|(#*)("""|")|[()]')
-COMMENT_TOKEN = re.compile(r"/\*|\*/")
-BRACKET = re.compile(r"[()\[\]{}]")
-CONTINUATION = re.compile(r"\s*\.")
-STRING_TOKENS = {}
-ENTRY = re.compile(r'\(\s*(?:typeId\s*:\s*)?"((?:[^"\\\n]|\\.)*)"\s*,\s*(?:snapshot\s*:\s*)?')
-DECLARATION = re.compile(r"\b(class|struct|enum|actor|extension)\s+([A-Z]\w*)\b([^{};]*)\{")
-STATIC = re.compile(
- r"^[ \t]*(?:@\w+(?:\([^)\n]*\))?\s+)*"
- r"(?:(?:public|private|fileprivate|internal|open|nonisolated|override|final)(?:\([^)\n]*\))?\s+)*"
- r"(?:static\s+(?:let|var)|class\s+var)\s+(\w+)\s*(?::[^={\n]+?)?\s*(=|\{)",
- re.M,
-)
-LABEL = re.compile(r"\s*([A-Za-z_]\w*)\s*:(?!:)")
-CONSTRUCTOR = re.compile(r"(?:[A-Z]\w*\.)*([A-Z]\w*)\s*\(")
-MODIFIER = re.compile(r"\.\s*(\w+)\s*\(")
-SNAPSHOT_PARAMETER = re.compile(r"([a-z]\w*)((?:\.[A-Za-z_]\w*)+)")
-CALL = re.compile(r"(?:Self\.)?([a-z]\w*)\s*\(")
-NAME = re.compile(r"(?:Self\.|PluginMetadataRegistry\.)?([a-z]\w*)")
-MEMBER = re.compile(r"([A-Z]\w*)\.([A-Za-z_]\w*)")
-BOOL = re.compile(r"true|false")
-ESCAPES = {'"': '"', "\\": "\\", "n": "\n", "t": "\t", "r": "\r", "0": "\0", "'": "'"}
-
-
-class Unreadable(Exception):
- pass
-
-
-def mask(text):
- # A bracket or a declaration inside a comment or a string must not count, and an offset into the result
- # must still point at the same character of the original, where a literal's value is read.
- spans = []
- i = 0
- while True:
- token = TOP_TOKEN.search(text, i)
- if not token:
- break
- if token.group(0) == "//":
- end = text.find("\n", token.start())
- end = len(text) if end < 0 else end
- spans.append((token.start(), end, " "))
- elif token.group(0) == "/*":
- end = skip_block_comment(text, token.start())
- spans.append((token.start(), end, " "))
- else:
- hashes, multiline = len(token.group(1)), token.group(2) == '"""'
- close = skip_string(text, token.end(), hashes, multiline)
- spans.append((token.end(), close, "x"))
- end = close + len(token.group(2)) + hashes
- i = end
- out, emitted = [], 0
- for start, end, keep in spans:
- out.append(text[emitted:start])
- out.append(re.sub(r"[^\n]", keep, text[start:end]))
- emitted = end
- out.append(text[emitted:])
- return "".join(out)
-
-
-def skip_block_comment(text, i):
- depth = 0
- for token in COMMENT_TOKEN.finditer(text, i):
- depth += 1 if token.group(0) == "/*" else -1
- if depth == 0:
- return token.end()
- return len(text)
-
-
-def skip_string(text, i, hashes, multiline):
- pattern = STRING_TOKENS.get((hashes, multiline))
- if pattern is None:
- close = re.escape('"""' if multiline else '"') + "#" * hashes
- pattern = STRING_TOKENS[(hashes, multiline)] = re.compile(r"\\" + "#" * hashes + r"(\(|.)|" + close, re.S)
- while True:
- token = pattern.search(text, i)
- if not token:
- raise Unreadable("a string literal is never closed")
- if not token.group(0).startswith("\\"):
- return token.start()
- i = skip_interpolation(text, token.end()) if token.group(1) == "(" else token.end()
-
-
-def skip_interpolation(text, i):
- depth = 0
- while True:
- token = CODE_TOKEN.search(text, i)
- if not token:
- raise Unreadable("an interpolation is never closed")
- lexeme = token.group(0)
- if lexeme == "(":
- depth += 1
- i = token.end()
- elif lexeme == ")":
- if depth == 0:
- return token.end()
- depth -= 1
- i = token.end()
- elif lexeme == "//":
- end = text.find("\n", token.start())
- i = len(text) if end < 0 else end
- elif lexeme == "/*":
- i = skip_block_comment(text, token.start())
- else:
- hashes, quotes = len(token.group(1)), token.group(2)
- i = skip_string(text, token.end(), hashes, quotes == '"""') + len(quotes) + hashes
-
-
-class Source:
- def __init__(self, path, root):
- self.path = path
- self.name = path.relative_to(root).as_posix()
- self.text = path.read_text(encoding="utf-8")
- try:
- self.code = mask(self.text)
- except Unreadable as error:
- raise Unreadable(f"{self.name}: {error}") from error
-
- def where(self, offset):
- return f"{self.name}:{self.text.count(chr(10), 0, offset) + 1}"
-
-
-class Expr:
- def __init__(self, source, start, end):
- while start < end and source.code[start].isspace():
- start += 1
- while end > start and source.code[end - 1].isspace():
- end -= 1
- self.source, self.start, self.end = source, start, end
-
- @property
- def code(self):
- return self.source.code[self.start:self.end]
-
- @property
- def text(self):
- return self.source.text[self.start:self.end]
-
- def where(self):
- return self.source.where(self.start)
-
- def snippet(self):
- flat = " ".join(self.text.split())
- return flat if len(flat) <= 60 else flat[:57] + "..."
-
-
-def matching(code, i):
- depth = 0
- for bracket in BRACKET.finditer(code, i):
- depth += 1 if bracket.group(0) in OPEN else -1
- if depth == 0:
- return bracket.start()
- raise Unreadable("a bracket is never closed")
-
-
-def expression_end(code, i):
- # A line break ends a Swift statement unless the next line goes on with a member, as .withSystemNames(...) does.
- depth, begun = 0, False
- j = i
- while j < len(code):
- c = code[j]
- if c in OPEN:
- depth += 1
- elif c in CLOSE:
- if depth == 0:
- return j
- depth -= 1
- elif depth == 0 and c in ",;":
- return j
- elif depth == 0 and c == "\n" and begun and not CONTINUATION.match(code, j):
- return j
- begun = begun or not c.isspace()
- j += 1
- return j
-
-
-def literal(expr):
- if BOOL.fullmatch(expr.code):
- return expr.code == "true"
- quoted = re.fullmatch(r'(#*)"([^"\n]*)"\1', expr.code)
- if not quoted:
- return None
- hashes = quoted.group(1)
- body = expr.text[len(hashes) + 1:len(expr.text) - len(hashes) - 1]
- if "\\" + hashes + "(" in body:
- return None
- if hashes:
- return body
- value, k = [], 0
- while k < len(body):
- if body[k] == "\\" and k + 1 < len(body) and body[k + 1] in ESCAPES:
- value.append(ESCAPES[body[k + 1]])
- k += 2
- else:
- value.append(body[k])
- k += 1
- return "".join(value)
-
-
-def arguments(expr, open_at):
- source = expr.source
- close = matching(source.code, open_at)
- if close >= expr.end:
- raise Unreadable(f"{expr.where()}: `{expr.snippet()}` is never closed")
- args = {}
- start = open_at + 1
- while start < close:
- end = expression_end(source.code, start)
- if end > close:
- end = close
- label = LABEL.match(source.code, start, end)
- if label:
- name = label.group(1)
- if name in args:
- raise Unreadable(f"{source.where(start)}: passes {name} twice")
- args[name] = Expr(source, label.end(), end)
- start = end + 1
- return args, Expr(source, close + 1, expr.end)
-
-
-def describe(value):
- return ("true" if value else "false") if isinstance(value, bool) else f'"{value}"'
-
-
-def normalized(name):
- return re.sub(r"\W", "", name).lower()
-
-
-class Curated:
- def __init__(self, sources):
- self.sources = sources
- self.entries = {}
- for source in sources:
- for found in ENTRY.finditer(source.text):
- quote = found.start(1) - 1
- if source.code[found.start()] != "(" or source.code[quote] != '"':
- continue
- # A call such as requestTemplate("Scan", ...) is not an entry; a tuple follows a bracket or a comma.
- before = source.code[:found.start()].rstrip()
- if before and (before[-1].isalnum() or before[-1] in "_)]?!>"):
- continue
- type_id = literal(Expr(source, quote, found.end(1) + 1))
- if type_id is None:
- continue
- end = expression_end(source.code, found.end())
- self.entries.setdefault(type_id, []).append(Expr(source, found.end(), end))
-
- def resolve(self, expr, path, hops=0):
- if hops > MAX_HOPS:
- raise Unreadable(f"{expr.where()}: follows more than {MAX_HOPS} references")
- value = literal(expr)
- if value is not None:
- if path:
- raise Unreadable(f"{expr.where()}: `{expr.snippet()}` has no {path[0]}")
- return value, expr.where()
- code = expr.code
-
- constructed = CONSTRUCTOR.match(code)
- if constructed and constructed.group(1) in CONSTRUCTED_TYPES:
- args, tail = arguments(expr, expr.start + constructed.end() - 1)
- self.check_tail(tail)
- if not path:
- raise Unreadable(f"{expr.where()}: `{expr.snippet()}` is not a literal")
- if path[0] not in args:
- raise Unreadable(f"{expr.where()}: {constructed.group(1)}(...) passes no {path[0]}")
- return self.resolve(args[path[0]], path[1:], hops)
-
- parameter = SNAPSHOT_PARAMETER.fullmatch(code)
- if parameter:
- entry = self.entry_for_parameter(parameter.group(1), expr)
- return self.resolve(entry, list(parameter.group(2)[1:].split(".")) + list(path), hops + 1)
-
- call = CALL.match(code)
- if call:
- close = matching(code, call.end() - 1)
- if code[close + 1:].strip():
- raise Unreadable(f"{expr.where()}: cannot read `{expr.snippet()}` as a literal")
- return self.resolve(self.function_body(call.group(1), expr), path, hops + 1)
-
- named = NAME.fullmatch(code)
- if named:
- return self.resolve(self.binding(named.group(1), expr), path, hops + 1)
-
- raise Unreadable(f"{expr.where()}: cannot read `{expr.snippet()}` as a literal")
-
- def check_tail(self, tail):
- rest = tail
- while rest.code:
- modifier = MODIFIER.match(rest.code)
- if not modifier or modifier.group(1) not in KEEPS_CAPABILITIES:
- raise Unreadable(f"{rest.where()}: `{rest.snippet()}` may change a capability this check compares")
- close = matching(rest.source.code, rest.start + modifier.end() - 1)
- rest = Expr(rest.source, close + 1, rest.end)
-
- def entry_for_parameter(self, name, expr):
- # KingbaseES's entry is PostgreSQL's, passed in as `postgreSQL: PluginMetadataSnapshot`.
- declared = re.compile(r"\b" + re.escape(name) + r"\s*:\s*PluginMetadataSnapshot\b")
- if not any(declared.search(source.code) for source in self.sources):
- raise Unreadable(f"{expr.where()}: `{name}` is not a PluginMetadataSnapshot parameter")
- named = [type_id for type_id in self.entries if normalized(type_id) == normalized(name)]
- if len(named) != 1 or len(self.entries[named[0]]) != 1:
- raise Unreadable(f"{expr.where()}: `{name}` names no single curated entry")
- return self.entries[named[0]][0]
-
- def function_body(self, name, expr):
- pattern = re.compile(r"\bfunc\s+" + re.escape(name) + r"\s*\(")
- found = [(source, match) for source in self.sources for match in pattern.finditer(source.code)]
- if len(found) != 1:
- raise Unreadable(f"{expr.where()}: {len(found)} functions named {name}")
- source, match = found[0]
- parameters_end = matching(source.code, match.end() - 1)
- body_open = source.code.index("{", parameters_end)
- body = Expr(source, body_open + 1, matching(source.code, body_open))
- returned = re.match(r"return\b", body.code)
- return Expr(source, body.start + returned.end(), body.end) if returned else body
-
- def binding(self, name, expr):
- pattern = re.compile(r"\blet\s+" + re.escape(name) + r"\s*(?::[^=\n]+)?=")
- found = [(source, match) for source in self.sources for match in pattern.finditer(source.code)]
- if len(found) != 1:
- raise Unreadable(f"{expr.where()}: {len(found)} let bindings named {name}")
- source, match = found[0]
- return Expr(source, match.end(), expression_end(source.code, match.end()))
-
-
-def conforms_to_driver_plugin(clause):
- return re.search(r"\bDriverPlugin\b", clause) is not None
-
-
-class Declared:
- def __init__(self, name, folder, source, clause):
- self.name, self.folder, self.source = name, folder, source
- self.is_driver = conforms_to_driver_plugin(clause)
- self.statics = {}
-
-
-def statics_in(source, body_open, body_close):
- # Only the top level: a static of a nested type is not the plugin's.
- code = source.code
- found = []
- depth, counted = 0, body_open + 1
- for match in STATIC.finditer(code, body_open + 1, body_close):
- depth += code.count("{", counted, match.start()) - code.count("}", counted, match.start())
- counted = match.start()
- if depth != 0:
- continue
- if match.group(2) == "=":
- found.append((match.group(1), Expr(source, match.end(), expression_end(source.code, match.end()))))
- else:
- brace = match.end() - 1
- body = Expr(source, brace + 1, matching(source.code, brace))
- returned = re.match(r"return\b", body.code)
- found.append((match.group(1), Expr(source, body.start + returned.end(), body.end) if returned else body))
- return found
-
-
-class Plugins:
- def __init__(self, plugins_dir, root):
- self.plugins_dir = plugins_dir
- self.types = []
- self.defaults = {}
- extensions = []
- for path in sorted(plugins_dir.rglob("*.swift")):
- folder = path.relative_to(plugins_dir).parts[0]
- # A test bundle's doubles are not what the plugin ships, and may share a real type's name.
- if folder.endswith("Tests"):
- continue
- source = Source(path, root)
- for match in DECLARATION.finditer(source.code):
- body_open = match.end() - 1
- try:
- body_close = matching(source.code, body_open)
- members = statics_in(source, body_open, body_close)
- except Unreadable as error:
- raise Unreadable(f"{source.where(body_open)}: {error}") from error
- if match.group(1) == "extension":
- extensions.append((match.group(2), folder, match.group(3), members))
- else:
- declared = Declared(match.group(2), folder, source, match.group(3))
- self.add(declared, members)
- self.types.append(declared)
- for name, folder, clause, members in extensions:
- if name == "DriverPlugin" and folder == PLUGINKIT_DIR:
- for member, expr in members:
- self.defaults.setdefault(member, []).append(expr)
- for declared in self.types:
- if declared.name == name and declared.folder == folder:
- declared.is_driver = declared.is_driver or conforms_to_driver_plugin(clause)
- self.add(declared, members)
-
- @staticmethod
- def add(declared, members):
- for member, expr in members:
- declared.statics.setdefault(member, []).append(expr)
-
- def drivers(self):
- for folder in sorted(path.name for path in self.plugins_dir.iterdir() if (path / "Info.plist").is_file()):
- found = [declared for declared in self.types if declared.folder == folder and declared.is_driver]
- if len(found) > 1:
- yield folder, None, f"{len(found)} types conform to DriverPlugin"
- elif found:
- yield folder, found[0], None
- elif any(declared.folder == folder and "databaseTypeId" in declared.statics for declared in self.types):
- yield folder, None, "declares databaseTypeId on a type that does not visibly conform to DriverPlugin"
-
- def find(self, name, near, expr):
- found = [declared for declared in self.types if declared.name == name and declared.folder == near]
- if not found:
- found = [declared for declared in self.types if declared.name == name]
- if len(found) != 1:
- raise Unreadable(f"{expr.where()}: {len(found)} types named {name}")
- return found[0]
-
- def static(self, declared, member, hops=0):
- if hops > MAX_HOPS:
- raise Unreadable(f"{declared.name}.{member} follows more than {MAX_HOPS} references")
- exprs = declared.statics.get(member, [])
- if len(exprs) > 1:
- places = ", ".join(expr.where() for expr in exprs)
- raise Unreadable(f"{declared.name} declares {member} {len(exprs)} times ({places})")
- if exprs:
- return self.value(exprs[0], declared, hops)
- if not declared.is_driver:
- raise Unreadable(f"{declared.source.name}: {declared.name} declares no static {member}")
- defaults = self.defaults.get(member, [])
- if len(defaults) != 1:
- raise Unreadable(f"PluginKit has {len(defaults)} defaults for {member}")
- value, where = self.value(defaults[0], None, hops)
- return value, f"PluginKit default, {where}"
-
- def value(self, expr, declared, hops):
- value = literal(expr)
- if value is not None:
- return value, expr.where()
- member = MEMBER.fullmatch(expr.code)
- if member and (member.group(1) != "Self" or declared):
- near = declared.folder if declared else PLUGINKIT_DIR
- owner = declared if member.group(1) == "Self" else self.find(member.group(1), near, expr)
- return self.static(owner, member.group(2), hops + 1)
- raise Unreadable(f"{expr.where()}: cannot read `{expr.snippet()}` as a literal")
-
-
-def problems_in(apple):
- registry = sorted(apple.glob(REGISTRY_GLOB))
- if not registry:
- raise SystemExit(f"no {REGISTRY_GLOB} under {apple}")
- try:
- curated = Curated([Source(path, apple) for path in registry])
- plugins = Plugins(apple / "Plugins", apple)
- except Unreadable as error:
- return [str(error)], [], 0
-
- unreadable, mismatches, compared = [], [], 0
- for folder, driver, reason in plugins.drivers():
- if reason:
- unreadable.append(f"{folder}: {reason}")
- continue
- try:
- type_id, _ = plugins.static(driver, "databaseTypeId")
- if not isinstance(type_id, str):
- raise Unreadable(f"databaseTypeId is {describe(type_id)}, not a string")
- except Unreadable as error:
- unreadable.append(f"{folder}: {error}")
- continue
- entries = curated.entries.get(type_id, [])
- if len(entries) != 1:
- places = "".join(f" ({entry.where()})" for entry in entries)
- unreadable.append(f'{folder}: {len(entries)} curated entries for "{type_id}" in {REGISTRY_GLOB}{places}')
- continue
- compared += 1
- for capability, path in CAPABILITIES.items():
- try:
- curated_value, curated_where = curated.resolve(entries[0], path)
- plugin_value, plugin_where = plugins.static(driver, capability)
- except Unreadable as error:
- unreadable.append(f"{type_id} {capability}: {error}")
- continue
- if curated_value != plugin_value:
- mismatches.append(
- f"{type_id} {capability}: curated {describe(curated_value)} ({curated_where}), "
- f"plugin {describe(plugin_value)} ({plugin_where})"
- )
- return unreadable, mismatches, compared
-
-
-def main(argv=None):
- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
- parser.add_argument("--apple", type=Path, default=APPLE_DIR, help="the apple/ folder to check")
- args = parser.parse_args(argv)
-
- unreadable, mismatches, compared = problems_in(args.apple)
- errors = unreadable + mismatches
- if errors:
- for error in errors:
- print(f"::error::{error}", file=sys.stderr)
- hint = (
- " The plugin's value replaces the curated one once its code loads: declare the same value on both sides."
- if mismatches
- else ""
- )
- print(f"\n{len(errors)} problem(s).{hint}", file=sys.stderr)
- return 1
- if compared == 0:
- print(f"::error::no driver plugin under {args.apple / 'Plugins'}", file=sys.stderr)
- return 1
- print(f"{compared} driver plugins agree with their curated entries on {', '.join(CAPABILITIES)}")
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/apple/scripts/ci/check-source-ratchets.py b/apple/scripts/ci/check-source-ratchets.py
new file mode 100644
index 0000000000..a971fd9c71
--- /dev/null
+++ b/apple/scripts/ci/check-source-ratchets.py
@@ -0,0 +1,310 @@
+#!/usr/bin/env python3
+"""Fail when engine-name comparisons in the app, or singleton reads in its views, rise above their baseline.
+
+Comments are skipped, block comments nested, and a string literal is opaque apart from its interpolations, which are
+code.
+
+engine-name-comparisons, over apple/TablePro/. The names are the `static let = DatabaseType(rawValue: "")`
+lines of apple/TablePro/Models/Connection/DatabaseType.swift. Each of these counts once:
+ - `==` or `!=`, optional whitespace, an optional `DatabaseType`, then `.` ending at a word boundary;
+ - `.` or `DatabaseType.` as a whole item of a `case` pattern list, which ends at `:`, `where`, `in`,
+ or the `=` of `if case .a = x`;
+ - a string literal whose whole text is a raw value, right after or right before `==` or `!=`, or as a whole item
+ of a `case` list.
+ A name counts on any type: `case .mysql:` over SqlDialect counts too. `[.mysql].contains(t)` does not.
+
+view-singleton-reads, over apple/TablePro/Views/ and apple/TablePro/ViewModels/: each `DatabaseManager.shared`,
+`PluginManager.shared` and `AppSettingsManager.shared`.
+
+A count above its baseline in source-ratchets.json fails. A count below it passes with a notice to lower it.
+
+Usage:
+ check-source-ratchets.py [--apple ] [--list | --write]
+"""
+
+import argparse
+import functools
+import json
+import re
+import sys
+from pathlib import Path
+
+APPLE = Path(__file__).resolve().parents[2]
+SCRIPT = "apple/scripts/ci/check-source-ratchets.py"
+BASELINE = "scripts/ci/source-ratchets.json"
+DATABASE_TYPE = "TablePro/Models/Connection/DatabaseType.swift"
+
+ENGINES = "engine-name-comparisons"
+SINGLETONS = "view-singleton-reads"
+RATCHETS = (ENGINES, SINGLETONS)
+
+ADVICE = {
+ ENGINES: "move the new ones into plugin metadata or a PluginKit capability (apple/AGENTS.md, Scope)",
+ SINGLETONS: "pass the new ones in as injected services",
+}
+
+ENGINE_NAME = re.compile(r'^\s*static let (\w+) = DatabaseType\(rawValue: "([^"\\]*)"\)', re.MULTILINE)
+SINGLETON = re.compile(r"\b(?:DatabaseManager|PluginManager|AppSettingsManager)\.shared(?!\w)")
+
+OPAQUE = re.compile(r'//|/\*|#*"')
+STRING_OPENER = re.compile(r'(#*)("""|")')
+BLOCK_COMMENT = re.compile(r"/\*|\*/")
+INTERPOLATION = re.compile(r'[()]|//|/\*|#*"')
+NOT_NEWLINE = re.compile(r"[^\n]")
+
+CASE = re.compile(r"(?+-*/%&|^~")
+COMPARED_BEFORE = re.compile(r"(? 1 else "")
+ else:
+ i = comment_end(source, start)
+ code.append(NOT_NEWLINE.sub(" ", source[start:i]))
+
+
+def stripped(code, start, end):
+ while start < end and code[start].isspace():
+ start += 1
+ while end > start and code[end - 1].isspace():
+ end -= 1
+ return start, end
+
+
+def case_items(code, i):
+ """Yield (start, end) of each item in the pattern list that starts at `i`."""
+ depth = 0
+ item = i
+ while i < len(code):
+ char = code[i]
+ if char in "([":
+ depth += 1
+ elif char in ")]":
+ if depth == 0:
+ break
+ depth -= 1
+ elif char in "{};":
+ break
+ elif depth == 0:
+ if char == ",":
+ yield stripped(code, item, i)
+ item = i + 1
+ elif char == ":" or (char == "=" and code[i - 1] not in OPERATOR and code[i + 1:i + 2] != "="):
+ break
+ elif LIST_END_WORD.match(code, i) and not (code[i - 1].isalnum() or code[i - 1] == "_"):
+ break
+ i += 1
+ yield stripped(code, item, i)
+
+
+@functools.lru_cache(maxsize=None)
+def engine_patterns(names):
+ member = r"(?:DatabaseType)?\.(?:" + "|".join(names) + r")\b"
+ return re.compile(r"(? = DatabaseType(rawValue: ...)` lines in apple/{DATABASE_TYPE}.")
+ return 1
+ found = scan(apple, engines)
+
+ if args.list:
+ for ratchet, matches in found.items():
+ for path, line, text in matches:
+ print(f"{path}:{line}: {ratchet}: {text}")
+ return 0
+
+ counts = {ratchet: len(matches) for ratchet, matches in found.items()}
+ baseline_path = apple / BASELINE
+ if args.write:
+ baseline_path.write_text(json.dumps(counts, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ for ratchet in RATCHETS:
+ print(f"{ratchet}: {counts[ratchet]}")
+ return 0
+
+ if not baseline_path.is_file():
+ print(f"::error::apple/{BASELINE} is missing. Run {SCRIPT} --write.")
+ return 1
+ baseline = json.loads(baseline_path.read_text(encoding="utf-8"))
+ status = 0
+ for ratchet in RATCHETS:
+ count = counts[ratchet]
+ if ratchet not in baseline:
+ print(f"::error::apple/{BASELINE} has no baseline for {ratchet}. Run {SCRIPT} --write.")
+ status = 1
+ continue
+ limit = baseline[ratchet]
+ print(f"{ratchet}: {count} (baseline {limit})")
+ if count > limit:
+ print(
+ f"::error::{ratchet} rose from {limit} to {count}. Run {SCRIPT} --list and {ADVICE[ratchet]}; "
+ f"raise the baseline in apple/{BASELINE} only when that is not possible."
+ )
+ status = 1
+ elif count < limit:
+ print(f"::notice::{ratchet} fell from {limit} to {count}. Lower the baseline with {SCRIPT} --write.")
+ return status
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/apple/scripts/ci/source-ratchets.json b/apple/scripts/ci/source-ratchets.json
new file mode 100644
index 0000000000..3471c7c20d
--- /dev/null
+++ b/apple/scripts/ci/source-ratchets.json
@@ -0,0 +1,4 @@
+{
+ "engine-name-comparisons": 580,
+ "view-singleton-reads": 453
+}
diff --git a/apple/scripts/ci/test_check_capability_parity.py b/apple/scripts/ci/test_check_capability_parity.py
deleted file mode 100644
index 1c6563176d..0000000000
--- a/apple/scripts/ci/test_check_capability_parity.py
+++ /dev/null
@@ -1,413 +0,0 @@
-#!/usr/bin/env python3
-"""Fixture tests for check-capability-parity.py."""
-
-import contextlib
-import importlib.util
-import io
-import tempfile
-import unittest
-from pathlib import Path
-
-SPEC = importlib.util.spec_from_file_location(
- "check_capability_parity", Path(__file__).with_name("check-capability-parity.py")
-)
-check = importlib.util.module_from_spec(SPEC)
-SPEC.loader.exec_module(check)
-
-DRIVER_PLUGIN = """public protocol DriverPlugin: TableProPlugin {
- static var databaseTypeId: String { get }
- static var supportsHealthMonitor: Bool { get }
-}
-
-public extension DriverPlugin {
- static var additionalDatabaseTypeIds: [String] { [] }
- static var containerEntityName: String { "Database" }
- static var supportsHealthMonitor: Bool { true }
- static var supportsForeignKeyDisable: Bool { true }
- static var supportsSSH: Bool { true }
- static var supportsSSL: Bool { true }
-}
-"""
-
-PLIST = '\n\n\n\n'
-
-
-def capabilities(ssh="true", ssl="true", fk="true", extra=""):
- return f"""PluginMetadataSnapshot.CapabilityFlags(
- supportsSchemaSwitching: false,
- supportsImport: true,
- supportsExport: true,
- supportsSSH: {ssh},
- supportsSSL: {ssl},
- supportsCascadeDrop: false,
- supportsForeignKeyDisable: {fk},{extra}
- supportsReadOnlyMode: true,
- supportsQueryProgress: false,
- requiresReconnectForDatabaseSwitch: false,
- supportsDropDatabase: false
- )"""
-
-
-def schema(container='"Database"'):
- return f"""PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "public",
- defaultGroupName: "main",
- tableEntityName: "Tables",
- containerEntityName: {container},
- defaultPrimaryKeyColumn: nil,
- immutableColumns: [],
- systemDatabaseNames: [],
- systemSchemaNames: [],
- fileExtensions: [],
- databaseGroupingStrategy: .byDatabase,
- structureColumnFields: [.name, .type]
- )"""
-
-
-def snapshot(health="true", caps=None, info=None, tail=""):
- return f"""PluginMetadataSnapshot(
- displayName: "Example", iconName: "cylinder", defaultPort: 1_234,
- requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: true,
- isDownloadable: true, primaryUrlScheme: "example", parameterStyle: .questionMark,
- navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
- supportsHealthMonitor: {health}, urlSchemes: ["example"], postConnectActions: [],
- brandColorHex: "#123456", queryLanguageName: "SQL", editorLanguage: .sql,
- connectionMode: .network, supportsDatabaseSwitching: true,
- capabilities: {caps or capabilities()},
- schema: {info or schema()},
- editor: PluginMetadataSnapshot.EditorConfig(
- sqlDialect: nil, statementCompletions: [], columnTypesByCategory: ["Text": ["TEXT"]]
- ),
- connection: PluginMetadataSnapshot.ConnectionConfig(
- category: .relational, tagline: String(localized: "Example (\\(1 + 1)) \\"engine\\"")
- )
- ){tail}"""
-
-
-def registry(*entries, helpers=""):
- listed = ",\n".join(f' ("{type_id}", {body})' for type_id, body in entries)
- return f"""import Foundation
-
-extension PluginMetadataRegistry {{
- func examplePluginDefaults() -> [(typeId: String, snapshot: PluginMetadataSnapshot)] {{
- [
-{listed}
- ]
- }}
-{helpers}
-}}
-"""
-
-
-def plugin_class(name, type_id, *statics, extra=""):
- lines = "".join(f" {line}\n" for line in statics)
- return f"""import Foundation
-import TableProPluginKit
-
-final class {name}: NSObject, TableProPlugin, DriverPlugin {{
- static let pluginName = "{name}"
- static let databaseTypeId = "{type_id}"
-{lines}
- func createDriver(config: DriverConnectionConfig) -> any PluginDatabaseDriver {{
- ExampleDriver(config: config)
- }}
-}}
-{extra}"""
-
-
-class CheckCapabilityParityTests(unittest.TestCase):
- def setUp(self):
- self.temp = tempfile.TemporaryDirectory()
- self.apple = Path(self.temp.name)
- kit = self.apple / "Plugins" / "TableProPluginKit"
- kit.mkdir(parents=True)
- (kit / "DriverPlugin.swift").write_text(DRIVER_PLUGIN, encoding="utf-8")
- (self.apple / "TablePro" / "Core" / "Plugins").mkdir(parents=True)
-
- def tearDown(self):
- self.temp.cleanup()
-
- def curated(self, text, name="PluginMetadataRegistry+ExampleDefaults.swift"):
- (self.apple / "TablePro" / "Core" / "Plugins" / name).write_text(text, encoding="utf-8")
-
- def plugin(self, folder, swift, name="ExamplePlugin.swift"):
- directory = self.apple / "Plugins" / folder
- directory.mkdir(parents=True, exist_ok=True)
- (directory / "Info.plist").write_text(PLIST, encoding="utf-8")
- (directory / name).write_text(swift, encoding="utf-8")
- return directory
-
- def problems(self):
- unreadable, mismatches, _ = check.problems_in(self.apple)
- return unreadable, mismatches
-
- def run_main(self):
- out, err = io.StringIO(), io.StringIO()
- with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
- code = check.main(["--apple", str(self.apple)])
- return code, out.getvalue(), err.getvalue()
-
- def test_a_plugin_that_keeps_the_defaults_the_entry_states_passes(self):
- self.curated(registry(("Example", snapshot())))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- code, out, err = self.run_main()
- self.assertEqual(code, 0, err)
- self.assertIn("1 driver plugins agree", out)
-
- def test_a_curated_health_monitor_opt_out_the_plugin_does_not_repeat_fails(self):
- # #2700: the plugin's default `true` replaced the curated opt-out and the app pinged the connection.
- self.curated(registry(("SQLite", snapshot(health="false"))))
- self.plugin("SQLiteDriverPlugin", plugin_class("SQLitePlugin", "SQLite"))
- unreadable, mismatches = self.problems()
- self.assertEqual(unreadable, [])
- self.assertEqual(len(mismatches), 1)
- self.assertIn("SQLite supportsHealthMonitor: curated false", mismatches[0])
- self.assertIn("plugin true (PluginKit default, Plugins/TableProPluginKit/DriverPlugin.swift:9)", mismatches[0])
-
- self.plugin("SQLiteDriverPlugin", plugin_class("SQLitePlugin", "SQLite", "static let supportsHealthMonitor = false"))
- self.assertEqual(self.problems(), ([], []))
-
- def test_a_plugin_opt_out_the_curated_entry_does_not_repeat_fails(self):
- self.curated(registry(("Example", snapshot())))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example", "static let supportsHealthMonitor = false"))
- _, mismatches = self.problems()
- self.assertEqual(len(mismatches), 1)
- self.assertIn("curated true", mismatches[0])
- self.assertIn("plugin false (Plugins/ExampleDriverPlugin/ExamplePlugin.swift:7)", mismatches[0])
-
- def test_a_duckdb_style_transport_flip_fails_until_both_sides_agree(self):
- self.curated(registry(("DuckDB", snapshot(caps=capabilities(ssh="false", ssl="false")))))
- self.plugin("DuckDBDriverPlugin", plugin_class("DuckDBPlugin", "DuckDB"))
- _, mismatches = self.problems()
- self.assertEqual(
- [line.split(":")[0] for line in mismatches], ["DuckDB supportsSSH", "DuckDB supportsSSL"]
- )
-
- self.curated(registry(("DuckDB", snapshot(caps=capabilities(ssh="true", ssl="false")))))
- self.plugin(
- "DuckDBDriverPlugin",
- plugin_class("DuckDBPlugin", "DuckDB", "static let supportsSSH = true", "static let supportsSSL: Bool = false"),
- )
- self.assertEqual(self.problems(), ([], []))
-
- def test_a_container_name_and_a_foreign_key_flag_the_plugin_does_not_restate_fail(self):
- self.curated(registry(("Beancount", snapshot(caps=capabilities(fk="false"), info=schema('"Ledger"')))))
- self.plugin("BeancountDriverPlugin", plugin_class("BeancountPlugin", "Beancount"))
- _, mismatches = self.problems()
- self.assertEqual(len(mismatches), 2)
- self.assertIn('Beancount containerEntityName: curated "Ledger"', mismatches[1])
- self.assertIn('plugin "Database"', mismatches[1])
-
- statics = ("static let supportsForeignKeyDisable = false", 'static var containerEntityName: String { "Ledger" }')
- self.plugin("BeancountDriverPlugin", plugin_class("BeancountPlugin", "Beancount", *statics))
- self.assertEqual(self.problems(), ([], []))
-
- def test_references_to_literals_are_followed_on_both_sides(self):
- helpers = """
- static let exampleSchemaInfo = PluginMetadataSnapshot.SchemaInfo(
- defaultSchemaName: "", defaultGroupName: "main", tableEntityName: "Tables", containerEntityName: "Schema",
- defaultPrimaryKeyColumn: nil, immutableColumns: [], systemDatabaseNames: [], systemSchemaNames: [],
- fileExtensions: [], databaseGroupingStrategy: .bySchema, structureColumnFields: [.name]
- )
-
- private func exampleCapabilities(lite: Bool) -> PluginMetadataSnapshot.CapabilityFlags {
- """ + capabilities(ssh="false", extra="\n exactRowCountIsFullScan: lite,") + """
- }
-"""
- self.curated(registry(
- ("Example", snapshot(caps="exampleCapabilities(lite: false)", info="Self.exampleSchemaInfo")),
- helpers=helpers,
- ))
- metadata = 'enum ExampleMetadata {\n static let containerEntityName = "Schema"\n}\n'
- self.plugin(
- "ExampleDriverPlugin",
- plugin_class(
- "ExamplePlugin", "Example",
- "static let containerEntityName = ExampleMetadata.containerEntityName",
- "static let supportsSSH = Self.remoteTransport",
- "static let remoteTransport = false",
- ),
- )
- (self.apple / "Plugins" / "ExampleDriverPlugin" / "ExampleMetadata.swift").write_text(metadata, encoding="utf-8")
- self.assertEqual(self.problems(), ([], []))
-
- def test_a_snapshot_parameter_named_after_a_type_reads_that_entry_and_test_doubles_do_not_count(self):
- fork = """PluginMetadataSnapshot(
- displayName: "Fork", iconName: "cylinder", defaultPort: 1,
- requiresAuthentication: true, supportsForeignKeys: true, supportsSchemaEditing: true,
- isDownloadable: true, primaryUrlScheme: "fork", parameterStyle: .dollar,
- navigationModel: .standard, explainVariants: [], pathFieldRole: .database,
- supportsHealthMonitor: example.supportsHealthMonitor, urlSchemes: ["fork"], postConnectActions: [],
- brandColorHex: "#000000", queryLanguageName: "SQL", editorLanguage: .sql,
- connectionMode: .network, supportsDatabaseSwitching: true,
- capabilities: example.capabilities, schema: example.schema, editor: example.editor,
- connection: example.connection
- ).withSystemNames(databases: [], schemas: ["sys"])"""
- helpers = f"""
- static func forkDefaults(example: PluginMetadataSnapshot) -> [(typeId: String, snapshot: PluginMetadataSnapshot)] {{
- [("Fork", {fork})]
- }}
-"""
- self.curated(registry(("Example", snapshot(caps=capabilities(fk="false"))), helpers=helpers))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example", "static let supportsForeignKeyDisable = false"))
- self.plugin(
- "ForkDriverPlugin",
- plugin_class("ForkPlugin", "Fork", "static let supportsForeignKeyDisable = ExamplePlugin.supportsForeignKeyDisable"),
- name="ForkPlugin.swift",
- )
- # A test bundle's double of the same name must not make the reference ambiguous.
- tests = self.apple / "Plugins" / "ExampleDriverTests"
- tests.mkdir()
- doubled = plugin_class("ExamplePlugin", "Example", "static let supportsForeignKeyDisable = true")
- (tests / "Doubles.swift").write_text(doubled, encoding="utf-8")
- self.assertEqual(self.problems(), ([], []))
-
- self.plugin("ForkDriverPlugin", plugin_class("ForkPlugin", "Fork"), name="ForkPlugin.swift")
- _, mismatches = self.problems()
- self.assertEqual([line.split(":")[0] for line in mismatches], ["Fork supportsForeignKeyDisable"])
-
- def test_a_reference_to_an_undeclared_static_falls_back_to_the_default_only_on_a_driver(self):
- self.curated(registry(("Example", snapshot()), ("Fork", snapshot())))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- self.plugin(
- "ForkDriverPlugin",
- plugin_class(
- "ForkPlugin", "Fork",
- "static let supportsSSH = ExamplePlugin.supportsSSH",
- "static let supportsSSL = ForkMetadata.supportsSSL",
- extra="enum ForkMetadata {}\n",
- ),
- name="ForkPlugin.swift",
- )
- unreadable, mismatches = self.problems()
- self.assertEqual(mismatches, [])
- self.assertEqual(len(unreadable), 1)
- self.assertIn("Fork supportsSSL", unreadable[0])
- self.assertIn("ForkMetadata declares no static supportsSSL", unreadable[0])
-
- def test_an_expression_that_is_not_a_literal_is_a_failure_not_a_skip(self):
- self.curated(registry(("Example", snapshot(caps=capabilities(ssh="!isEmbedded")))))
- statics = ("static let supportsSSL = isRemote && true", 'static let containerEntityName = "\\(prefix)base"')
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example", *statics))
- unreadable, mismatches = self.problems()
- self.assertEqual(mismatches, [])
- self.assertEqual(
- [line.split(":")[0] for line in unreadable],
- ["Example supportsSSH", "Example supportsSSL", "Example containerEntityName"],
- )
- self.assertTrue(all("as a literal" in line for line in unreadable), unreadable)
-
- code, _, err = self.run_main()
- self.assertEqual(code, 1)
- self.assertIn("::error::Example supportsSSH", err)
- self.assertNotIn("declare the same value", err)
-
- def test_an_argument_the_entry_does_not_pass_is_a_failure(self):
- caps = capabilities().replace(" supportsSSL: true,\n", "")
- self.curated(registry(("Example", snapshot(caps=caps))))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- unreadable, _ = self.problems()
- self.assertEqual(len(unreadable), 1)
- self.assertIn("CapabilityFlags(...) passes no supportsSSL", unreadable[0])
-
- def test_a_plugin_with_no_curated_entry_or_two_is_a_failure(self):
- self.curated(registry(("Other", snapshot())))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- unreadable, _ = self.problems()
- self.assertEqual(unreadable, ['ExampleDriverPlugin: 0 curated entries for "Example" in ' + check.REGISTRY_GLOB])
-
- self.curated(registry(("Example", snapshot()), ("Example", snapshot())))
- unreadable, _ = self.problems()
- self.assertEqual(len(unreadable), 1)
- self.assertIn('2 curated entries for "Example"', unreadable[0])
-
- def test_a_static_declared_twice_is_a_failure(self):
- self.curated(registry(("Example", snapshot())))
- self.plugin(
- "ExampleDriverPlugin",
- plugin_class("ExamplePlugin", "Example", "static let supportsSSH = true",
- extra="extension ExamplePlugin {\n static let supportsSSH = false\n}\n"),
- )
- unreadable, _ = self.problems()
- self.assertEqual(len(unreadable), 1)
- self.assertIn("ExamplePlugin declares supportsSSH 2 times", unreadable[0])
-
- def test_a_conformance_declared_in_an_extension_counts(self):
- self.curated(registry(("Example", snapshot(health="false"))))
- swift = plugin_class("ExamplePlugin", "Example").replace(", DriverPlugin {", " {")
- swift += "\nextension ExamplePlugin: DriverPlugin {\n static let supportsHealthMonitor = false\n}\n"
- self.plugin("ExampleDriverPlugin", swift)
- code, out, err = self.run_main()
- self.assertEqual(code, 0, err)
- self.assertIn("1 driver plugins agree", out)
-
- def test_a_static_in_an_extension_counts(self):
- self.curated(registry(("Example", snapshot(health="false"))))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- (self.apple / "Plugins" / "ExampleDriverPlugin" / "ExamplePlugin+Health.swift").write_text(
- "extension ExamplePlugin {\n static var supportsHealthMonitor: Bool {\n return false\n }\n}\n",
- encoding="utf-8",
- )
- self.assertEqual(self.problems(), ([], []))
-
- def test_comments_strings_and_nested_types_do_not_count(self):
- self.curated(registry(("Example", snapshot(
- caps=capabilities(ssh="false /* supportsSSL: false, */"),
- info=schema('"Data\\"base\\" (main)"'),
- ))))
- swift = plugin_class(
- "ExamplePlugin", "Example",
- "// static let supportsSSL = false",
- 'static let note = "static let supportsHealthMonitor = false"',
- 'static let raw = #"static let supportsForeignKeyDisable = "no""#',
- "static let supportsSSH = false // true until Remote mode dialed a server",
- 'static let containerEntityName = "Data\\"base\\" (main)"',
- "enum Inner {\n static let supportsSSH = true\n }",
- )
- self.plugin("ExampleDriverPlugin", swift)
- self.assertEqual(self.problems(), ([], []))
-
- def test_a_modifier_that_may_change_a_compared_capability_is_a_failure(self):
- safe = snapshot(tail='.withSystemNames(databases: ["sys"], schemas: [])\n .withIconName("icon")')
- self.curated(registry(("Example", safe)))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- self.assertEqual(self.problems(), ([], []))
-
- self.curated(registry(("Example", snapshot(tail=".withSwitchRouting(from: other)"))))
- unreadable, _ = self.problems()
- self.assertEqual(len(unreadable), 5)
- self.assertIn("withSwitchRouting(from: other)` may change a capability", unreadable[0])
-
- def test_a_variant_keeps_its_curated_entry_and_is_not_compared(self):
- self.curated(registry(("Example", snapshot()), ("ExampleLite", snapshot(health="false"))))
- self.plugin(
- "ExampleDriverPlugin",
- plugin_class("ExamplePlugin", "Example", 'static let additionalDatabaseTypeIds = ["ExampleLite"]'),
- )
- self.assertEqual(self.problems(), ([], []))
-
- def test_a_call_that_is_not_an_entry_is_not_read_as_one(self):
- helpers = """
- static let templates = [requestTemplate("Example", #"{"TableName": ""}"#)]
-"""
- self.curated(registry(("Example", snapshot()), helpers=helpers))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- self.assertEqual(self.problems(), ([], []))
-
- def test_folders_without_a_driver_plugin_are_not_compared(self):
- self.curated(registry(("Example", snapshot())))
- self.plugin("ExampleDriverPlugin", plugin_class("ExamplePlugin", "Example"))
- self.plugin("CSVExportPlugin", 'final class CSVExportPlugin: ExportFormatPlugin {\n static let formatId = "csv"\n}\n')
- code, out, _ = self.run_main()
- self.assertEqual(code, 0)
- self.assertIn("1 driver plugins agree", out)
-
- def test_an_empty_plugins_folder_fails(self):
- self.curated(registry(("Example", snapshot())))
- code, _, err = self.run_main()
- self.assertEqual(code, 1)
- self.assertIn("no driver plugin", err)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/apple/scripts/ci/test_check_source_ratchets.py b/apple/scripts/ci/test_check_source_ratchets.py
new file mode 100644
index 0000000000..f49c155a00
--- /dev/null
+++ b/apple/scripts/ci/test_check_source_ratchets.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+"""Fixture tests for check-source-ratchets.py."""
+
+import contextlib
+import importlib.util
+import io
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+SPEC = importlib.util.spec_from_file_location(
+ "check_source_ratchets", Path(__file__).with_name("check-source-ratchets.py")
+)
+check = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(check)
+
+DATABASE_TYPE = '''struct DatabaseType {
+ let rawValue: String
+}
+
+extension DatabaseType {
+ static let mysql = DatabaseType(rawValue: "MySQL")
+ static let mssql = DatabaseType(rawValue: "SQL Server")
+ static let kafka = DatabaseType(rawValue: "Kafka")
+}
+'''
+
+COMPARISONS = '''if type == .mysql {}
+if type != DatabaseType.mssql {}
+let isKafka = type ==
+ .kafka
+if type == .mysqlFork {}
+if type === .mysql {}
+'''
+
+CASE_LISTS = '''switch type {
+case .mysql,
+ .mssql:
+ break
+case .kafka where flag:
+ break
+case DatabaseType.mysql:
+ break
+case .other, .some(.mysql):
+ break
+default:
+ break
+}
+if case .kafka = type {}
+let known = [.mysql].contains(type)
+'''
+
+LITERALS = '''if name == "MySQL" {}
+if "SQL Server" != name {}
+switch name {
+case "Kafka",
+ "Other":
+ break
+default:
+ break
+}
+connect("MySQL")
+if name == "MySQL \\(suffix)" {}
+'''
+
+HIDDEN = '''// if type == .mysql {}
+/* outer /* inner */ type == .mysql */
+let a = "type == .mysql"
+let b = "\\(f("x)")) == .mysql"
+let c = #"raw "== .mysql" case .kafka:"#
+let d = """
+ case .mysql:
+ """
+let e = #""""#
+if type == .kafka {}
+'''
+
+SINGLETONS = '''let a = DatabaseManager.shared
+let b = PluginManager.shared.plugins
+let c = AppSettingsManager.shared
+let d = DatabaseManager.sharedInstance
+let e = MyDatabaseManager.shared
+// DatabaseManager.shared
+let f = "PluginManager.shared"
+'''
+
+
+class CheckSourceRatchetsTests(unittest.TestCase):
+ def setUp(self):
+ folder = tempfile.TemporaryDirectory()
+ self.addCleanup(folder.cleanup)
+ self.apple = Path(folder.name) / "apple"
+ self.write("TablePro/Models/Connection/DatabaseType.swift", DATABASE_TYPE)
+ (self.apple / "scripts/ci").mkdir(parents=True)
+
+ def write(self, relative, text):
+ path = self.apple / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+ def run_check(self, *args):
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ status = check.main(["--apple", str(self.apple), *args])
+ return status, output.getvalue()
+
+ def listed(self, ratchet):
+ status, output = self.run_check("--list")
+ self.assertEqual(status, 0)
+ return [line.split(f": {ratchet}: ")[1] for line in output.splitlines() if f": {ratchet}: " in line]
+
+ def engines(self, source):
+ self.write("TablePro/Core/Example.swift", source)
+ return self.listed("engine-name-comparisons")
+
+ def baseline(self, engines, singletons):
+ self.write(
+ "scripts/ci/source-ratchets.json",
+ json.dumps({"engine-name-comparisons": engines, "view-singleton-reads": singletons}),
+ )
+
+ def test_comparisons_count(self):
+ self.assertEqual(self.engines(COMPARISONS), ["== .mysql", "!= DatabaseType.mssql", "== .kafka"])
+
+ def test_case_list_items_count(self):
+ self.assertEqual(
+ self.engines(CASE_LISTS),
+ ["case .mysql", "case .mssql", "case .kafka", "case DatabaseType.mysql", "case .kafka"],
+ )
+
+ def test_raw_value_literals_count_beside_a_comparison_or_in_a_case_list(self):
+ self.assertEqual(self.engines(LITERALS), ['== "MySQL"', '"SQL Server" !=', 'case "Kafka"'])
+
+ def test_comments_and_strings_are_skipped(self):
+ self.assertEqual(self.engines(HIDDEN), ["== .kafka"])
+
+ def test_an_interpolation_is_code(self):
+ source = 'let a = "\\(type == .mysql ? "x" : "y")"\nlet b = Text("Open \\(PluginManager.shared.name)")\n'
+ self.assertEqual(self.engines(source), ["== .mysql"])
+ self.write("TablePro/Views/Example.swift", source)
+ self.assertEqual(self.listed("view-singleton-reads"), ["PluginManager.shared"])
+
+ def test_list_names_the_file_and_line(self):
+ self.write("TablePro/Core/Example.swift", "\nif type == .mysql {}\n")
+ _, output = self.run_check("--list")
+ self.assertEqual(output, "apple/TablePro/Core/Example.swift:2: engine-name-comparisons: == .mysql\n")
+
+ def test_singletons_count_only_in_views_and_view_models(self):
+ for folder in ("Views/Main", "ViewModels", "Core"):
+ self.write(f"TablePro/{folder}/Example.swift", SINGLETONS)
+ found = self.listed("view-singleton-reads")
+ self.assertEqual(len(found), 6)
+ self.assertEqual(found[:3], ["DatabaseManager.shared", "PluginManager.shared", "AppSettingsManager.shared"])
+
+ def test_a_rise_fails(self):
+ self.write("TablePro/Core/Example.swift", "if type == .mysql {}\n")
+ self.baseline(0, 0)
+ status, output = self.run_check()
+ self.assertEqual(status, 1)
+ self.assertIn("engine-name-comparisons: 1 (baseline 0)", output)
+ self.assertIn("::error::engine-name-comparisons rose from 0 to 1.", output)
+
+ def test_an_equal_count_passes(self):
+ self.write("TablePro/Views/Example.swift", "if type == .mysql { DatabaseManager.shared }\n")
+ self.baseline(1, 1)
+ status, output = self.run_check()
+ self.assertEqual(status, 0)
+ self.assertNotIn("::", output)
+
+ def test_a_fall_passes_with_a_notice(self):
+ self.baseline(2, 0)
+ status, output = self.run_check()
+ self.assertEqual(status, 0)
+ self.assertIn("::notice::engine-name-comparisons fell from 2 to 0.", output)
+
+ def test_a_missing_ratchet_fails(self):
+ self.write("scripts/ci/source-ratchets.json", json.dumps({"engine-name-comparisons": 0}))
+ status, output = self.run_check()
+ self.assertEqual(status, 1)
+ self.assertIn("::error::", output)
+ self.assertIn("view-singleton-reads", output)
+
+ def test_no_engine_names_fails(self):
+ self.write("TablePro/Models/Connection/DatabaseType.swift", "struct DatabaseType {}\n")
+ self.baseline(0, 0)
+ status, output = self.run_check()
+ self.assertEqual(status, 1)
+ self.assertIn("::error::", output)
+
+ def test_write_records_the_counts(self):
+ self.write("TablePro/Views/Example.swift", "if type == .mysql { DatabaseManager.shared }\n")
+ status, _ = self.run_check("--write")
+ self.assertEqual(status, 0)
+ self.assertEqual(
+ (self.apple / "scripts/ci/source-ratchets.json").read_text(encoding="utf-8"),
+ '{\n "engine-name-comparisons": 1,\n "view-singleton-reads": 1\n}\n',
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/core/docs/decisions/0010-macos-on-the-core.md b/core/docs/decisions/0010-macos-on-the-core.md
index 718a924f29..875a968d6c 100644
--- a/core/docs/decisions/0010-macos-on-the-core.md
+++ b/core/docs/decisions/0010-macos-on-the-core.md
@@ -1,6 +1,6 @@
# 0010: The macOS app moves to the core in slices, starting with the connection library
-- **Status**: Accepted
+- **Status**: Accepted; later slices for importers, the MCP server and SSH amended by [0043](0043-macos-later-slices-importers-mcp-ssh.md)
- **Date**: 2026-11-04
## Context
diff --git a/core/docs/decisions/0043-macos-later-slices-importers-mcp-ssh.md b/core/docs/decisions/0043-macos-later-slices-importers-mcp-ssh.md
new file mode 100644
index 0000000000..ece6e7b24b
--- /dev/null
+++ b/core/docs/decisions/0043-macos-later-slices-importers-mcp-ssh.md
@@ -0,0 +1,41 @@
+# 0043: Importers, the MCP server and SSH move with the macOS app's later slices
+
+- **Status**: Accepted; amends 0010
+- **Date**: 2026-11-21
+
+## Context
+
+[0010](0010-macos-on-the-core.md) moves the macOS app to the core in five slices: the library, the connections, history and saved queries, the script reader, then engines. Three pieces exist in Swift and in the core, and none of the five covers them:
+
+- **Importers from other apps.** The Mac's own under `apple/TablePro/Core/Services/Export/ForeignApp/`, with their review in `TableProImport`; the core's `tablepro-foreign-import` ([0008](0008-importers-from-other-apps.md)), which the FFI exposes ([0033](0033-foreign-import-and-result-editing-through-the-ffi.md)) and which reads DBX's key ([0039](0039-dbx-passwords-from-its-key.md)). The core already fixes defects the Swift copy keeps (0008, Consequences).
+- **The MCP server.** The Mac's `Core/MCP` and `TableProMCP`; the core's `tablepro-mcp` behind `Core::mcp_server` ([0036](0036-mcp-and-the-command-line-through-the-ffi.md)).
+- **SSH.** The Mac's libssh2 stack in `Core/SSH`, a second one in the iOS app, and the core's `tablepro-ssh` ([0009](0009-in-process-ssh-on-windows.md)). Both Apple apps keep the host keys a user trusted in a `known_hosts` file of their own, one `[host]:port type base64` line each, through one `HostKeyStore` in `TableProSSHTransport`.
+
+## Decision
+
+Each moves in a slice of its own, after the slice that holds what it works on:
+
+6. **Importers, after slices 2 and 3.** `apply()` writes connections into the core's library and saved queries into the history's store (0033), so the Mac takes the review once both live there. It reads through `Core::foreign_sources`, `read_foreign` and `ForeignImportReview`, with a host whose `keychain()` reads another app's keychain items after the user allows it, DBX's key among them (0039).
+7. **The MCP server, after slice 5.** `Core::mcp_server` reaches only sessions that `connect_saved` opened (0036), so its tools see a Mac connection once that engine runs in the core, and the slice waits for the last engine: one port cannot serve two servers. The Mac passes an `McpAppHost` that opens a connection as Connect does and asks about a write in the connection's window, and keeps the token in the Keychain through `HostSecrets`. Its stdio bridge and client setup stay as [0023](0023-mcp-client-setup-from-one-catalog.md) has them.
+8. **SSH, with each engine in slice 5.** An engine that moves opens its tunnel through `tablepro-ssh`'s in-process transport, which the iOS app can use too since it cannot start a process (0009). The host passes the app's own `known_hosts` as the file the transport reads and adds trusted keys to, so a host trusted before the move stays trusted and the previous release still reads what the core wrote. The libssh2 stacks go with the last Swift engine.
+
+As each slice ships, its Swift copy and that copy's tests are deleted in the same change.
+
+## Rationale
+
+- Each piece follows its data: an import writes library rows and saved queries, the MCP tools act on sessions, and a tunnel belongs to the driver that dials through it.
+- Moving a piece before its data would bridge the core to a Swift store and back, one more seam to keep in step.
+- One known-hosts file per app keeps the trust a user already gave; `HostKeyStore` made it one Swift type, so the core has one format and two paths to read.
+
+## Consequences
+
+- Until a slice ships, a fix to its piece lands twice: in Rust for Linux and Windows, in Swift for the Mac.
+- The Mac has no DBX importer until slice 6 (0039, Consequences).
+- Every MCP change before slice 7 is Swift's alone, since the Mac's tools cannot reach a core session before slice 5.
+- `tablepro-ssh` gains a known-hosts path the host names, beside `~/.ssh/known_hosts`, when slice 8 starts.
+
+## Alternatives considered
+
+- **Importers first, writing through a bridge into the Swift library.** The review's duplicate handling and its write lock live in the core library (0008); a Swift library would need both again.
+- **The core's MCP server for the engines already moved, the Swift one for the rest.** Two servers on one port, or two ports for one app.
+- **Trusting `~/.ssh/known_hosts` alone after the move.** Every host a user trusted in the app would prompt again, and the iOS app has no such file.
diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md
index adaa240b39..88472d6321 100644
--- a/core/docs/decisions/README.md
+++ b/core/docs/decisions/README.md
@@ -17,7 +17,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the
| [0007](0007-sorting-a-result.md) | A sort names its column by name or position, else the core sorts the rows held | Accepted | `sort_reference` names a unique plain column, else its position on PostgreSQL, SQLite, SQL Server and DuckDB; otherwise, and for a statement that cannot run again, `value::order` sorts the rows held, which `ResultSet::sorted` gives the FFI as a view. |
| [0008](0008-importers-from-other-apps.md) | Importers from other apps live in the core | Accepted; the Windows host and the FFI surface amended by 0033, other apps' stores by 0039 | One crate reads each app's files on every platform into one record shape, takes keychains and directories from the app, says what it cannot carry, and reviews the result against the library with the macOS duplicate handling. |
| [0009](0009-in-process-ssh-on-windows.md) | SSH on Windows runs in process on russh | Accepted | russh behind `tablepro-ssh`'s `in-process` feature, on every target; Windows uses it, Linux keeps OpenSSH. Forwards are channels with no address, so MySQL and MongoDB relay them through a private listener that serves only this process. |
-| [0010](0010-macos-on-the-core.md) | The macOS app moves to the core in slices, starting with the connection library | Accepted | UniFFI Swift bindings in an XCFramework of the static library, without the engines, at the app's deployment target; UI, Keychain and the CloudKit transport stay Swift; the core maps the library's CloudKit records both ways with the existing fields and merges a pull field by field. |
+| [0010](0010-macos-on-the-core.md) | The macOS app moves to the core in slices, starting with the connection library | Accepted; later slices amended by 0043 | UniFFI Swift bindings in an XCFramework of the static library, without the engines, at the app's deployment target; UI, Keychain and the CloudKit transport stay Swift; the core maps the library's CloudKit records both ways with the existing fields and merges a pull field by field. |
| [0011](0011-sql-dump-and-import-in-process.md) | SQL dumps and SQL file imports run in process | Accepted; the import of COPY rows as INSERTs superseded by 0024 | Export Database writes one `.sql` file from each driver's catalog read in `pg_dump` and `mysqldump` order, and Import SQL File splits a file of any size as the engine's client does and runs it on an editor session; no app calls `pg_dump` or `mysqldump`. |
| [0012](0012-copies-before-a-format-upgrade.md) | A file in an older format is copied beside itself before its first write in the newer one | Accepted | `write_document_blocking` and the history's open copy a file an older build wrote to `.v-` before replacing it, the history through `VACUUM INTO`; three kept per file; no copy, no write. |
| [0013](0013-catalog-operations.md) | Truncating a table and creating or dropping a schema or database | Accepted | `DdlDialect` plans TRUNCATE and CREATE and DROP for schemas and databases per engine, MongoDB through its shell; a database change runs outside any transaction as `WriteKind::DatabaseChanges`; a login to a missing database fails as `DatabaseNotFound` and parks. |
@@ -48,3 +48,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the
| [0040](0040-duckdb-prepares-inside-a-transaction-it-runs-in.md) | DuckDB prepares a statement only inside a transaction it runs in | Accepted | DuckDB 2.0 prepares through a PREPARE that never writes, so a binding that takes a sequence value invalidates the database once that prepare commits on its own; the Swift apps run statements they do not stream through `duckdb_query`, and every prepare of user SQL, in the core too, runs inside the session's transaction or one the driver opens for the statement. |
| [0041](0041-a-result-window-can-keep-its-line-breaks.md) | A result window can keep its line breaks | Accepted | `tablepro_cursor_fetch_lines` packs the window `tablepro_cursor_fetch` does with each line break kept as one `\n`, for a grid that wraps its cells; both read one set of break forms (LF, CR LF, CR, VT, FF, NEL, U+2028, U+2029), which the one-line text now shows as spaces in full. |
| [0042](0042-a-mysql-result-can-be-wider-than-4096-columns.md) | A MySQL result can be wider than 4,096 columns | Accepted | sqlx-mysql 0.9.1 refuses a result set past 4,096 columns, the limit for a table, not a SELECT; sqlx-mysql and sqlx-core come from `TableProApp/sqlx`, the v0.9.1 tag with the refusal dropped and the claimed count's reservation capped at 4,096, until a release has the fix. |
+| [0043](0043-macos-later-slices-importers-mcp-ssh.md) | Importers, the MCP server and SSH move with the macOS app's later slices | Accepted | Importers after slices 2 and 3 through `ForeignImportReview`, the MCP server after the last engine of slice 5 with an `McpAppHost`, SSH with each engine on the in-process transport reading the app's own `known_hosts`; each Swift copy goes with its slice. |
diff --git a/scripts/ci/detect-changed-paths.sh b/scripts/ci/detect-changed-paths.sh
index 583347cce0..7974f17dd5 100755
--- a/scripts/ci/detect-changed-paths.sh
+++ b/scripts/ci/detect-changed-paths.sh
@@ -45,7 +45,10 @@ case "$SUITE" in
'apple/TablePro\.xcodeproj/project\.xcworkspace/xcshareddata/swiftpm/Package\.resolved$'
'apple/scripts/(generate-project|download-libs|create-openssl-dylibs|build-dameng|build-hana)\.sh$'
'apple/scripts/lib/' 'apple/scripts/ci/verify-plugin-loads\.sh$' 'apple/scripts/check-pluginkit-abi\.sh$'
- '\.github/actions/(setup-xcode(gen)?|prepare-build)/' '\.github/workflows/(ci|macos-tests)\.yml$') ;;
+ '\.github/actions/(setup-xcode(gen)?|prepare-build)/' '\.github/workflows/(ci|macos-tests)\.yml$'
+ # The Unit plan compares every built plugin with the app's curated entries.
+ 'apple/TablePro/Core/Plugins/PluginMetadataRegistry[^/]*\.swift$'
+ 'apple/TableProTests/Core/Plugins/PluginMetadataCuratedParityTests\.swift$') ;;
ios)
# The package's TableProPluginKit target is a symlink, so git reports its changes here.
PATTERNS=('apple/TableProMobile/' 'apple/Libs/' 'apple/Plugins/TableProPluginKit/'
diff --git a/scripts/ci/test_detect_changed_paths.py b/scripts/ci/test_detect_changed_paths.py
index 79580a0514..494e54aa4a 100644
--- a/scripts/ci/test_detect_changed_paths.py
+++ b/scripts/ci/test_detect_changed_paths.py
@@ -471,6 +471,8 @@ def test_plugins_runs_on_what_the_plugin_build_reads(self):
".github/actions/setup-xcodegen/action.yml",
".github/actions/prepare-build/action.yml",
".github/workflows/macos-tests.yml",
+ "apple/TablePro/Core/Plugins/PluginMetadataRegistry+Neo4jDefaults.swift",
+ "apple/TableProTests/Core/Plugins/PluginMetadataCuratedParityTests.swift",
]:
with self.subTest(path=path):
self.assertEqual(self.verdict_after("plugins", path), "true")