Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
9501f15
feat(pluginkit): add statement batches and schema-wide export reads
datlechin Nov 19, 2026
e7329c4
feat(postgres): run a statement batch as one pipeline inside a transa…
datlechin Nov 19, 2026
39eb4d6
perf(data-write): save grid edits in one batch when a failure rolls t…
datlechin Nov 19, 2026
7aacabf
perf(import): send SQL import and Data Sync statements in batches ins…
datlechin Nov 19, 2026
3415b82
perf(export): read the Data Dictionary's columns, keys and indexes on…
datlechin Nov 19, 2026
fe8de1f
fix(import): roll back an import or Data Sync stopped during its last…
datlechin Nov 19, 2026
863d70c
fix(postgres): fail the last statement of a pipeline whose Sync never…
datlechin Nov 19, 2026
12ab41e
fix(import): keep reads and setting calls out of import batches
datlechin Nov 19, 2026
d3a6e92
Revert "perf(data-write): save grid edits in one batch when a failure…
datlechin Nov 19, 2026
d3de381
revert(compare): keep Data Sync sending one statement at a time
datlechin Nov 19, 2026
ffb49fd
fix(import): send a declined batch one statement at a time and roll b…
datlechin Nov 19, 2026
4c69a8c
chore(l10n): add the batch statement strings to the catalog
datlechin Nov 19, 2026
6073eab
revert(import): keep SQL import sending one statement at a time
datlechin Nov 19, 2026
8a9f319
fix(postgres): send a text that may hold two statements alone, never …
datlechin Nov 19, 2026
1a0984b
fix(postgres): end a line comment at a carriage return when reading a…
datlechin Nov 19, 2026
57032bd
revert(pluginkit): leave statement batches out until a caller can kee…
datlechin Nov 19, 2026
914feae
fix(export): read a group read that reached the row limit table by ta…
datlechin Nov 19, 2026
6003a91
docs(changelog): note the faster PostgreSQL Data Dictionary export
datlechin Nov 19, 2026
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
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 = 45
TABLEPRO_PLUGINKIT_VERSION = 46
TABLEPRO_PLUGINKIT_MINIMUM_VERSION = 19
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,22 @@ final class DataDictionaryExportPlugin: ObservableObject, ExportFormatPlugin, Se
var failures = DataDictionaryReadFailures()
var objects: [DataDictionaryObject] = []
objects.reserveCapacity(tables.count)
var groups: [String: DataDictionaryGroupReads] = [:]
let groupSizes = Dictionary(grouping: tables, by: \.databaseName).mapValues(\.count)
for (index, table) in tables.enumerated() {
try progress.checkCancellation()
progress.setCurrentTable(table.qualifiedName, index: index + 1)
objects.append(try await DataDictionaryReader.read(table, from: dataSource, progress: progress, failures: &failures))
if groups[table.databaseName] == nil {
groups[table.databaseName] = try await DataDictionaryGroupReads.read(
databaseName: table.databaseName,
objectCount: groupSizes[table.databaseName] ?? 0,
from: dataSource,
progress: progress
)
}
objects.append(try await DataDictionaryReader.read(
table, from: dataSource, group: groups[table.databaseName], progress: progress, failures: &failures
))
}
try progress.checkCancellation()

Expand Down Expand Up @@ -127,12 +139,17 @@ enum DataDictionaryReader {
static func read(
_ table: PluginExportTable,
from dataSource: any PluginExportDataSource,
group: DataDictionaryGroupReads? = nil,
progress: PluginExportProgress,
failures: inout DataDictionaryReadFailures
) async throws -> DataDictionaryObject {
var object = DataDictionaryObject(name: table.name, container: table.containerName, kind: table.kind)
do {
object.columns = try await dataSource.fetchColumns(table: table.name, databaseName: table.databaseName)
if let columns = group?.columns?[table.name] {
object.columns = columns
} else {
object.columns = try await dataSource.fetchColumns(table: table.name, databaseName: table.databaseName)
}
} catch {
try rethrowIfCancelled(error, progress: progress)
object.columnsError = error.localizedDescription
Expand All @@ -141,7 +158,11 @@ enum DataDictionaryReader {

// Every kind, as the Structure tab reads them: SQL Server indexes a view.
do {
object.indexes = try await dataSource.fetchIndexes(table: table.name, databaseName: table.databaseName)
if let indexes = group?.indexes {
object.indexes = indexes[table.name] ?? []
} else {
object.indexes = try await dataSource.fetchIndexes(table: table.name, databaseName: table.databaseName)
}
} catch {
try rethrowIfCancelled(error, progress: progress)
object.indexesError = error.localizedDescription
Expand All @@ -150,7 +171,13 @@ enum DataDictionaryReader {

if table.kind == .table {
do {
object.foreignKeys = try await dataSource.fetchForeignKeys(table: table.name, databaseName: table.databaseName)
if let foreignKeys = group?.foreignKeys {
object.foreignKeys = foreignKeys[table.name] ?? []
} else {
object.foreignKeys = try await dataSource.fetchForeignKeys(
table: table.name, databaseName: table.databaseName
)
}
} catch {
try rethrowIfCancelled(error, progress: progress)
object.foreignKeysError = error.localizedDescription
Expand All @@ -168,8 +195,59 @@ enum DataDictionaryReader {
return object
}

private static func rethrowIfCancelled(_ error: Error, progress: PluginExportProgress) throws {
static func rethrowIfCancelled(_ error: Error, progress: PluginExportProgress) throws {
if error is CancellationError || error is PluginExportCancellationError { throw error }
try progress.checkCancellation()
}
}

// One read per group for what the source answers group-wide. A table such a read leaves out has none of that kind, and
// a read that fails is nil, so each table is read alone and its own failure named.
struct DataDictionaryGroupReads {
var columns: [String: [PluginColumnInfo]]?
var foreignKeys: [String: [PluginForeignKeyInfo]]?
var indexes: [String: [PluginIndexInfo]]?

// A read that reached the row limit may have stopped inside a table, so it is not taken as that table's answer.
static func read(
databaseName: String,
objectCount: Int,
from dataSource: any PluginExportDataSource,
progress: PluginExportProgress,
rowLimit: Int = PluginRowLimits.emergencyMax
) async throws -> DataDictionaryGroupReads {
var reads = DataDictionaryGroupReads()
let bulk = dataSource.bulkReads
guard objectCount > 1 else { return reads }
if bulk.contains(.columns) {
reads.columns = try await attempt(progress, rowLimit) {
try await dataSource.fetchAllColumns(databaseName: databaseName)
}
}
if bulk.contains(.indexes) {
reads.indexes = try await attempt(progress, rowLimit) {
try await dataSource.fetchAllIndexes(databaseName: databaseName)
}
}
if bulk.contains(.foreignKeys) {
reads.foreignKeys = try await attempt(progress, rowLimit) {
try await dataSource.fetchAllForeignKeys(databaseName: databaseName)
}
}
return reads
}

private static func attempt<Element>(
_ progress: PluginExportProgress,
_ rowLimit: Int,
_ read: () async throws -> [String: [Element]]
) async throws -> [String: [Element]]? {
do {
let answer = try await read()
return answer.values.reduce(0) { $0 + $1.count } < rowLimit ? answer : nil
} catch {
try DataDictionaryReader.rethrowIfCancelled(error, progress: progress)
return nil
}
}
}
161 changes: 161 additions & 0 deletions apple/Plugins/FormatPluginTests/DataDictionaryGroupReadTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
//
// DataDictionaryGroupReadTests.swift
// FormatPluginTests
//

import Foundation
import TableProPluginKit
import Testing

private struct Denied: LocalizedError {
var errorDescription: String? { "permission denied" }
}

private final class GroupReadingSource: PluginExportDataSource, @unchecked Sendable {
let databaseTypeId = "PostgreSQL"
let bulkReads: PluginExportBulkReads
var failsBulkColumns = false
private(set) var calls: [String] = []

private let columns: [String: [PluginColumnInfo]] = [
"orgs": [PluginColumnInfo(name: "id", dataType: "integer", isNullable: false, isPrimaryKey: true)],
"users": [
PluginColumnInfo(name: "id", dataType: "bigint", isNullable: false, isPrimaryKey: true),
PluginColumnInfo(name: "org_id", dataType: "integer", isNullable: true, comment: "Owner")
],
]
private let indexes: [String: [PluginIndexInfo]] = [
"users": [PluginIndexInfo(name: "users_org_idx", columns: ["org_id"], type: "btree")]
]
private let foreignKeys: [String: [PluginForeignKeyInfo]] = [
"users": [PluginForeignKeyInfo(
name: "users_org_fk", column: "org_id", referencedTable: "orgs", referencedColumn: "id",
referencedDatabase: nil, referencedSchema: "public", onDelete: "CASCADE"
)]
]

init(bulkReads: PluginExportBulkReads) {
self.bulkReads = bulkReads
}

func streamRows(table: String, databaseName: String) -> AsyncThrowingStream<PluginStreamElement, Error> {
AsyncThrowingStream { $0.finish() }
}

func fetchTableDDL(table: String, databaseName: String) async throws -> String { "" }

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

func quoteIdentifier(_ identifier: String) -> String { "\"\(identifier)\"" }
func escapeStringLiteral(_ value: String) -> String { value }
func fetchApproximateRowCount(table: String, databaseName: String) async throws -> Int? { nil }

func fetchColumns(table: String, databaseName: String) async throws -> [PluginColumnInfo] {
calls.append("columns \(table)")
return columns[table] ?? []
}

func fetchAllColumns(databaseName: String) async throws -> [String: [PluginColumnInfo]] {
calls.append("all columns")
if failsBulkColumns { throw Denied() }
return columns
}

func fetchIndexes(table: String, databaseName: String) async throws -> [PluginIndexInfo] {
calls.append("indexes \(table)")
return indexes[table] ?? []
}

func fetchAllIndexes(databaseName: String) async throws -> [String: [PluginIndexInfo]] {
calls.append("all indexes")
return indexes
}

func fetchForeignKeys(table: String, databaseName: String) async throws -> [PluginForeignKeyInfo] {
calls.append("foreign keys \(table)")
return foreignKeys[table] ?? []
}

func fetchAllForeignKeys(databaseName: String) async throws -> [String: [PluginForeignKeyInfo]] {
calls.append("all foreign keys")
return foreignKeys
}
}

struct DataDictionaryGroupReadTests {
private static let tables = ["orgs", "users"].map {
PluginExportTable(name: $0, databaseName: "public", tableType: "table", schema: "public", kind: .table)
}

private func export(_ tables: [PluginExportTable], from source: GroupReadingSource) async throws -> String {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let destination = directory.appendingPathComponent("shop.md")
let plugin = DataDictionaryExportPlugin()
let original = plugin.settings
defer { plugin.settings = original }
plugin.settings.fileType = .markdown
_ = try await plugin.export(
tables: tables,
dataSource: source,
destination: destination,
progress: PluginExportProgress(progress: Progress(totalUnitCount: 0))
)
let text = try String(contentsOf: destination, encoding: .utf8)
return text.components(separatedBy: "\n").filter { !$0.contains("generated") }.joined(separator: "\n")
}

@Test("A group whose source reads it whole is asked once per kind, and the file reads as it did table by table")
func groupReadMatchesTableReads() async throws {
let grouped = GroupReadingSource(bulkReads: [.columns, .foreignKeys, .indexes])
let alone = GroupReadingSource(bulkReads: [])

let groupedText = try await export(Self.tables, from: grouped)
let aloneText = try await export(Self.tables, from: alone)

#expect(grouped.calls == ["all columns", "all indexes", "all foreign keys"])
#expect(alone.calls == [
"columns orgs", "indexes orgs", "foreign keys orgs", "columns users", "indexes users", "foreign keys users",
])
#expect(groupedText == aloneText)
}

@Test("A group read that fails falls back to each table's own read")
func failedGroupReadFallsBack() async throws {
let source = GroupReadingSource(bulkReads: [.columns, .foreignKeys, .indexes])
source.failsBulkColumns = true

_ = try await export(Self.tables, from: source)

#expect(source.calls == ["all columns", "all indexes", "all foreign keys", "columns orgs", "columns users"])
}

@Test("A group read that reached the row limit is set aside, since it may have stopped inside a table")
func groupReadAtTheRowLimitFallsBack() async throws {
let source = GroupReadingSource(bulkReads: [.columns, .foreignKeys, .indexes])

let reads = try await DataDictionaryGroupReads.read(
databaseName: "public",
objectCount: 2,
from: source,
progress: PluginExportProgress(progress: Progress(totalUnitCount: 0)),
rowLimit: 3
)

#expect(reads.columns == nil)
#expect(reads.indexes?.isEmpty == false)
#expect(reads.foreignKeys?.isEmpty == false)
}

@Test("A group of one object is read on its own")
func singleObjectReadsAlone() async throws {
let source = GroupReadingSource(bulkReads: [.columns, .foreignKeys, .indexes])

_ = try await export([Self.tables[0]], from: source)

#expect(source.calls == ["columns orgs", "indexes orgs", "foreign keys orgs"])
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ extension PostgreSQLPluginDriver {

var providesBulkIndexFetch: Bool { true }

// Each is the per-table read with its table predicate dropped, decoded by the same row reader.
var exportBulkReads: PluginExportBulkReads { [.columns, .foreignKeys, .indexes] }

func fetchAllIndexes(schema: String?) async throws -> [String: [PluginIndexInfo]] {
let resolvedSchema = schema ?? core.currentSchema
let query = PostgreSQLIndexQueries.indexList(
Expand Down
5 changes: 5 additions & 0 deletions apple/Plugins/TableProPluginKit/PluginDatabaseDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ public protocol PluginDatabaseDriver: AnyObject, Sendable {
var tableDDLIncludesForeignKeys: Bool { get }
func fetchAllIndexes(schema: String?) async throws -> [String: [PluginIndexInfo]]
var providesBulkIndexFetch: Bool { get }
// Which of `fetchAllColumns`, `fetchAllForeignKeys` and `fetchAllIndexes` answer every table the way its own read
// does, so an export may read a schema once instead.
var exportBulkReads: PluginExportBulkReads { get }
func fetchAllTableMetadata(schema: String?) async throws -> [String: PluginTableMetadata]
var providesBulkTableMetadataFetch: Bool { get }
func fetchAllDatabaseMetadata() async throws -> [PluginDatabaseMetadata]
Expand Down Expand Up @@ -1161,6 +1164,8 @@ public extension PluginDatabaseDriver {
/// Answers whether `fetchAllIndexes` is a single query rather than the N+1 default below.
var providesBulkIndexFetch: Bool { false }

var exportBulkReads: PluginExportBulkReads { [] }

/// Default: fetches indexes per-table sequentially (N+1 round-trips).
/// SQL drivers should override with a single bulk query (e.g. INFORMATION_SCHEMA.STATISTICS).
func fetchAllIndexes(schema: String?) async throws -> [String: [PluginIndexInfo]] {
Expand Down
15 changes: 15 additions & 0 deletions apple/Plugins/TableProPluginKit/PluginExportBulkReads.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import Foundation

// The schema-wide reads that answer each table exactly as its own read does, so an export can take one in place of a
// read per table.
public struct PluginExportBulkReads: OptionSet, Sendable {
public let rawValue: UInt32

public init(rawValue: UInt32) {
self.rawValue = rawValue
}

public static let columns = PluginExportBulkReads(rawValue: 1 << 0)
public static let foreignKeys = PluginExportBulkReads(rawValue: 1 << 1)
public static let indexes = PluginExportBulkReads(rawValue: 1 << 2)
}
7 changes: 7 additions & 0 deletions apple/Plugins/TableProPluginKit/PluginExportDataSource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ public protocol PluginExportDataSource: AnyObject, Sendable {
func fetchAllForeignKeys(databaseName: String) async throws -> [String: [PluginForeignKeyInfo]]
var tableDDLIncludesForeignKeys: Bool { get }

// The group reads that answer each table as its own read does; any other is read table by table.
var bulkReads: PluginExportBulkReads { get }
func fetchAllIndexes(databaseName: String) async throws -> [String: [PluginIndexInfo]]

/// Mirrors `PluginDatabaseDriver.fetchIndexDDL` for the export side: the `CREATE INDEX`
/// statements this table needs that `fetchTableDDL` does not already declare.
func fetchIndexDDL(table: String, databaseName: String) async throws -> [String]
Expand Down Expand Up @@ -102,6 +106,9 @@ public extension PluginExportDataSource {
/// them a second time.
var tableDDLIncludesForeignKeys: Bool { false }

var bulkReads: PluginExportBulkReads { [] }
func fetchAllIndexes(databaseName: String) async throws -> [String: [PluginIndexInfo]] { [:] }

func fetchIndexDDL(table: String, databaseName: String) async throws -> [String] { [] }

func fetchCommentDDL(table: String, databaseName: String) async throws -> [String] { [] }
Expand Down
9 changes: 9 additions & 0 deletions apple/TablePro/Core/Plugins/ExportDataSourceAdapter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,15 @@ final class ExportDataSourceAdapter: PluginExportDataSource, @unchecked Sendable
pluginDriver?.tableDDLIncludesForeignKeys ?? false
}

var bulkReads: PluginExportBulkReads {
pluginDriver?.exportBulkReads ?? []
}

func fetchAllIndexes(databaseName: String) async throws -> [String: [PluginIndexInfo]] {
guard let pluginDriver else { return [:] }
return try await pluginDriver.fetchAllIndexes(schema: exportSchema(for: databaseName))
}

func fetchIndexDDL(table: String, databaseName: String) async throws -> [String] {
guard let pluginDriver else { return [] }
return try await pluginDriver.fetchIndexDDL(table: table, schema: exportSchema(for: databaseName))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@ final class MaskingExportDataSource: PluginExportDataSource, @unchecked Sendable
try await base.fetchIndexes(table: table, databaseName: databaseName)
}

var bulkReads: PluginExportBulkReads { base.bulkReads }

func fetchAllIndexes(databaseName: String) async throws -> [String: [PluginIndexInfo]] {
try await base.fetchAllIndexes(databaseName: databaseName)
}

func fetchObjectComment(_ object: PluginExportTable) async throws -> String? {
try await base.fetchObjectComment(object)
}
Expand Down
1 change: 1 addition & 0 deletions apple/changelog.d/4350.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The Data Dictionary export reads a PostgreSQL schema's columns, keys and indexes in one pass, not table by table.
Loading