Skip to content

Commit 19722ac

Browse files
authored
perf(macos): free each chunk the SQL import parser reads instead of holding the whole file (#4279)
1 parent 2a9690f commit 19722ac

5 files changed

Lines changed: 60 additions & 12 deletions

File tree

‎apple/TablePro/Core/Utilities/SQL/SQLFileParser.swift‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1186,21 +1186,25 @@ extension SQLFileParser {
11861186
return ctx.sawBatchSeparator
11871187
}
11881188

1189+
// A MySQL count keeps each statement's text, so the cut drains per statement as well as per chunk.
11891190
private func readNextStatement() throws {
1190-
processBuffer()
1191-
guard ctx.collected.isEmpty else { return }
1192-
guard !ctx.atEndOfInput else {
1193-
emitTrailingStatement()
1194-
finished = true
1195-
closeFile()
1196-
return
1191+
try autoreleasepool {
1192+
processBuffer()
1193+
guard ctx.collected.isEmpty else { return }
1194+
guard !ctx.atEndOfInput else {
1195+
emitTrailingStatement()
1196+
finished = true
1197+
closeFile()
1198+
return
1199+
}
1200+
try readChunk()
11971201
}
1198-
try readChunk()
11991202
}
12001203

12011204
private func readChunk() throws {
12021205
let handle = try openFileIfNeeded()
1203-
let rawData = handle.readData(ofLength: limits.chunkSize)
1206+
// A count, a GO scan and a driver's COPY read chunk after chunk with nothing draining the autorelease pool.
1207+
let rawData = try autoreleasepool { try handle.read(upToCount: limits.chunkSize) } ?? Data()
12041208
if !rawData.isEmpty, let onRead {
12051209
bytesRead += Int64(rawData.count)
12061210
onRead(bytesRead, fileSize)
@@ -1337,8 +1341,10 @@ extension SQLFileParser {
13371341

13381342
private func nextRowsPiece(generation: Int) throws -> Data? {
13391343
do {
1340-
guard let piece = try nextRowsRange(generation: generation) else { return nil }
1341-
return Data(nsBuffer.substring(with: piece).utf8)
1344+
return try autoreleasepool {
1345+
guard let piece = try nextRowsRange(generation: generation) else { return nil }
1346+
return Data(nsBuffer.substring(with: piece).utf8)
1347+
}
13421348
} catch {
13431349
rowsFailure = error
13441350
copyRows = nil

‎apple/TablePro/Views/Import/ImportDialog.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ struct ImportDialog: View {
437437
}
438438

439439
let maxPreviewSize = 5 * 1_024 * 1_024
440-
let previewData = handle.readData(ofLength: maxPreviewSize)
440+
let previewData = try handle.read(upToCount: maxPreviewSize) ?? Data()
441441

442442
var decoder = SQLChunkDecoder(encoding: selectedEncoding.encoding)
443443
if let preview = decoder.decode(previewData) {

‎apple/TableProTests/Core/Utilities/SQL/SQLFileParserTests.swift‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,46 @@ struct SQLFileParserTests {
415415
#expect(count == statementCount)
416416
}
417417

418+
@Test("An empty file holds no statement, parsed or counted")
419+
func emptyFile() async throws {
420+
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".sql")
421+
try Data().write(to: url)
422+
defer { try? FileManager.default.removeItem(at: url) }
423+
424+
let parser = SQLFileParser()
425+
var statements: [String] = []
426+
for try await (statement, _) in parser.parseFile(url: url, encoding: .utf8, grammar: TestGrammar.postgres) {
427+
statements.append(statement)
428+
}
429+
#expect(statements.isEmpty)
430+
#expect(try await parser.countStatements(url: url, encoding: .utf8, grammar: TestGrammar.postgres) == 0)
431+
}
432+
433+
@Test("A last statement with no ; arrives when the file ends on a full read chunk", arguments: [1, 6, 9, 18])
434+
func lastStatementEndsOnChunkBoundary(chunkSize: Int) async throws {
435+
let sql = "SELECT 1;\nSELECT 2"
436+
try #require(sql.utf8.count % chunkSize == 0)
437+
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".sql")
438+
try Data(sql.utf8).write(to: url)
439+
defer { try? FileManager.default.removeItem(at: url) }
440+
441+
let parser = SQLFileParser(chunkSize: chunkSize)
442+
var statements: [String] = []
443+
for try await (statement, _) in parser.parseFile(url: url, encoding: .utf8, grammar: TestGrammar.postgres) {
444+
statements.append(statement)
445+
}
446+
#expect(statements == ["SELECT 1", "SELECT 2"])
447+
#expect(try await parser.countStatements(url: url, encoding: .utf8, grammar: TestGrammar.postgres) == 2)
448+
}
449+
450+
@Test("A UTF-8 file cut inside its last character fails rather than dropping the bytes")
451+
func fileCutInsideItsLastCharacter() async throws {
452+
let cut = Data(Data("SELECT 'é".utf8).dropLast())
453+
await #expect(throws: DecompressionError.self) {
454+
_ = try await Self.parse(cut, encoding: .utf8)
455+
}
456+
}
457+
418458
@Test("Dialect.from maps known database type ids")
419459
func dialect_from_database_type_id() {
420460
#expect(SqlDialect.from(databaseTypeId: "PostgreSQL") == .postgres)

‎apple/changelog.d/4279.fixed.1.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
A read error while previewing or importing a SQL file quit TablePro instead of failing the import.

‎apple/changelog.d/4279.fixed.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Importing a large SQL file held memory the size of the file while counting its statements or loading COPY rows.

0 commit comments

Comments
 (0)