Skip to content
Open
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
4 changes: 2 additions & 2 deletions apple/Packages/TableProCore/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
),
Expand Down Expand Up @@ -546,7 +546,7 @@ let package = Package(
),
.testTarget(
name: "TableProSQLFileTests",
dependencies: ["TableProSQLFile", "TableProSQLGrammar", "TableProTabularIO"],
dependencies: ["TableProSQLFile", "TableProSQLGrammar", "TableProTabularIO", "TableProGzip"],
path: "Tests/TableProSQLFileTests",
swiftSettings: pluginCoreSettings
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
33 changes: 33 additions & 0 deletions apple/Plugins/FormatPluginTests/ExportImportRoundTripTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading