From 4103d001ed0ee8ca5e4e1cb616cc0e051be54e52 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 07:05:59 +0700 Subject: [PATCH 1/2] perf(export): stream gzip while writing a dump and while reading one back A gzip export wrote the whole dump uncompressed to a temp file and compressed it in a second pass after the last row, and could not split. Each part now deflates as it is written, on its own queue, and a split part is a gzip file of its own. A .sql.gz import inflated the whole file to disk and lexed it once more to count statements; the parser now reads the gzip file through an inflater and the count is gone. --- apple/Packages/TableProCore/Package.swift | 4 +- .../Sources/TableProGzip/GzipDeflater.swift | 9 + .../TableProSQLFile/SQLFileByteReader.swift | 91 +++++++++ .../TableProSQLFile/SQLFileParser.swift | 39 ++-- .../TableProGzipTests/GzipDeflaterTests.swift | 23 +++ .../SQLFileParserGzipTests.swift | 110 ++++++++++ .../ExportImportRoundTripTests.swift | 33 +++ .../SQLExportGzipWriterTests.swift | 83 ++++++++ .../SQLExportPlugin/SQLExportCompressor.swift | 61 ------ .../SQLExportPlugin/SQLExportFileWriter.swift | 63 ++++-- .../SQLExportPlugin/SQLExportPartOutput.swift | 193 ++++++++++++++++++ .../SQLExportPlugin/SQLExportPlugin.swift | 35 +--- .../Core/Plugins/SqlFileImportSource.swift | 81 +------- .../Core/Services/Export/ImportService.swift | 26 +-- .../Utilities/File/FileDecompressor.swift | 28 --- .../TablePro/Views/Import/ImportDialog.swift | 156 ++------------ .../SqlFileImportSourceCleanupTests.swift | 121 ----------- .../SqlFileImportSourceGzipTests.swift | 80 ++++++++ .../ImportFileFormatResolverTests.swift | 8 +- .../Import/ImportStatementCountTests.swift | 41 ---- 20 files changed, 725 insertions(+), 560 deletions(-) create mode 100644 apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileByteReader.swift create mode 100644 apple/Packages/TableProCore/Tests/TableProSQLFileTests/SQLFileParserGzipTests.swift create mode 100644 apple/Plugins/FormatPluginTests/SQLExportGzipWriterTests.swift delete mode 100644 apple/Plugins/SQLExportPlugin/SQLExportCompressor.swift create mode 100644 apple/Plugins/SQLExportPlugin/SQLExportPartOutput.swift delete mode 100644 apple/TablePro/Core/Utilities/File/FileDecompressor.swift delete mode 100644 apple/TableProTests/Core/Plugins/SqlFileImportSourceCleanupTests.swift create mode 100644 apple/TableProTests/Core/Plugins/SqlFileImportSourceGzipTests.swift delete mode 100644 apple/TableProTests/Views/Import/ImportStatementCountTests.swift diff --git a/apple/Packages/TableProCore/Package.swift b/apple/Packages/TableProCore/Package.swift index fb7764aa8e..e12b048fe3 100644 --- a/apple/Packages/TableProCore/Package.swift +++ b/apple/Packages/TableProCore/Package.swift @@ -273,7 +273,7 @@ let package = Package( // Reads a .sql file for both apps' imports, so never TableProPluginKit. .target( name: "TableProSQLFile", - dependencies: ["TableProSQLGrammar", "TableProTabularIO"], + dependencies: ["TableProSQLGrammar", "TableProTabularIO", "TableProGzip"], path: "Sources/TableProSQLFile", swiftSettings: pluginCoreSettings ), @@ -546,7 +546,7 @@ let package = Package( ), .testTarget( name: "TableProSQLFileTests", - dependencies: ["TableProSQLFile", "TableProSQLGrammar", "TableProTabularIO"], + dependencies: ["TableProSQLFile", "TableProSQLGrammar", "TableProTabularIO", "TableProGzip"], path: "Tests/TableProSQLFileTests", swiftSettings: pluginCoreSettings ), diff --git a/apple/Packages/TableProCore/Sources/TableProGzip/GzipDeflater.swift b/apple/Packages/TableProCore/Sources/TableProGzip/GzipDeflater.swift index cd644fa7db..5f26fe214f 100644 --- a/apple/Packages/TableProCore/Sources/TableProGzip/GzipDeflater.swift +++ b/apple/Packages/TableProCore/Sources/TableProGzip/GzipDeflater.swift @@ -67,6 +67,15 @@ public final class GzipDeflater { } } + // A sync flush writes out everything taken so far and keeps the window, so the bytes written are the + // stream's exact size up to here at the cost of a few bytes, not of the compression ratio. + public func flush(into sink: (UnsafeRawBufferPointer) throws -> Void) throws { + guard !finished else { throw GzipError.compressionFailed } + stream.pointee.next_in = nil + stream.pointee.avail_in = 0 + try drain(flush: Z_SYNC_FLUSH, into: sink) + } + public func finish(into sink: (UnsafeRawBufferPointer) throws -> Void) throws { guard !finished else { return } stream.pointee.next_in = nil diff --git a/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileByteReader.swift b/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileByteReader.swift new file mode 100644 index 0000000000..396a245eb6 --- /dev/null +++ b/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileByteReader.swift @@ -0,0 +1,91 @@ +import Foundation +import TableProGzip +import TableProWireIO + +/// The bytes of a dump as the parser reads them: the file itself, or the SQL inside a gzip file, +/// inflated as it is read so nothing is written to disk. A gzip file is told by its magic number, +/// which no text dump can start with. +public final class SQLFileByteReader { + private static let gzipMagic: [UInt8] = [0x1F, 0x8B] + + // Nothing is written, so the disk budget a copy needs does not apply, and the parser's span + // limit bounds memory. + private static let streamingBudget = DecompressionBudget(ratioLimit: .max, grace: .max) + + private let handle: FileHandle + private var inflater: GzipInflater? + private var pendingInput = Data() + private var reachedEnd = false + + /// The file's size on disk, and how much of it has been read: compressed bytes for a gzip file. + public private(set) var fileSize: Int64 = 0 + public private(set) var bytesRead: Int64 = 0 + + public var isCompressed: Bool { inflater != nil } + + public init(url: URL) throws { + handle = try FileHandle(forReadingFrom: url) + var info = stat() + fileSize = fstat(handle.fileDescriptor, &info) == 0 ? Int64(info.st_size) : 0 + let head = try autoreleasepool { try handle.read(upToCount: 2) } ?? Data() + try handle.seek(toOffset: 0) + if Array(head) == Self.gzipMagic { + inflater = try GzipInflater(budget: Self.streamingBudget) + } + } + + deinit { + try? handle.close() + } + + /// The next bytes of SQL, about `count` of them; empty once the file ends. + public func read(upToCount count: Int) throws -> Data { + guard let inflater else { + guard !reachedEnd else { return Data() } + let block = try autoreleasepool { try handle.read(upToCount: count) } ?? Data() + bytesRead += Int64(block.count) + if block.isEmpty { reachedEnd = true } + return block + } + var inflated = Data() + while inflated.count < count, !reachedEnd { + if pendingInput.isEmpty { + let block = try autoreleasepool { try handle.read(upToCount: count) } ?? Data() + bytesRead += Int64(block.count) + guard !block.isEmpty else { + reachedEnd = true + try inflater.finish() + break + } + pendingInput = block + } + // Fed a slice at a time, so one compressed block of zero-filled rows inflates no more than a slice's worth + // past the size asked for, however far it packs. + let slice = pendingInput.prefix(Self.inflateSlice) + pendingInput = pendingInput.dropFirst(slice.count) + try slice.withUnsafeBytes { raw in + try inflater.inflate(raw) { inflated.append($0.assumingMemoryBound(to: UInt8.self)) } + } + } + return inflated + } + + // Deflate packs at most about 1,032 to 1, so 4 KiB of input inflates to at most about 4 MiB. + private static let inflateSlice = 4 * 1_024 + + public func close() throws { + try handle.close() + } + + /// The first `limit` bytes of SQL in the file, for a preview, and whether they are all of it. + public static func leadingBytes(of url: URL, limit: Int) throws -> (data: Data, isWholeFile: Bool) { + let reader = try SQLFileByteReader(url: url) + var data = Data() + while data.count < limit { + let block = try reader.read(upToCount: 256 * 1_024) + guard !block.isEmpty else { return (data, true) } + data.append(block) + } + return (data.prefix(limit), false) + } +} diff --git a/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileParser.swift b/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileParser.swift index fc1ebc8d3f..4a9f9de312 100644 --- a/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileParser.swift +++ b/apple/Packages/TableProCore/Sources/TableProSQLFile/SQLFileParser.swift @@ -704,9 +704,7 @@ extension SQLFileParser { private let limits: ReadLimits private let onRead: (@Sendable (Int64, Int64) -> Void)? - private var fileHandle: FileHandle? - private var fileSize: Int64 = 0 - private var bytesRead: Int64 = 0 + private var reader: SQLFileByteReader? private var ctx: ParserContext private let nsBuffer = NSMutableString() // Text before it is lexed; it is deleted when the next chunk is read, not once per statement. @@ -882,12 +880,13 @@ extension SQLFileParser { } private func readChunk() throws { - let handle = try openFileIfNeeded() + let reader = try openFileIfNeeded() // A count, a GO scan and a driver's COPY read chunk after chunk with nothing draining the autorelease pool. - let rawData = try autoreleasepool { try handle.read(upToCount: limits.chunkSize) } ?? Data() - if !rawData.isEmpty, let onRead { - bytesRead += Int64(rawData.count) - onRead(bytesRead, fileSize) + let readBefore = reader.bytesRead + let rawData = try autoreleasepool { try reader.read(upToCount: limits.chunkSize) } + // A gzip file reports the compressed bytes read against its size on disk. + if reader.bytesRead != readBefore, let onRead { + onRead(reader.bytesRead, reader.fileSize) } if rawData.isEmpty && !decoder.hasPendingBytes { @@ -1030,25 +1029,21 @@ extension SQLFileParser { } } - private func openFileIfNeeded() throws -> FileHandle { - if let fileHandle { - return fileHandle + // A size of 0, taken from the open handle, leaves the import's bar on statements. + private func openFileIfNeeded() throws -> SQLFileByteReader { + if let reader { + return reader } - let handle = try FileHandle(forReadingFrom: url) - fileHandle = handle - // Taken from the open handle; a size of 0 leaves the import's bar on statements. - if onRead != nil { - var info = stat() - fileSize = fstat(handle.fileDescriptor, &info) == 0 ? Int64(info.st_size) : 0 - } - return handle + let opened = try SQLFileByteReader(url: url) + reader = opened + return opened } private func closeFile() { - guard let handle = fileHandle else { return } - fileHandle = nil + guard let opened = reader else { return } + reader = nil do { - try handle.close() + try opened.close() } catch { SQLFileParser.logger.warning( "Failed to close file handle for \(self.url.path): \(error.localizedDescription)") diff --git a/apple/Packages/TableProCore/Tests/TableProGzipTests/GzipDeflaterTests.swift b/apple/Packages/TableProCore/Tests/TableProGzipTests/GzipDeflaterTests.swift index 4c24b403f4..e853c5658a 100644 --- a/apple/Packages/TableProCore/Tests/TableProGzipTests/GzipDeflaterTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProGzipTests/GzipDeflaterTests.swift @@ -161,3 +161,26 @@ func rawDeflateRoundTrips(count: Int) throws { #expect(try rawInflate(packed, expectedCount: input.count) == input) } } + +@Test("A sync flush writes out every byte taken so far, and the stream still finishes whole") +func syncFlushWritesEverythingTaken() throws { + let first = DeflaterFixture.dumpText(lines: 20_000) + let second = DeflaterFixture.dumpText(lines: 500) + let deflater = try GzipDeflater() + var output = Data() + let sink: (UnsafeRawBufferPointer) throws -> Void = { output.append($0.assumingMemoryBound(to: UInt8.self)) } + try first.withUnsafeBytes { try deflater.deflate($0, into: sink) } + try deflater.flush(into: sink) + let flushed = output + + var inflatedPrefix = Data() + let inflater = try GzipInflater(budget: .init(limit: .max, ratioLimit: .max, grace: .max)) + try flushed.withUnsafeBytes { raw in + try inflater.inflate(raw) { inflatedPrefix.append($0.assumingMemoryBound(to: UInt8.self)) } + } + #expect(inflatedPrefix == first) + + try second.withUnsafeBytes { try deflater.deflate($0, into: sink) } + try deflater.finish(into: sink) + #expect(try GzipInflater.decompress(output, budget: .init(limit: .max, ratioLimit: .max, grace: .max)) == first + second) +} diff --git a/apple/Packages/TableProCore/Tests/TableProSQLFileTests/SQLFileParserGzipTests.swift b/apple/Packages/TableProCore/Tests/TableProSQLFileTests/SQLFileParserGzipTests.swift new file mode 100644 index 0000000000..bae306b4fa --- /dev/null +++ b/apple/Packages/TableProCore/Tests/TableProSQLFileTests/SQLFileParserGzipTests.swift @@ -0,0 +1,110 @@ +import Foundation +import os +import TableProGzip +@testable import TableProSQLFile +import TableProSQLGrammar +import Testing + +struct SQLFileParserGzipTests { + private static func write(_ data: Data, extension pathExtension: String) throws -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("SQLFileParserGzipTests-\(UUID().uuidString).\(pathExtension)") + try data.write(to: url) + return url + } + + private static func statements(of url: URL, parser: SQLFileParser = SQLFileParser()) async throws -> [String] { + var statements: [String] = [] + for try await (statement, _) in parser.parseFile(url: url, encoding: .utf8, grammar: TestGrammar.postgres) { + statements.append(statement) + } + return statements + } + + @Test("A gzip file parses to the statements of the SQL inside it, with no copy on disk") + func gzipFileParsesLikeItsSQL() async throws { + let sql = (1...5_000).map { "INSERT INTO t VALUES (\($0), 'row \($0);');\n" }.joined() + let plain = try Self.write(Data(sql.utf8), extension: "sql") + let packed = try Self.write(try GzipDeflater.compress(Data(sql.utf8)), extension: "sql.gz") + defer { + try? FileManager.default.removeItem(at: plain) + try? FileManager.default.removeItem(at: packed) + } + + let expected = try await Self.statements(of: plain) + #expect(expected.count == 5_000) + #expect(try await Self.statements(of: packed, parser: SQLFileParser(chunkSize: 512)) == expected) + #expect(try await SQLFileParser().countStatements(url: packed, encoding: .utf8, grammar: TestGrammar.postgres) == 5_000) + } + + @Test("A gzip file reports the compressed bytes read against its size on disk") + func gzipReportsCompressedBytes() async throws { + let sql = (1...2_000).map { "SELECT \($0);\n" }.joined() + let packedData = try GzipDeflater.compress(Data(sql.utf8)) + let packed = try Self.write(packedData, extension: "sql.gz") + defer { try? FileManager.default.removeItem(at: packed) } + let last = OSAllocatedUnfairLock<(read: Int64, size: Int64)?>(initialState: nil) + + let stream = SQLFileParser(chunkSize: 256).parseFile( + url: packed, encoding: .utf8, grammar: { TestGrammar.postgres }, + onRead: { read, size in last.withLock { $0 = (read, size) } } + ) + var count = 0 + for try await _ in stream { count += 1 } + + #expect(count == 2_000) + let report = try #require(last.withLock { $0 }) + #expect(report.size == Int64(packedData.count)) + #expect(report.read == Int64(packedData.count)) + } + + @Test("A gzip file cut short fails the parse instead of ending quietly") + func truncatedGzipFails() async throws { + let sql = (1...2_000).map { "SELECT \($0);\n" }.joined() + let packedData = try GzipDeflater.compress(Data(sql.utf8)) + let packed = try Self.write(packedData.prefix(packedData.count - 12), extension: "sql.gz") + defer { try? FileManager.default.removeItem(at: packed) } + + await #expect(throws: (any Error).self) { + _ = try await Self.statements(of: packed) + } + } + + @Test("The preview reads the first bytes of SQL inside a gzip file") + func previewReadsInflatedText() throws { + let sql = String(repeating: "SELECT 1;\n", count: 10_000) + let packed = try Self.write(try GzipDeflater.compress(Data(sql.utf8)), extension: "sql.gz") + defer { try? FileManager.default.removeItem(at: packed) } + + let head = try SQLFileByteReader.leadingBytes(of: packed, limit: 1_000) + #expect(head.data == Data(sql.utf8).prefix(1_000)) + #expect(!head.isWholeFile) + let whole = try SQLFileByteReader.leadingBytes(of: packed, limit: 1 << 20) + #expect(whole.data == Data(sql.utf8)) + #expect(whole.isWholeFile) + } +} + +struct SQLFileByteReaderBoundTests { + @Test("A read of a gzip file that packs far returns about the size asked for, not the block's whole expansion") + func readIsBoundedByOutput() throws { + let zeros = Data(count: 64 << 20) + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("SQLFileByteReaderBoundTests-\(UUID().uuidString).sql.gz") + try GzipDeflater.compress(zeros).write(to: url) + defer { try? FileManager.default.removeItem(at: url) } + + let reader = try SQLFileByteReader(url: url) + let first = try reader.read(upToCount: 64 * 1_024) + #expect(!first.isEmpty) + #expect(first.count < 8 << 20) + + var total = first.count + while true { + let next = try reader.read(upToCount: 64 * 1_024) + if next.isEmpty { break } + total += next.count + } + #expect(total == zeros.count) + } +} diff --git a/apple/Plugins/FormatPluginTests/ExportImportRoundTripTests.swift b/apple/Plugins/FormatPluginTests/ExportImportRoundTripTests.swift index fef8f82850..6f4c0b30b2 100644 --- a/apple/Plugins/FormatPluginTests/ExportImportRoundTripTests.swift +++ b/apple/Plugins/FormatPluginTests/ExportImportRoundTripTests.swift @@ -54,6 +54,39 @@ struct ExportImportRoundTripTests { try RoundTrip.expectSame(target, RoundTripFixture.bulkTable, RoundTripFixture.bulkRows) } + @Test("A gzipped SQL dump split into parts writes each part as its own gzip file, and they restore in order") + func gzippedSplitSQLRestoresInPartOrder() async throws { + // Hex text packs to about half its size, so 4 MB of it passes a 1 MB cap after compression. + var generator = SystemRandomNumberGenerator() + let noiseRows: [[StoredValue]] = (0 ..< 4_000).map { index in + let hex = (0 ..< 500).map { _ in String(format: "%02x", UInt8.random(in: 0 ... 255, using: &generator)) } + return [.integer(Int64(index + 1)), .text(hex.joined())] + } + let source = try RoundTripDatabase() + try source.execute(#"CREATE TABLE "noise" ("id" INTEGER PRIMARY KEY, "body" TEXT)"#) + for row in noiseRows { + try source.insert(row, into: "noise") + } + var options = SQLExportOptions() + options.compressWithGzip = true + options.splitSizeMegabytes = 1 + + let dump = try await RoundTrip.sqlDump(of: ["noise"], from: source, options: options, fileExtension: "sql.gz") + defer { RoundTrip.remove(dump.files) } + #expect(dump.files.count >= 2) + #expect(dump.result.warnings.allSatisfy { !$0.contains("split size was not applied") }) + for file in dump.files { + let bytes = try Data(contentsOf: file) + #expect(bytes.prefix(2) == Data([0x1F, 0x8B])) + #expect(bytes.count <= 1 << 20) + #expect(try !RoundTripImportFile.text(of: file).isEmpty) + } + + let target = try RoundTripDatabase() + try await RoundTrip.restore(dump.files, into: target) + try RoundTrip.expectSame(target, "noise", noiseRows) + } + @Test("A SQL dump split into parts restores every row when the parts run in order") func splitSQLRestoresInPartOrder() async throws { let source = try RoundTripFixture.databaseWithBulk() diff --git a/apple/Plugins/FormatPluginTests/SQLExportGzipWriterTests.swift b/apple/Plugins/FormatPluginTests/SQLExportGzipWriterTests.swift new file mode 100644 index 0000000000..dfcd9c92d4 --- /dev/null +++ b/apple/Plugins/FormatPluginTests/SQLExportGzipWriterTests.swift @@ -0,0 +1,83 @@ +// +// SQLExportGzipWriterTests.swift +// FormatPluginTests +// + +import Foundation +import TableProGzip +import TableProPluginKit +import Testing + +// The writer deflates as it writes, so a gzip dump never exists uncompressed on disk, and a split +// cap is the size of each gzip file. +struct SQLExportGzipWriterTests { + private func directory() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + // Hex packs to about half its size, so three of these pass a 1 MiB cap after compression. + private func statement(_ index: Int) -> String { + var generator = SystemRandomNumberGenerator() + let hex = (0 ..< 250_000).map { _ in String(UInt8.random(in: 0 ... 15, using: &generator), radix: 16) }.joined() + return "INSERT INTO t VALUES (\(index), '\(hex)');\n" + } + + @Test("Each part of a split gzip dump is a gzip file of its own, at most the cap, and they join to the dump") + func splitGzipPartsStandAlone() throws { + let directory = try directory() + defer { try? FileManager.default.removeItem(at: directory) } + let destination = directory.appendingPathComponent("dump.sql.gz") + let writer = try SQLExportFileWriter(destination: destination, splitSizeMegabytes: 1, compressesWithGzip: true) + let statements = (0 ..< 12).map(statement) + for text in statements { + try writer.write(text) + } + let written = try writer.commit() + + #expect(written.count >= 2) + #expect(written.first?.lastPathComponent == "dump.part1.sql.gz") + var joined = Data() + for part in written { + let bytes = try Data(contentsOf: part) + #expect(bytes.count <= 1 << 20) + let inflated = try GzipInflater.decompress(bytes) + #expect(String(decoding: inflated, as: UTF8.self).hasSuffix(";\n")) + joined.append(inflated) + } + #expect(String(decoding: joined, as: UTF8.self) == statements.joined()) + let leftovers = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasSuffix(".tmp") } + #expect(leftovers.isEmpty) + } + + @Test("An unsplit gzip dump keeps its name and inflates to every statement written") + func unsplitGzipKeepsItsName() throws { + let directory = try directory() + defer { try? FileManager.default.removeItem(at: directory) } + let destination = directory.appendingPathComponent("dump.sql.gz") + let writer = try SQLExportFileWriter(destination: destination, splitSizeMegabytes: 0, compressesWithGzip: true) + let text = (0 ..< 50_000).map { "INSERT INTO t VALUES (\($0));\n" }.joined() + try writer.write(text) + + #expect(try writer.commit() == [destination]) + let inflated = try GzipInflater.decompress(try Data(contentsOf: destination)) + #expect(String(decoding: inflated, as: UTF8.self) == text) + } + + @Test("A Stop that lands while the last compression drains publishes nothing and leaves no temporary file") + func stopBeforePublishLeavesNothing() throws { + let directory = try directory() + defer { try? FileManager.default.removeItem(at: directory) } + let destination = directory.appendingPathComponent("dump.sql.gz") + let writer = try SQLExportFileWriter(destination: destination, splitSizeMegabytes: 0, compressesWithGzip: true) + try writer.write("SELECT 1;\n") + + #expect(throws: PluginExportCancellationError.self) { + try writer.commit { throw PluginExportCancellationError() } + } + writer.rollback() + + #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty) + } +} diff --git a/apple/Plugins/SQLExportPlugin/SQLExportCompressor.swift b/apple/Plugins/SQLExportPlugin/SQLExportCompressor.swift deleted file mode 100644 index e1aefcb41d..0000000000 --- a/apple/Plugins/SQLExportPlugin/SQLExportCompressor.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// SQLExportCompressor.swift -// SQLExportPlugin -// - -import Foundation -import TableProGzip -import TableProPluginKit - -// Compresses through the atomic pair, so a failed or stopped compression leaves the previous file whole (#2533). -nonisolated internal enum SQLExportCompressor { - // Often enough that whoever watches the status sees the run move, rarely enough to cost nothing. - private static let statusInterval = Duration.milliseconds(250) - - @concurrent - internal static func compress( - source: URL, - to destination: URL, - progress: PluginExportProgress - ) async throws { - try progress.checkCancellation() - - let (handle, tempURL) = try PluginExportUtilities.beginAtomicWrite(for: destination) - var committed = false - defer { - if !committed { PluginExportUtilities.rollbackAtomicWrite(at: tempURL) } - } - - let clock = ContinuousClock() - var lastStatus: ContinuousClock.Instant? - do { - try GzipFile.compress(source: source, into: handle, isCancelled: { progress.isCancelled }) { done, total in - let now = clock.now - if done < total, let lastStatus, now - lastStatus < Self.statusInterval { return } - lastStatus = now - progress.setStatus(Self.status(done: done, total: total)) - } - } catch is CancellationError { - try? handle.close() - throw PluginExportCancellationError() - } catch { - try? handle.close() - throw error - } - // A volume can report a deferred write failure only at close, and a swallowed one would let a truncated temp - // replace a valid dump. - try handle.close() - // A Stop that lands after the last chunk still abandons the file. - try progress.checkCancellation() - try PluginExportUtilities.commitAtomicWrite(from: tempURL, to: destination) - committed = true - } - - private static func status(done: Int64, total: Int64) -> String { - String( - format: String(localized: "Compressing\u{2026} %1$@ of %2$@"), - ByteCountFormatter.string(fromByteCount: done, countStyle: .file), - ByteCountFormatter.string(fromByteCount: total, countStyle: .file) - ) - } -} diff --git a/apple/Plugins/SQLExportPlugin/SQLExportFileWriter.swift b/apple/Plugins/SQLExportPlugin/SQLExportFileWriter.swift index a0a241c319..06fb5711e0 100644 --- a/apple/Plugins/SQLExportPlugin/SQLExportFileWriter.swift +++ b/apple/Plugins/SQLExportPlugin/SQLExportFileWriter.swift @@ -6,7 +6,8 @@ import Foundation import TableProPluginKit -/// Writes a dump, starting a new file once the current one passes a size cap. +/// Writes a dump, starting a new file once the current one passes a size cap. With gzip on, each +/// part is a gzip file of its own, deflated as it is written, and the cap is the compressed size. /// /// Rotation happens between writes and never inside one, so a part always ends on a complete /// statement: a restore that replays the parts in order gets the same statements in the same order @@ -34,12 +35,12 @@ nonisolated internal final class SQLExportFileWriter { private let destination: URL private let splitSizeBytes: Int + private let compressesWithGzip: Bool private let sessionDeclaration: SQLExportSessionDeclaration private let publish: (URL, URL) throws -> Void - private var handle: FileHandle + private var output: any SQLExportPartOutput private var tempURL: URL - private var bytesInCurrentPart = 0 private var currentPartHasStatements = false private var partIndex = 1 private var pending: [(temp: URL, final: URL)] = [] @@ -60,14 +61,18 @@ nonisolated internal final class SQLExportFileWriter { destination: URL, splitSizeMegabytes: Int, sessionDeclaration: SQLExportSessionDeclaration = .empty, + compressesWithGzip: Bool = false, publish: @escaping (URL, URL) throws -> Void = SQLExportFileWriter.publishAtomically ) throws { self.destination = destination self.splitSizeBytes = max(0, splitSizeMegabytes) * 1_024 * 1_024 self.sessionDeclaration = sessionDeclaration + self.compressesWithGzip = compressesWithGzip self.publish = publish - let (handle, tempURL) = try PluginExportUtilities.beginAtomicWrite(for: destination) - self.handle = handle + let (output, tempURL) = try Self.openPart( + for: destination, compressesWithGzip: compressesWithGzip, splitSizeBytes: splitSizeBytes + ) + self.output = output self.tempURL = tempURL do { try beginPart() @@ -91,16 +96,15 @@ nonisolated internal final class SQLExportFileWriter { internal func write(_ text: String, opening scope: SQLExportSessionScope? = nil) throws { let data = try text.toUTF8Data() let scopeBytes = (scope?.opener.utf8.count ?? 0) + (scope?.closer.utf8.count ?? 0) - let partSize = bytesInCurrentPart + data.count + scopeBytes + partTailBytes - if splitSizeBytes > 0, currentPartHasStatements, partSize > splitSizeBytes { + if splitSizeBytes > 0, currentPartHasStatements, + try output.wouldExceed(splitSizeBytes, adding: data.count + scopeBytes + partTailBytes) { try rotate() } if let scope { openScopes.append(scope) try writeRaw(scope.opener) } - try handle.write(contentsOf: data) - bytesInCurrentPart += data.count + try output.write(data) currentPartHasStatements = true } @@ -115,12 +119,16 @@ nonisolated internal final class SQLExportFileWriter { /// user chose; a split one numbers all of its parts, so no part silently claims that name. /// Parts go out in order, so a publish that fails partway leaves the dump's first parts rather /// than a hole in the middle of it, and the failure names them. + /// + /// `beforePublish` runs once every part is closed, after a gzip part's queued compression has + /// drained, so a Stop that lands during that wait still leaves the destination as it was. @discardableResult - internal func commit() throws -> [URL] { + internal func commit(beforePublish: () throws -> Void = {}) throws -> [URL] { try endPart() - try handle.close() + try output.close() let finalURL = didSplit ? Self.partURL(for: destination, part: partIndex) : destination pending.append((tempURL, finalURL)) + try beforePublish() didAttemptPublish = true for entry in pending { do { @@ -140,7 +148,7 @@ nonisolated internal final class SQLExportFileWriter { /// parts it did publish are not ours to take back. internal func rollback() { guard !didAttemptPublish else { return } - try? handle.close() + output.abandon() PluginExportUtilities.rollbackAtomicWrite(at: tempURL) for entry in pending { PluginExportUtilities.rollbackAtomicWrite(at: entry.temp) @@ -156,19 +164,32 @@ nonisolated internal final class SQLExportFileWriter { } } - /// The file the caller compresses when gzip is on. Compression runs over a single file, so a - /// split export is the one case it cannot apply to. - internal var currentFileURL: URL { tempURL } + private static func openPart( + for destination: URL, + compressesWithGzip: Bool, + splitSizeBytes: Int + ) throws -> (any SQLExportPartOutput, URL) { + let (handle, tempURL) = try PluginExportUtilities.beginAtomicWrite(for: destination) + guard compressesWithGzip else { return (SQLExportPlainOutput(handle: handle), tempURL) } + do { + return (try SQLExportGzipOutput(handle: handle, splitSizeBytes: splitSizeBytes), tempURL) + } catch { + try? handle.close() + PluginExportUtilities.rollbackAtomicWrite(at: tempURL) + throw error + } + } private func rotate() throws { try endPart() - try handle.close() + try output.close() pending.append((tempURL, Self.partURL(for: destination, part: partIndex))) partIndex += 1 - let (nextHandle, nextTemp) = try PluginExportUtilities.beginAtomicWrite(for: destination) - handle = nextHandle + let (nextOutput, nextTemp) = try Self.openPart( + for: destination, compressesWithGzip: compressesWithGzip, splitSizeBytes: splitSizeBytes + ) + output = nextOutput tempURL = nextTemp - bytesInCurrentPart = 0 currentPartHasStatements = false try beginPart() } @@ -201,9 +222,7 @@ nonisolated internal final class SQLExportFileWriter { private func writeRaw(_ text: String) throws { guard !text.isEmpty else { return } - let data = try text.toUTF8Data() - try handle.write(contentsOf: data) - bytesInCurrentPart += data.count + try output.write(try text.toUTF8Data()) } } diff --git a/apple/Plugins/SQLExportPlugin/SQLExportPartOutput.swift b/apple/Plugins/SQLExportPlugin/SQLExportPartOutput.swift new file mode 100644 index 0000000000..0916991070 --- /dev/null +++ b/apple/Plugins/SQLExportPlugin/SQLExportPartOutput.swift @@ -0,0 +1,193 @@ +// +// SQLExportPartOutput.swift +// SQLExportPlugin +// + +import Foundation +import TableProGzip + +/// Where one part of a dump goes: the file as written, or a gzip stream over it. +nonisolated internal protocol SQLExportPartOutput: AnyObject { + func write(_ data: Data) throws + + /// Whether the part, closed after `extra` more bytes, could be larger than `cap` bytes on disk. + func wouldExceed(_ cap: Int, adding extra: Int) throws -> Bool + + /// Writes what the part still owes and closes the file. A volume can report a deferred write + /// failure only at close, so it throws rather than letting a truncated part be published. + func close() throws + + /// Closes the file without finishing it, for a part that will be removed. + func abandon() +} + +nonisolated internal final class SQLExportPlainOutput: SQLExportPartOutput { + private let handle: FileHandle + private var written = 0 + + internal init(handle: FileHandle) { + self.handle = handle + } + + internal func write(_ data: Data) throws { + try handle.write(contentsOf: data) + written += data.count + } + + internal func wouldExceed(_ cap: Int, adding extra: Int) throws -> Bool { + written + extra > cap + } + + internal func close() throws { + try handle.close() + } + + internal func abandon() { + try? handle.close() + } +} + +/// Deflates on a serial queue of its own, so compression overlaps reading the next rows instead of +/// following the whole dump. The queue holds at most `maxChunksInFlight` chunks; a writer that gets +/// ahead of it waits, which keeps memory bounded by a few chunks whatever the dump's size. +/// +/// The size of a part on disk is known exactly only up to the last sync flush. A splitting writer +/// flushes every `syncInterval` input bytes, so the bound it rotates on is at most that far above +/// the truth, and it drains the queue before deciding a part is full. +/// +/// Unchecked: the writer's state is touched only by the one caller, the deflater and the handle +/// only on the serial queue, and what both read is behind the lock. +nonisolated internal final class SQLExportGzipOutput: SQLExportPartOutput, @unchecked Sendable { + private struct Progress { + var compressedBytes = 0 + var syncedInputBytes = 0 + var compressedBytesAtSync = 0 + var failure: (any Error)? + } + + private static let chunkSize = 1 << 20 + private static let maxChunksInFlight = 2 + + private let handle: FileHandle + private let deflater: GzipDeflater + private let queue = DispatchQueue(label: "com.TablePro.SQLExport.gzip", qos: .userInitiated) + private let slots = DispatchSemaphore(value: maxChunksInFlight) + private let progressLock = NSLock() + private var progressState = Progress() + private let syncInterval: Int? + + private var buffer = Data() + private var acceptedInputBytes = 0 + private var inputBytesAtLastSync = 0 + + /// `splitSizeBytes` above zero turns on the periodic sync flush a size cap needs. + internal init(handle: FileHandle, splitSizeBytes: Int) throws { + self.handle = handle + self.deflater = try GzipDeflater(container: .gzip) + self.syncInterval = splitSizeBytes > 0 ? min(Self.chunkSize, max(splitSizeBytes / 32, 16 * 1_024)) : nil + buffer.reserveCapacity(Self.chunkSize) + } + + internal func write(_ data: Data) throws { + try rethrowFailure() + buffer.append(data) + acceptedInputBytes += data.count + if let syncInterval, acceptedInputBytes - inputBytesAtLastSync >= syncInterval { + submit(flushing: true) + } else if buffer.count >= Self.chunkSize { + submit(flushing: false) + } + } + + internal func wouldExceed(_ cap: Int, adding extra: Int) throws -> Bool { + try rethrowFailure() + if bound(adding: extra) <= cap { return false } + // The quick bound counts every byte since the last sync as incompressible; flush to know. + submit(flushing: true) + queue.sync {} + try rethrowFailure() + return bound(adding: extra) > cap + } + + internal func close() throws { + submit(flushing: false) + queue.sync { + guard withProgress({ $0.failure == nil }) else { return } + do { + try deflater.finish { try handle.write(contentsOf: $0) } + } catch { + withProgress { $0.failure = error } + } + } + if let failure = withProgress({ $0.failure }) { + try? handle.close() + throw failure + } + try handle.close() + } + + internal func abandon() { + queue.sync {} + try? handle.close() + } + + // zlib's worst case for incompressible input is a stored block of 5 bytes per 16 KiB; the + // constant covers the final block and the 8-byte trailer. + private static func compressedBound(_ input: Int) -> Int { + input + (input >> 11) + 64 + } + + private func bound(adding extra: Int) -> Int { + let synced = withProgress { (bytes: $0.compressedBytesAtSync, input: $0.syncedInputBytes) } + return synced.bytes + Self.compressedBound(acceptedInputBytes - synced.input + extra) + } + + private func submit(flushing: Bool) { + guard !buffer.isEmpty || flushing else { return } + let chunk = buffer + buffer = Data() + buffer.reserveCapacity(Self.chunkSize) + let inputThrough = acceptedInputBytes + if flushing { inputBytesAtLastSync = inputThrough } + // Backpressure: the queue is a dispatch queue, not the cooperative pool, so it always frees a slot. + slots.wait() + queue.async { [self] in + defer { slots.signal() } + deflate(chunk, flushing: flushing, inputThrough: inputThrough) + } + } + + // Runs on `queue` only. + private func deflate(_ chunk: Data, flushing: Bool, inputThrough: Int) { + guard withProgress({ $0.failure == nil }) else { return } + do { + var produced = 0 + let sink: (UnsafeRawBufferPointer) throws -> Void = { [handle] bytes in + try handle.write(contentsOf: bytes) + produced += bytes.count + } + try chunk.withUnsafeBytes { try deflater.deflate($0, into: sink) } + if flushing { try deflater.flush(into: sink) } + let written = produced + withProgress { state in + state.compressedBytes += written + if flushing { + state.syncedInputBytes = inputThrough + state.compressedBytesAtSync = state.compressedBytes + } + } + } catch { + withProgress { $0.failure = error } + } + } + + private func withProgress(_ body: (inout Progress) -> T) -> T { + progressLock.lock() + defer { progressLock.unlock() } + return body(&progressState) + } + + private func rethrowFailure() throws { + if let failure = withProgress({ $0.failure }) { throw failure } + } +} diff --git a/apple/Plugins/SQLExportPlugin/SQLExportPlugin.swift b/apple/Plugins/SQLExportPlugin/SQLExportPlugin.swift index 70ea66ca33..11c390f186 100644 --- a/apple/Plugins/SQLExportPlugin/SQLExportPlugin.swift +++ b/apple/Plugins/SQLExportPlugin/SQLExportPlugin.swift @@ -97,36 +97,18 @@ nonisolated final class SQLExportPlugin: ObservableObject, ExportFormatPlugin, S groupReads: groupReads(for: tables, dataSource: dataSource, progress: progress)) var statementTally = SQLExportStatementTally() - let actualDestination: URL - let gzipTempURL: URL? - - if options.compressWithGzip { - let tempSQL = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString + ".sql") - gzipTempURL = tempSQL - actualDestination = tempSQL - } else { - gzipTempURL = nil - actualDestination = destination - } - - // Compression runs over one file, so a compressed export never splits, and says so. - let splitSize = options.compressWithGzip ? 0 : options.splitSizeMegabytes - if options.compressWithGzip, options.splitSizeMegabytes > 0 { - run.metadataWarnings.append(String(localized: - "A compressed export is written as one file, so the split size was not applied.")) - } var readScope = await SQLExportReadScope.open(on: dataSource, for: tables) let writer: SQLExportFileWriter do { writer = try SQLExportFileWriter( - destination: actualDestination, - splitSizeMegabytes: splitSize, + destination: destination, + splitSizeMegabytes: options.splitSizeMegabytes, sessionDeclaration: .forDatabaseType( dataSource.databaseTypeId, readTimeZone: readScope.readTimeZone, readsWithANSIQuotes: readScope.readsWithANSIQuotes, - literalsEscapeBackslash: dataSource.lexicalFeatures.contains(.backslashEscapesInSingleQuotes)) + literalsEscapeBackslash: dataSource.lexicalFeatures.contains(.backslashEscapesInSingleQuotes)), + compressesWithGzip: options.compressWithGzip ) } catch { await readScope.close(on: dataSource) @@ -193,7 +175,7 @@ nonisolated final class SQLExportPlugin: ObservableObject, ExportFormatPlugin, S await readScope.close(on: dataSource) // The publication point: a Stop during any phase above, the grant phase included, must not replace the file. try progress.checkCancellation() - let writtenParts = try writer.commit() + let writtenParts = try writer.commit { try progress.checkCancellation() } committed = true if writer.didSplit, let first = writtenParts.first, let last = writtenParts.last { run.metadataWarnings.append(String( @@ -213,13 +195,6 @@ nonisolated final class SQLExportPlugin: ObservableObject, ExportFormatPlugin, S throw error } - if options.compressWithGzip, let gzipSource = gzipTempURL { - progress.setStatus(String(localized: "Compressing\u{2026}")) - defer { try? FileManager.default.removeItem(at: gzipSource) } - try await SQLExportCompressor.compress( - source: gzipSource, to: destination, progress: progress) - } - progress.finalizeTable() var warnings: [String] = [] diff --git a/apple/TablePro/Core/Plugins/SqlFileImportSource.swift b/apple/TablePro/Core/Plugins/SqlFileImportSource.swift index bd85d6e30f..8aff3fb621 100644 --- a/apple/TablePro/Core/Plugins/SqlFileImportSource.swift +++ b/apple/TablePro/Core/Plugins/SqlFileImportSource.swift @@ -19,24 +19,17 @@ final class SqlFileImportSource: PluginImportSource, @unchecked Sendable { private let family: TransactionEngineFamily private let parser = SQLFileParser() - private let externalDecompressedURL: URL? - private let _decompressedURL = OSAllocatedUnfairLock(initialState: nil) - private let ownsDecompressedFile: Bool - + // A `.gz` is read through the parser's inflater, so no expanded copy is written to disk. init( url: URL, encoding: String.Encoding, grammar: @escaping @Sendable () -> SQLLexicalGrammar = { .ansi }, - family: TransactionEngineFamily = .other, - decompressedURL: URL? = nil, - ownsDecompressedFile: Bool? = nil + family: TransactionEngineFamily = .other ) { self.url = url self.encoding = encoding self.grammar = OSAllocatedUnfairLock(initialState: grammar) self.family = family - self.externalDecompressedURL = decompressedURL - self.ownsDecompressedFile = ownsDecompressedFile ?? (decompressedURL == nil) } func fileURL() -> URL { @@ -44,12 +37,11 @@ final class SqlFileImportSource: PluginImportSource, @unchecked Sendable { } func fileSizeBytes() -> Int64 { - let targetURL = effectiveURL do { - let attrs = try FileManager.default.attributesOfItem(atPath: targetURL.path(percentEncoded: false)) + let attrs = try FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false)) return attrs[.size] as? Int64 ?? 0 } catch { - Self.logger.warning("Failed to get file size for \(targetURL.path(percentEncoded: false)): \(error.localizedDescription)") + Self.logger.warning("Failed to get file size for \(self.url.path(percentEncoded: false)): \(error.localizedDescription)") return 0 } } @@ -59,25 +51,23 @@ final class SqlFileImportSource: PluginImportSource, @unchecked Sendable { grammar.withLock { $0 = provider } } - // Bytes read from the file the parser opens, which for a `.gz` is the decompressed copy. + // Bytes read from the file on disk, which for a `.gz` are its compressed bytes. func reportsReading(to handler: @escaping @Sendable (_ bytesRead: Int64, _ fileSize: Int64) -> Void) { readReporter.withLock { $0 = handler } } func statements() async throws -> AsyncThrowingStream<(statement: String, lineNumber: Int), Error> { - let fileURL = try await resolveURL() let grammar = self.grammar.withLock { $0 } let onRead = readReporter.withLock { $0 } - let parsed = parser.parseFile(url: fileURL, encoding: encoding, grammar: grammar, onRead: onRead) + let parsed = parser.parseFile(url: url, encoding: encoding, grammar: grammar, onRead: onRead) guard SQLDumpStatementRewriter.rewrites(fileDecodedFrom: encoding) else { return parsed } return rewriter(grammar: grammar).rewriting(parsed) } func elements() async throws -> AsyncThrowingStream { - let fileURL = try await resolveURL() let grammar = self.grammar.withLock { $0 } let onRead = readReporter.withLock { $0 } - var parsed = parser.parseElements(url: fileURL, encoding: encoding, grammar: grammar, onRead: onRead) + var parsed = parser.parseElements(url: url, encoding: encoding, grammar: grammar, onRead: onRead) if SQLDumpStatementRewriter.rewrites(fileDecodedFrom: encoding) { parsed = rewriter(grammar: grammar).rewriting(parsed) } @@ -90,63 +80,6 @@ final class SqlFileImportSource: PluginImportSource, @unchecked Sendable { private func rewriter(grammar: @escaping @Sendable () -> SQLLexicalGrammar) -> SQLDumpStatementRewriter { SQLDumpStatementRewriter(encoding: encoding, family: family.dumpFamily, grammar: grammar) } - - // A file this source decompressed is always its own to remove: a retry arrives with the flag off, and gating on it - // leaked the whole expanded dump. - func cleanup() { - let tempURL = _decompressedURL.withLock { - let url = $0 - $0 = nil - return url - } - let external = ownsDecompressedFile ? externalDecompressedURL : nil - - for fileURL in [tempURL, external].compactMap({ $0 }) { - do { - try FileManager.default.removeItem(at: fileURL) - } catch { - Self.logger.warning("Failed to clean up temp file: \(error.localizedDescription)") - } - } - } - - deinit { - let tempURL = _decompressedURL.withLock { $0 } - let external = ownsDecompressedFile ? externalDecompressedURL : nil - for fileURL in [tempURL, external].compactMap({ $0 }) { - try? FileManager.default.removeItem(at: fileURL) - } - } - - // MARK: - Private - - private var effectiveURL: URL { - if let external = externalDecompressedURL { - return external - } - if let decompressed = _decompressedURL.withLock({ $0 }) { - return decompressed - } - return url - } - - private func resolveURL() async throws -> URL { - if let external = externalDecompressedURL { - return external - } - - if let existing = _decompressedURL.withLock({ $0 }) { - return existing - } - - let result = try await FileDecompressor.decompressIfNeeded(url) - - if result != url { - _decompressedURL.withLock { $0 = result } - } - - return result - } } extension TransactionEngineFamily { diff --git a/apple/TablePro/Core/Services/Export/ImportService.swift b/apple/TablePro/Core/Services/Export/ImportService.swift index 6959fc99ef..0fab374fda 100644 --- a/apple/TablePro/Core/Services/Export/ImportService.swift +++ b/apple/TablePro/Core/Services/Export/ImportService.swift @@ -120,9 +120,6 @@ final class ImportService: ObservableObject { formatId: String, encoding: String.Encoding, scope: DatabaseScope, - decompressedURL: URL? = nil, - ownsDecompressedFile: Bool = false, - knownStatementCount: Int? = nil, targetTable: String? = nil, columnMapping: [String: String] = [:], sourceFields: Set = [], @@ -132,8 +129,7 @@ final class ImportService: ObservableObject { do { let result = try await performImportFile( from: url, sourceName: sourceName, formatId: formatId, encoding: encoding, scope: scope, - decompressedURL: decompressedURL, ownsDecompressedFile: ownsDecompressedFile, - knownStatementCount: knownStatementCount, targetTable: targetTable, columnMapping: columnMapping, + targetTable: targetTable, columnMapping: columnMapping, sourceFields: sourceFields, rowWriting: rowWriting, authorization: authorization ) await run.complete() @@ -153,9 +149,6 @@ final class ImportService: ObservableObject { formatId: String, encoding: String.Encoding, scope: DatabaseScope, - decompressedURL: URL? = nil, - ownsDecompressedFile: Bool = false, - knownStatementCount: Int? = nil, targetTable: String? = nil, columnMapping: [String: String] = [:], sourceFields: Set = [], @@ -172,7 +165,9 @@ final class ImportService: ObservableObject { state = ImportState(isImporting: true) state.fileName = historyName state.countsRows = targetTable != nil - state.totalIsEstimate = knownStatementCount == nil + // No statement count is taken up front: it lexed the whole file once more before the import. Progress + // follows the bytes read, and the statements run are a running count. + state.totalIsEstimate = true let workId = beginRunningWork(named: historyName) defer { state.isImporting = false @@ -183,28 +178,21 @@ final class ImportService: ObservableObject { let sqlSource = type(of: plugin).requiresTargetTable ? nil : SqlFileImportSource( url: url, encoding: encoding, - family: TransactionEngineFamily.of(connection.type), - decompressedURL: decompressedURL, - ownsDecompressedFile: ownsDecompressedFile + family: TransactionEngineFamily.of(connection.type) ) sqlSource?.reportsReading(to: fileReadingReporter()) let source: any PluginImportSource if let sqlSource { source = sqlSource } else { - source = PlainFileImportSource(url: decompressedURL ?? url) + source = PlainFileImportSource(url: url) } defer { source.cleanup() } guard !isStopRequested else { throw PluginImportCancellationError() } - // After the source exists, so a refusal still removes the decompressed copy it was handed. try await authorizeRun(named: historyName, given: authorization) - let initialTotal = Int64(knownStatementCount ?? 0) - let nsProgress = Progress(totalUnitCount: initialTotal) + let nsProgress = Progress(totalUnitCount: 0) let progress = PluginImportProgress(progress: nsProgress) - if knownStatementCount != nil { - state.estimatedTotalStatements = Int(initialTotal) - } currentProgress = progress let observations = track(nsProgress) defer { observations.forEach { $0.invalidate() } } diff --git a/apple/TablePro/Core/Utilities/File/FileDecompressor.swift b/apple/TablePro/Core/Utilities/File/FileDecompressor.swift deleted file mode 100644 index 3635477186..0000000000 --- a/apple/TablePro/Core/Utilities/File/FileDecompressor.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// FileDecompressor.swift -// TablePro -// - -import Foundation -import TableProGzip - -enum FileDecompressor { - private static func innerExtension(for url: URL) -> String { - let name = url.deletingPathExtension().pathExtension.lowercased() - return name.isEmpty ? "sql" : name - } - - // The file panel accepts DUMP.SQL.GZ too, and a missed one reaches the statement parser still gzipped. - static func isCompressed(_ url: URL) -> Bool { - url.pathExtension.lowercased() == ImportFileFormatResolver.compressedFileExtension - } - - static func decompressIfNeeded(_ url: URL) async throws -> URL { - guard isCompressed(url) else { return url } - - let tempURL = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString + "." + innerExtension(for: url)) - try await GzipFile.decompress(source: url, destination: tempURL) - return tempURL - } -} diff --git a/apple/TablePro/Views/Import/ImportDialog.swift b/apple/TablePro/Views/Import/ImportDialog.swift index d11f358026..ce5a4734f8 100644 --- a/apple/TablePro/Views/Import/ImportDialog.swift +++ b/apple/TablePro/Views/Import/ImportDialog.swift @@ -32,8 +32,6 @@ struct ImportDialog: View { @State private var fileURL: URL? @State private var filePreview: String = "" @State private var fileSize: Int64 = 0 - @State private var statementCount: Int = 0 - @State private var isCountingStatements = false @State private var selectedEncoding: ImportEncoding @State private var detectedEncoding: ImportEncoding? @State private var selectedFormatId: String = "sql" @@ -44,9 +42,7 @@ struct ImportDialog: View { @State private var hostWindow: NSWindow? @State private var hasPreviewError = false - @State private var tempPreviewURL: URL? @State private var loadFileTask: Task? - @State private var countStatementsTask: Task? @State private var importTask: Task? // MARK: - Import Service @@ -117,7 +113,7 @@ struct ImportDialog: View { } .task { if let initialURL = initialFileURL, fileURL == nil { - // Tracked like a picked file, so a pick made during a long decompression cancels this load. + // Tracked like a picked file, so a pick made during a slow preview read cancels this load. let load = Task { await loadFile(initialURL) } loadFileTask = load await load.value @@ -133,9 +129,7 @@ struct ImportDialog: View { } .onDisappear { loadFileTask?.cancel() - countStatementsTask?.cancel() importTask?.cancel() - cleanupTempFiles() if !importSucceeded { restoreSettingsSnapshot() } @@ -206,28 +200,12 @@ struct ImportDialog: View { .font(.callout) } - HStack(spacing: 16) { - Label( - ByteCountFormatter.string(fromByteCount: fileSize, countStyle: .file), - systemImage: "chart.bar.doc.horizontal" - ) - .font(.callout) - .foregroundStyle(.secondary) - - if isCountingStatements { - HStack(spacing: 4) { - ProgressView() - .controlSize(.small) - Text("Counting…") - .font(.callout) - .foregroundStyle(.secondary) - } - } else if statementCount > 0 { - Label("\(statementCount) statements", systemImage: "list.bullet") - .font(.callout) - .foregroundStyle(.secondary) - } - } + Label( + ByteCountFormatter.string(fromByteCount: fileSize, countStyle: .file), + systemImage: "chart.bar.doc.horizontal" + ) + .font(.callout) + .foregroundStyle(.secondary) } } .frame(maxWidth: .infinity, alignment: .leading) @@ -376,12 +354,6 @@ struct ImportDialog: View { @MainActor private func loadFile(_ url: URL) async { - // The previous file's count must not land under this one, even when this one fails before counting. - countStatementsTask?.cancel() - countStatementsTask = nil - statementCount = 0 - isCountingStatements = false - cleanupTempFiles() hasPreviewError = false var isDirectory: ObjCBool = false @@ -403,49 +375,24 @@ struct ImportDialog: View { fileSize = 0 } - let urlToRead: URL - do { - urlToRead = try await FileDecompressor.decompressIfNeeded(url) - // A newer pick owns the dialog now; its import must not read this file's copy. - guard !Task.isCancelled else { - if urlToRead != url { - try? FileManager.default.removeItem(at: urlToRead) - } - return - } - if urlToRead != url { - tempPreviewURL = urlToRead - } - } catch is CancellationError { - return - } catch { - filePreview = String(format: String(localized: "Failed to decompress file: %@"), error.localizedDescription) - hasPreviewError = true - return - } - + // A `.gz` is previewed from its first inflated bytes; the import inflates it as it reads, so no expanded copy is + // written and no up-front pass lexes the whole file. do { - let handle = try FileHandle(forReadingFrom: urlToRead) - defer { - do { - try handle.close() - } catch { - Self.logger.warning("Failed to close file handle for preview: \(error.publicLogShape, privacy: .public)") - } - } - let maxPreviewSize = 5 * 1_024 * 1_024 - let previewData = try handle.read(upToCount: maxPreviewSize) ?? Data() + let leading = try await Self.leadingBytes(of: url, limit: maxPreviewSize) + // A newer pick owns the dialog now. + guard !Task.isCancelled else { return } + let previewData = leading.data if let preview = SQLDumpEncodingChoice.decodedPreview( - previewData, as: selectedEncoding.encoding, isWholeFile: previewData.count < maxPreviewSize + previewData, as: selectedEncoding.encoding, isWholeFile: leading.isWholeFile ) { filePreview = preview hasPreviewError = false } else if let detected = SQLDumpEncodingChoice.encoding( replacing: selectedEncoding.encoding, forPreview: previewData, - isWholeFile: previewData.count < maxPreviewSize, + isWholeFile: leading.isWholeFile, family: TransactionEngineFamily.of(connection.type).dumpFamily, grammar: sessionGrammar ).flatMap({ found in ImportEncoding.allCases.first { $0.encoding == found } }) { @@ -461,11 +408,12 @@ struct ImportDialog: View { filePreview = String(format: String(localized: "Failed to load preview: %@"), error.localizedDescription) hasPreviewError = true } + } - countStatementsTask?.cancel() - countStatementsTask = Task { - await countStatements(url: urlToRead) - } + // Off the main actor: inflating the first 5 MB of a `.gz` takes a moment. + @concurrent + nonisolated private static func leadingBytes(of url: URL, limit: Int) async throws -> (data: Data, isWholeFile: Bool) { + try SQLFileByteReader.leadingBytes(of: url, limit: limit) } @MainActor @@ -473,39 +421,12 @@ struct ImportDialog: View { SQLLexicalResolver.executionGrammar(for: connection.type, connectionId: connection.id) } - @MainActor - private func countStatements(url: URL) async { - isCountingStatements = true - statementCount = 0 - - do { - let count = try await ImportStatementCount.count( - url, - encoding: selectedEncoding.encoding, - grammar: sessionGrammar - ) - // A new file or encoding cancelled this count and started its own, which owns the result. - guard !Task.isCancelled else { return } - statementCount = count - } catch { - guard !Task.isCancelled else { return } - Self.logger.warning("Failed to count statements: \(error.publicLogShape, privacy: .public)") - statementCount = 0 - } - - isCountingStatements = false - } - private func performImport() { guard let url = fileURL else { return } let service = ImportService(connection: connection) importService = service - let decompressedURL = tempPreviewURL - let ownsDecompressedFile = decompressedURL != nil - tempPreviewURL = nil - phase = .running importTask = Task { @@ -517,10 +438,7 @@ struct ImportDialog: View { from: url, formatId: selectedFormatId, encoding: selectedEncoding.encoding, - scope: scope, - decompressedURL: decompressedURL, - ownsDecompressedFile: ownsDecompressedFile, - knownStatementCount: statementCount > 0 ? statementCount : nil + scope: scope ) await MainActor.run { @@ -548,36 +466,4 @@ struct ImportDialog: View { CatalogChangeService.post(.changed(CatalogChange(connectionId: connection.id, kinds: .everything))) } } - - private func cleanupTempFiles() { - if let tempURL = tempPreviewURL { - do { - try FileManager.default.removeItem(at: tempURL) - } catch { - Self.logger.error( - "cleanupTempFiles: Failed to remove tempPreviewURL at \(tempURL.path(percentEncoded: false), privacy: .private(mask: .hash)): \(error.publicLogShape, privacy: .public)" - ) - } - tempPreviewURL = nil - } - } -} - -enum ImportStatementCount { - // Detached keeps the scan off the main actor but ignores the caller's cancel, so the cancel is passed on. - static func count( - _ url: URL, - encoding: String.Encoding, - grammar: SQLLexicalGrammar, - parser: SQLFileParser = SQLFileParser() - ) async throws -> Int { - let counting = Task.detached { - try await parser.countStatements(url: url, encoding: encoding, grammar: grammar) - } - return try await withTaskCancellationHandler { - try await counting.value - } onCancel: { - counting.cancel() - } - } } diff --git a/apple/TableProTests/Core/Plugins/SqlFileImportSourceCleanupTests.swift b/apple/TableProTests/Core/Plugins/SqlFileImportSourceCleanupTests.swift deleted file mode 100644 index 300a4520eb..0000000000 --- a/apple/TableProTests/Core/Plugins/SqlFileImportSourceCleanupTests.swift +++ /dev/null @@ -1,121 +0,0 @@ -// -// SqlFileImportSourceCleanupTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import TableProPluginKit -import TableProSQLGrammar -import Testing - -/// A `.gz` the source expanded itself is the source's to delete, whoever owns the file the caller -/// handed over. Gating both on one flag leaked the whole expanded dump on every retry, because a -/// retry arrives with no caller-supplied file and therefore with the flag off. -/// Serialized because it watches the shared temporary directory for the file the source expands -/// into, and a `.sql` file another test wrote in the same window would be mistaken for it. -@Suite("SQL file import source cleanup", .serialized) -struct SqlFileImportSourceCleanupTests { - private func writeGzip(_ sql: String) throws -> URL { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent("sql-source-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - let plain = directory.appendingPathComponent("dump.sql") - try sql.write(to: plain, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/gzip") - process.arguments = [plain.path] - try process.run() - process.waitUntilExit() - - return directory.appendingPathComponent("dump.sql.gz") - } - - /// `FileDecompressor` writes to `temporaryDirectory/.sql`, so the file cannot be found by - /// name. The test watches which `.sql` files appear while it runs instead. - private func temporarySQLFiles() -> Set { - let contents = (try? FileManager.default.contentsOfDirectory( - at: FileManager.default.temporaryDirectory, includingPropertiesForKeys: nil - )) ?? [] - return Set(contents.filter { $0.pathExtension == "sql" }.map(\.lastPathComponent)) - } - - /// The retry shape: `ImportDialog` clears `tempPreviewURL` on the first attempt, so the second - /// attempt constructs the source with no decompressed file and `ownsDecompressedFile: false`. - @Test("A retry cleans up the file it decompressed for itself") - func retryCleansUpItsOwnDecompressedFile() async throws { - let archive = try writeGzip("SELECT 1;\n") - defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) } - - let before = temporarySQLFiles() - - let source = SqlFileImportSource( - url: archive, - encoding: .utf8, - grammar: { TestGrammar.standard }, - decompressedURL: nil, - ownsDecompressedFile: false - ) - _ = try await source.statements() - - let decompressed = temporarySQLFiles().subtracting(before) - #expect(!decompressed.isEmpty, "the source did not decompress anything, so nothing is proven") - - source.cleanup() - - let leaked = temporarySQLFiles().intersection(decompressed) - #expect(leaked.isEmpty, "cleanup left the decompressed dump behind: \(leaked)") - } - - /// The first-attempt shape, where the dialog hands over the file it decompressed for the - /// preview and says the source now owns it. - @Test("A caller-supplied decompressed file is removed when the source owns it") - func callerSuppliedFileIsRemovedWhenOwned() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent("sql-source-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - - let archive = directory.appendingPathComponent("dump.sql.gz") - try Data().write(to: archive) - let expanded = directory.appendingPathComponent("expanded.sql") - try "SELECT 1;\n".write(to: expanded, atomically: true, encoding: .utf8) - - let source = SqlFileImportSource( - url: archive, - encoding: .utf8, - grammar: { TestGrammar.standard }, - decompressedURL: expanded, - ownsDecompressedFile: true - ) - source.cleanup() - - #expect(FileManager.default.fileExists(atPath: expanded.path) == false) - } - - /// The dialog still needs its own preview copy afterwards when it kept ownership. - @Test("A caller-supplied decompressed file is left alone when the source does not own it") - func callerSuppliedFileSurvivesWhenNotOwned() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent("sql-source-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - - let archive = directory.appendingPathComponent("dump.sql.gz") - try Data().write(to: archive) - let expanded = directory.appendingPathComponent("expanded.sql") - try "SELECT 1;\n".write(to: expanded, atomically: true, encoding: .utf8) - - let source = SqlFileImportSource( - url: archive, - encoding: .utf8, - grammar: { TestGrammar.standard }, - decompressedURL: expanded, - ownsDecompressedFile: false - ) - source.cleanup() - - #expect(FileManager.default.fileExists(atPath: expanded.path)) - } -} diff --git a/apple/TableProTests/Core/Plugins/SqlFileImportSourceGzipTests.swift b/apple/TableProTests/Core/Plugins/SqlFileImportSourceGzipTests.swift new file mode 100644 index 0000000000..d2ac34a1a3 --- /dev/null +++ b/apple/TableProTests/Core/Plugins/SqlFileImportSourceGzipTests.swift @@ -0,0 +1,80 @@ +// +// SqlFileImportSourceGzipTests.swift +// TableProTests +// + +import Foundation +import os +@testable import TablePro +import TableProPluginKit +import TableProSQLGrammar +import Testing + +/// A `.sql.gz` import used to inflate the whole dump to a temporary `.sql` before the first +/// statement, writing the uncompressed size to disk and reading it back. The source now reads the +/// statements through the parser's inflater, so the temporary directory gains nothing. +/// Serialized because it watches the shared temporary directory for an expanded copy. +@Suite("SQL file import source reads gzip in place", .serialized) +struct SqlFileImportSourceGzipTests { + private func writeGzip(_ sql: String) throws -> URL { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("sql-source-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let plain = directory.appendingPathComponent("dump.sql") + try sql.write(to: plain, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/gzip") + process.arguments = [plain.path] + process.environment = [:] + try process.run() + process.waitUntilExit() + + return directory.appendingPathComponent("dump.sql.gz") + } + + private func temporarySQLFiles() -> Set { + let contents = (try? FileManager.default.contentsOfDirectory( + at: FileManager.default.temporaryDirectory, includingPropertiesForKeys: nil + )) ?? [] + return Set(contents.filter { $0.pathExtension == "sql" }.map(\.lastPathComponent)) + } + + @Test("A gzipped dump yields its statements with no expanded copy on disk") + func gzipIsReadInPlace() async throws { + let sql = (1...300).map { "INSERT INTO t VALUES (\($0));\n" }.joined() + let archive = try writeGzip(sql) + defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) } + let before = temporarySQLFiles() + + let source = SqlFileImportSource(url: archive, encoding: .utf8, grammar: { TestGrammar.standard }) + var statements: [String] = [] + for try await (statement, _) in try await source.statements() { + statements.append(statement) + } + + #expect(statements.count == 300) + #expect(statements.first == "INSERT INTO t VALUES (1)") + #expect(temporarySQLFiles().subtracting(before).isEmpty) + } + + @Test("Progress reads the compressed bytes against the size of the file on disk") + func progressFollowsCompressedBytes() async throws { + let sql = (1...3_000).map { "INSERT INTO t VALUES (\($0), 'row');\n" }.joined() + let archive = try writeGzip(sql) + defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) } + let onDisk = try #require( + try FileManager.default.attributesOfItem(atPath: archive.path)[.size] as? Int64 + ) + let last = OSAllocatedUnfairLock<(read: Int64, size: Int64)?>(initialState: nil) + + let source = SqlFileImportSource(url: archive, encoding: .utf8, grammar: { TestGrammar.standard }) + source.reportsReading { read, size in last.withLock { $0 = (read, size) } } + for try await _ in try await source.statements() {} + + #expect(source.fileSizeBytes() == onDisk) + let report = try #require(last.withLock { $0 }) + #expect(report.size == onDisk) + #expect(report.read == onDisk) + } +} diff --git a/apple/TableProTests/Core/Services/Export/ImportFileFormatResolverTests.swift b/apple/TableProTests/Core/Services/Export/ImportFileFormatResolverTests.swift index d99501537a..fbefb5a235 100644 --- a/apple/TableProTests/Core/Services/Export/ImportFileFormatResolverTests.swift +++ b/apple/TableProTests/Core/Services/Export/ImportFileFormatResolverTests.swift @@ -93,13 +93,11 @@ struct ImportFileFormatResolverTests { #expect(match(".sql.gz") == .format("sql")) } - @Test("An uppercase compressed dump resolves and is still recognized as compressed") - func uppercaseCompressedDumpIsExpanded() { + // The parser tells a gzip file by its magic number, so the name's case cannot leave one unread. + @Test("An uppercase compressed dump resolves to its format") + func uppercaseCompressedDumpResolves() { #expect(match("DUMP.SQL.GZ") == .format("sql")) #expect(match("ORDERS.CSV.GZ") == .compressedRowFormat(formatId: "csv")) - #expect(FileDecompressor.isCompressed(URL(fileURLWithPath: "/tmp/DUMP.SQL.GZ"))) - #expect(FileDecompressor.isCompressed(URL(fileURLWithPath: "/tmp/dump.sql.gz"))) - #expect(FileDecompressor.isCompressed(URL(fileURLWithPath: "/tmp/dump.sql")) == false) } @Test("Nothing reads .gz means a compressed file resolves to nothing") diff --git a/apple/TableProTests/Views/Import/ImportStatementCountTests.swift b/apple/TableProTests/Views/Import/ImportStatementCountTests.swift deleted file mode 100644 index 9bb6aabc11..0000000000 --- a/apple/TableProTests/Views/Import/ImportStatementCountTests.swift +++ /dev/null @@ -1,41 +0,0 @@ -import Foundation -@testable import TablePro -import TableProSQLGrammar -import Testing - -struct ImportStatementCountTests { - private func script(statements: Int) throws -> URL { - let url = FileManager.default.temporaryDirectory.appendingPathComponent("count-\(UUID().uuidString).sql") - try Data(String(repeating: "SELECT 1;\n", count: statements).utf8).write(to: url) - return url - } - - @Test("A count reaches every statement in the file") - func countsEveryStatement() async throws { - let url = try script(statements: 1_000) - defer { try? FileManager.default.removeItem(at: url) } - - let count = try await ImportStatementCount.count(url, encoding: .utf8, grammar: TestGrammar.postgres) - - #expect(count == 1_000) - } - - @Test("Cancelling the dialog's count stops the scan before the end of the file", .timeLimit(.minutes(1))) - func cancelReachesTheScan() async throws { - let total = 2_000_000 - let url = try script(statements: total) - defer { try? FileManager.default.removeItem(at: url) } - - let counting = Task { - try await ImportStatementCount.count(url, encoding: .utf8, grammar: TestGrammar.postgres) - } - counting.cancel() - - switch await counting.result { - case .success(let count): - #expect(count < total) - case .failure(let error): - #expect(error is CancellationError) - } - } -} From 5532826ccba9c6270ed6be34ccc10e632f57a40e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 07:06:18 +0700 Subject: [PATCH 2/2] docs(changelog): note streaming gzip export and import --- apple/changelog.d/4594.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 apple/changelog.d/4594.changed.md diff --git a/apple/changelog.d/4594.changed.md b/apple/changelog.d/4594.changed.md new file mode 100644 index 0000000000..abf6084d38 --- /dev/null +++ b/apple/changelog.d/4594.changed.md @@ -0,0 +1 @@ +A gzipped SQL export compresses as it writes and can be split, and a .sql.gz import reads without unpacking first.