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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion apple/.swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,13 @@ custom_rules:
excluded_match_kinds: [comment, doccomment]
message: "Schema, table and column names, SQL, payloads, hosts and paths are the user's. Log them at .private(mask: .hash), or .private next to a byte count."
severity: error
driver_adapter_downcast:
name: "Driver Adapter Downcast"
regex: '\b(as[?!]|is)\s+PluginDriverAdapter\b'
included: ['.*/TablePro/']
excluded_match_kinds: [comment, doccomment]
message: "Ask DatabaseDriver, or its plugin, for what the call needs: a cast hands every other driver the nil branch."
severity: error

# Storage and preferences
preference_key_namespace:
Expand Down Expand Up @@ -295,7 +302,8 @@ custom_rules:
regex: '\bSchemaStatementGenerator\(|\bCreateTableStatementComposer\.compose\(|\bgenerateCreateTableStatements\('
excluded:
- '.*/(Packages|Plugins)/'
- '.*/(DatabaseManager\+SchemaComposition|StructureTableRebuildHandler|CreateTableStatementComposer|SchemaSyncScriptBuilder)\.swift$'
# CreateTableEligibility only asks whether a probe table has a statement, and sends nothing.
- '.*/(DatabaseManager\+SchemaComposition|StructureTableRebuildHandler|CreateTableStatementComposer|SchemaSyncScriptBuilder|CreateTableEligibility)\.swift$'
message: "Compose DDL only on a driver leased for the statement's own scope (DatabaseManager+SchemaComposition)."
severity: error
result_buffer_handoff:
Expand Down
2 changes: 1 addition & 1 deletion apple/Configs/PluginKit.xcconfig
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// When to raise each, and how the build stamps them: .claude/rules/plugin-system.md, ABI.
TABLEPRO_PLUGINKIT_VERSION = 44
TABLEPRO_PLUGINKIT_VERSION = 45
TABLEPRO_PLUGINKIT_MINIMUM_VERSION = 19
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,13 @@ public enum MSSQLSchemaQueries {
return collation.flatMap(nonEmpty) ?? previous.flatMap(nonEmpty)
}

// sp_rename reads its first argument as a multipart name, so each part is bracketed before the whole becomes a
// literal: unbracketed, a schema literally named `[dbo]` names dbo. The new name is one part and stays bare.
public static func renameColumnStatement(schema: String, table: String, column: String, to newName: String) -> String {
let path = [schema, table, column].map { SQLQuoting.identifier($0, quote: .bracket) }.joined(separator: ".")
return "EXEC sp_rename \(MSSQLStringLiteral.quoted(path)), \(MSSQLStringLiteral.quoted(newName)), 'COLUMN'"
}

public static func alterColumnStatement(
qualifiedTable: String,
column: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -462,4 +462,16 @@ struct MSSQLSchemaQueriesTests {
#expect(MSSQLSchemaQueries.columns(schema: "dbo", table: "t").contains("= 'PRIMARY KEY'"))
#expect(MSSQLSchemaQueries.schemas.contains("'information_schema'"))
}

@Test("A rename brackets each part of the column it names, so a schema called [dbo] is not dbo")
func renameColumnBracketsEachPart() {
#expect(
MSSQLSchemaQueries.renameColumnStatement(schema: "sales", table: "orders", column: "id", to: "order_id")
== "EXEC sp_rename N'[sales].[orders].[id]', N'order_id', 'COLUMN'"
)
#expect(
MSSQLSchemaQueries.renameColumnStatement(schema: "[dbo]", table: "o'rders", column: "a.b", to: "c")
== "EXEC sp_rename N'[[dbo]]].[o''rders].[a.b]', N'c', 'COLUMN'"
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import Foundation
import TableProPluginKit
import Testing

private final class SchemaLessDDLDriver: PluginDatabaseDriver, @unchecked Sendable {
var supportsSchemas: Bool { false }
var supportsTransactions: Bool { false }
var currentSchema: String? { nil }
var serverVersion: String? { nil }

func connect() async throws {}
func disconnect() {}
func ping() async throws {}
func execute(query: String) async throws -> PluginQueryResult {
PluginQueryResult(columns: [], columnTypeNames: [], rows: [], rowsAffected: 0, executionTime: 0)
}

func fetchTables(schema: String?) async throws -> [PluginTableInfo] { [] }
func fetchColumns(table: String, schema: String?) async throws -> [PluginColumnInfo] { [] }
func fetchIndexes(table: String, schema: String?) async throws -> [PluginIndexInfo] { [] }
func fetchForeignKeys(table: String, schema: String?) async throws -> [PluginForeignKeyInfo] { [] }
func fetchTableDDL(table: String, schema: String?) async throws -> String { "" }
func fetchViewDefinition(view: String, schema: String?) async throws -> String { "" }
func fetchTableMetadata(table: String, schema: String?) async throws -> PluginTableMetadata {
PluginTableMetadata(tableName: table)
}

func fetchDatabases() async throws -> [String] { [] }
func fetchDatabaseMetadata(_ database: String) async throws -> PluginDatabaseMetadata {
PluginDatabaseMetadata(name: database)
}

func generateAddColumnSQL(table: String, column: PluginColumnDefinition) -> String? { "add \(table)" }
func generateModifyColumnSQL(
table: String,
oldColumn: PluginColumnDefinition,
newColumn: PluginColumnDefinition
) -> String? { "modify \(table)" }
func generateDropColumnSQL(table: String, columnName: String) -> String? { "drop \(table)" }
func generateAddIndexSQL(table: String, index: PluginIndexDefinition) -> String? { "index \(table)" }
func generateDropIndexSQL(table: String, indexName: String) -> String? { "drop index \(table)" }
func generateModifyIndexSQL(table: String, oldIndexName: String, newIndex: PluginIndexDefinition) -> String? {
"replace index \(table)"
}
func generateAddForeignKeySQL(table: String, fk: PluginForeignKeyDefinition) -> String? { "fk \(table)" }
func generateDropForeignKeySQL(table: String, constraintName: String) -> String? { "drop fk \(table)" }
func generateAddCheckConstraintSQL(table: String, constraint: PluginCheckConstraintDefinition) -> String? {
"check \(table)"
}
func generateDropCheckConstraintSQL(table: String, constraintName: String) -> String? { "drop check \(table)" }
func generateRenameCheckConstraintSQL(table: String, from oldName: String, to newName: String) -> String? {
"rename check \(table)"
}
func generateModifyPrimaryKeySQL(
table: String,
oldColumns: [String],
newColumns: [String],
constraintName: String?
) -> [String]? { ["pk \(table)"] }
func generateCreateTableSQL(definition: PluginCreateTableDefinition) -> String? { "create \(definition.tableName)" }
}

struct PluginSchemaDDLDefaultsTests {
private let driver: any PluginDatabaseDriver = SchemaLessDDLDriver()
private let column = PluginColumnDefinition(name: "c", dataType: "TEXT")

@Test("A driver that answers only the schema-less generators answers the schema-taking ones")
func schemaTakingDefaultsForward() {
let index = PluginIndexDefinition(name: "i", columns: ["c"])
let fk = PluginForeignKeyDefinition(name: "f", columns: ["c"], referencedTable: "u", referencedColumns: ["id"])
let check = PluginCheckConstraintDefinition(name: "k", expression: "c <> ''")

#expect(driver.generateAddColumnSQL(table: "t", schema: "s", column: column) == "add t")
#expect(driver.generateModifyColumnSQL(table: "t", schema: "s", oldColumn: column, newColumn: column) == "modify t")
#expect(driver.generateDropColumnSQL(table: "t", schema: "s", columnName: "c") == "drop t")
#expect(driver.generateAddIndexSQL(table: "t", schema: "s", index: index) == "index t")
#expect(driver.generateDropIndexSQL(table: "t", schema: "s", indexName: "i") == "drop index t")
#expect(driver.generateModifyIndexSQL(table: "t", schema: "s", oldIndexName: "i", newIndex: index) == "replace index t")
#expect(driver.generateAddForeignKeySQL(table: "t", schema: "s", fk: fk) == "fk t")
#expect(driver.generateDropForeignKeySQL(table: "t", schema: "s", constraintName: "f") == "drop fk t")
#expect(driver.generateAddCheckConstraintSQL(table: "t", schema: "s", constraint: check) == "check t")
#expect(driver.generateDropCheckConstraintSQL(table: "t", schema: "s", constraintName: "k") == "drop check t")
#expect(driver.generateRenameCheckConstraintSQL(table: "t", schema: "s", from: "k", to: "m") == "rename check t")
#expect(
driver.generateModifyPrimaryKeySQL(
table: "t", schema: "s", oldColumns: [], newColumns: ["c"], constraintName: nil
) == ["pk t"]
)
#expect(
driver.generateCreateTableStatements(
definition: PluginCreateTableDefinition(tableName: "t", columns: [column]), schema: "s"
) == ["create t"]
)
}
}
8 changes: 4 additions & 4 deletions apple/Plugins/BigQueryDriverPlugin/BigQueryPluginDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ internal final class BigQueryPluginDriver: PluginDatabaseDriver, @unchecked Send
"CREATE OR REPLACE VIEW \(quoteIdentifier(viewName)) AS\nSELECT * FROM table_name;"
}

func generateAddColumnSQL(table: String, column: PluginColumnDefinition) -> String? {
func generateAddColumnSQL(table: String, schema: String?, column: PluginColumnDefinition) -> String? {
guard let projectId else { return nil }
var sql = "ALTER TABLE \(qualifiedTable(table, schema: nil, projectId: projectId)) "
var sql = "ALTER TABLE \(qualifiedTable(table, schema: schema, projectId: projectId)) "
+ "ADD COLUMN \(quoteIdentifier(column.name)) \(column.dataType)"
if !column.isNullable {
sql += " NOT NULL"
Expand All @@ -168,9 +168,9 @@ internal final class BigQueryPluginDriver: PluginDatabaseDriver, @unchecked Send
return sql
}

func generateDropColumnSQL(table: String, columnName: String) -> String? {
func generateDropColumnSQL(table: String, schema: String?, columnName: String) -> String? {
guard let projectId else { return nil }
return "ALTER TABLE \(qualifiedTable(table, schema: nil, projectId: projectId)) "
return "ALTER TABLE \(qualifiedTable(table, schema: schema, projectId: projectId)) "
+ "DROP COLUMN \(quoteIdentifier(columnName))"
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,53 +1,44 @@
//
// ClickHousePartStatements.swift
// TablePro
// ClickHouseDriverPlugin
//

import Foundation
import TableProPluginKit

// ClickHouse takes the database from a request parameter any tab can move, so every statement names its own.
internal enum ClickHousePartStatements {
internal static func qualifiedName(
database: String,
table: String,
quote: (String) -> String
) -> String {
nonisolated enum ClickHousePartStatements {
static func qualifiedName(database: String, table: String, quote: (String) -> String) -> String {
guard !database.isEmpty else { return quote(table) }
return "\(quote(database)).\(quote(table))"
}

internal static func optimize(
database: String,
table: String,
quote: (String) -> String
) -> String {
static func optimize(database: String, table: String, quote: (String) -> String) -> String {
"OPTIMIZE TABLE \(qualifiedName(database: database, table: table, quote: quote)) FINAL"
}

internal static func dropPartition(
static func dropPartition(
database: String,
table: String,
partitionId: String,
quote: (String) -> String
) -> String? {
guard isValidPartitionId(partitionId) else { return nil }
let name = qualifiedName(database: database, table: table, quote: quote)
return "ALTER TABLE \(name) DROP PARTITION ID '\(partitionId)'"
return "ALTER TABLE \(qualifiedName(database: database, table: table, quote: quote)) DROP PARTITION ID '\(partitionId)'"
}

internal static func detachPartition(
static func detachPartition(
database: String,
table: String,
partitionId: String,
quote: (String) -> String
) -> String? {
guard isValidPartitionId(partitionId) else { return nil }
let name = qualifiedName(database: database, table: table, quote: quote)
return "ALTER TABLE \(name) DETACH PARTITION ID '\(partitionId)'"
return "ALTER TABLE \(qualifiedName(database: database, table: table, quote: quote)) DETACH PARTITION ID '\(partitionId)'"
}

// The server's own rule (MergeTreePartInfo::validatePartitionID); it also keeps quotes out of the literal.
internal static func isValidPartitionId(_ id: String) -> Bool {
static func isValidPartitionId(_ id: String) -> Bool {
!id.isEmpty && id.unicodeScalars.allSatisfy { scalar in
switch scalar {
case "0"..."9", "a"..."z", "A"..."Z", "-": true
Expand All @@ -56,24 +47,30 @@ internal enum ClickHousePartStatements {
}
}

// With no database of its own, ClickHouse resolves a request against its configured default.
private static func databasePredicate(_ database: String, escape: (String) -> String) -> String {
guard !database.isEmpty else { return "currentDatabase()" }
return "'\(escape(database))'"
}

// `partition` renders a tuple key as `(202401,'eu')` and no key as `tuple()`, so statements name `partition_id`.
internal static func parts(
database: String,
table: String,
escape: (String) -> String
) -> String {
// With no database of its own, ClickHouse resolves a request against its configured default.
static func parts(database: String, table: String) -> String {
"""
SELECT partition, partition_id, name, rows, bytes_on_disk,
toString(modification_time) AS mod_time, active
FROM system.parts
WHERE database = \(databasePredicate(database, escape: escape)) AND table = '\(escape(table))'
WHERE database = \(ClickHousePluginDriver.databaseExpression(database)) \
AND table = \(ClickHousePluginDriver.stringLiteral(table))
ORDER BY partition, name
"""
}

// Column order is `parts`.
static func part(from row: [PluginCellValue]) -> PluginStoragePart? {
guard let name = row[safe: 2]?.asText else { return nil }
return PluginStoragePart(
partition: row[safe: 0]?.asText ?? "",
partitionId: row[safe: 1]?.asText ?? "",
name: name,
rows: row[safe: 3]?.asText.flatMap { UInt64($0) } ?? 0,
bytesOnDisk: row[safe: 4]?.asText.flatMap { UInt64($0) } ?? 0,
modificationTime: row[safe: 5]?.asText ?? "",
isActive: row[safe: 6]?.asText == "1"
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//
// ClickHousePluginDriver+StorageParts.swift
// ClickHouseDriverPlugin
//

import Foundation
import TableProPluginKit

nonisolated extension ClickHousePluginDriver: PluginStorageParts {
func fetchStorageParts(table: String, database: String) async throws -> [PluginStoragePart] {
let result = try await execute(query: ClickHousePartStatements.parts(database: database, table: table))
return result.rows.compactMap(ClickHousePartStatements.part(from:))
}

func mergePartsStatement(table: String, database: String) -> String? {
ClickHousePartStatements.optimize(database: database, table: table, quote: quoteIdentifier)
}

func dropPartitionStatement(table: String, database: String, partitionId: String) -> String? {
ClickHousePartStatements.dropPartition(
database: database, table: table, partitionId: partitionId, quote: quoteIdentifier
)
}

func detachPartitionStatement(table: String, database: String, partitionId: String) -> String? {
ClickHousePartStatements.detachPartition(
database: database, table: table, partitionId: partitionId, quote: quoteIdentifier
)
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
//
// ClickHousePartStatementsTests.swift
// TableProTests
// ClickHouseDriverTests
//

import Foundation
@testable import TablePro
import TableProPluginKit
import Testing

struct ClickHousePartStatementsTests {
private let quote: (String) -> String = { "`\($0.replacingOccurrences(of: "`", with: "``"))`" }
private let escape: (String) -> String = { $0.replacingOccurrences(of: "'", with: "\\'") }

// An unqualified DROP PARTITION deleted data from whichever database the shared driver was last pinned to.
@Test("Every statement names the database it was given")
Expand Down Expand Up @@ -75,17 +74,15 @@ struct ClickHousePartStatementsTests {
// `currentDatabase()` answers with the request parameter, so the list showed another database's parts.
@Test("The parts read filters on the named database, never the connection's current one")
func partsReadNamesTheDatabase() {
let sql = ClickHousePartStatements.parts(
database: "analytics", table: "events", escape: escape
)
let sql = ClickHousePartStatements.parts(database: "analytics", table: "events")
#expect(sql.contains("WHERE database = 'analytics'"))
#expect(sql.contains("AND table = 'events'"))
#expect(!sql.contains("currentDatabase()"))
}

@Test("The parts read selects the partition ID beside the displayed partition value")
func partsReadSelectsThePartitionId() {
let sql = ClickHousePartStatements.parts(database: "analytics", table: "events", escape: escape)
let sql = ClickHousePartStatements.parts(database: "analytics", table: "events")
#expect(sql.contains("SELECT partition, partition_id, name, rows, bytes_on_disk,"))
}

Expand All @@ -100,7 +97,7 @@ struct ClickHousePartStatementsTests {
ClickHousePartStatements.optimize(database: "", table: "events", quote: quote)
== "OPTIMIZE TABLE `events` FINAL"
)
let sql = ClickHousePartStatements.parts(database: "", table: "events", escape: escape)
let sql = ClickHousePartStatements.parts(database: "", table: "events")
#expect(sql.contains("WHERE database = currentDatabase()"))
#expect(!sql.contains("database = ''"))
}
Expand All @@ -112,4 +109,33 @@ struct ClickHousePartStatementsTests {
)
#expect(sql == "ALTER TABLE `we``ird`.`ev``ents` DROP PARTITION ID '202401'")
}

@Test("A quote in a table name stays inside the literal")
func tableNameIsEscaped() {
let sql = ClickHousePartStatements.parts(database: "analytics", table: #"o'b\rien"#)
#expect(sql.contains(#"AND table = 'o''b\\rien'"#))
}

@Test("A parts row keeps the partition ID a statement names beside the value it shows")
func rowCarriesThePartitionId() throws {
let row: [PluginCellValue] = [
"(202401,'eu')",
"c1f8e6e2a7b04d4c9e1f0a2b3c4d5e6f",
"c1f8e6e2a7b04d4c9e1f0a2b3c4d5e6f_1_1_0",
"12",
"4096",
"2026-01-05 10:00:00",
"1",
]

let parsed = try #require(ClickHousePartStatements.part(from: row))

#expect(parsed.partition == "(202401,'eu')")
#expect(parsed.partitionId == "c1f8e6e2a7b04d4c9e1f0a2b3c4d5e6f")
#expect(parsed.name == "c1f8e6e2a7b04d4c9e1f0a2b3c4d5e6f_1_1_0")
#expect(parsed.rows == 12)
#expect(parsed.bytesOnDisk == 4096)
#expect(parsed.modificationTime == "2026-01-05 10:00:00")
#expect(parsed.isActive)
}
}
Loading
Loading