SPB Git

Repository Public License

CSV.swift 7.1 KB 159 lines swift

1import Foundation2import PrismCore34public enum CSV {5    public struct Limits: Sendable {6        public var maxBytes = 50 * 1024 * 10247        public var maxRows = 200_0008        public var maxColumns = 2009        public init() {}10    }1112    /// RFC 4180 parsing: quoted fields, doubled quotes, CRLF/LF/CR, optional BOM, `,` `;` or tab delimiter.13    public static func parse(_ data: Data, limits: Limits = Limits()) throws -> [[String]] {14        guard data.count <= limits.maxBytes else { throw DataError("The file is larger than \(limits.maxBytes / 1_048_576) MB.") }15        guard let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {16            throw DataError("The file is not readable text.")17        }18        return try parse(text, limits: limits)19    }2021    public static func parse(_ input: String, limits: Limits = Limits()) throws -> [[String]] {22        var scalars = Array(input.unicodeScalars)23        if scalars.first == "\u{FEFF}" { scalars.removeFirst() }24        let delimiter = detectDelimiter(scalars)25        var rows: [[String]] = []26        var row: [String] = []27        var field = String.UnicodeScalarView()28        var inQuotes = false, fieldWasQuoted = false29        var i = 030        func endField() { row.append(String(field)); field = String.UnicodeScalarView(); fieldWasQuoted = false }31        func endRow() throws {32            endField()33            if !(row.count == 1 && row[0].isEmpty) {34                guard row.count <= limits.maxColumns else { throw DataError("A row has more than \(limits.maxColumns) columns.") }35                rows.append(row)36                guard rows.count <= limits.maxRows else { throw DataError("The file has more than \(limits.maxRows) rows.") }37            }38            row = []39        }40        while i < scalars.count {41            let c = scalars[i]42            if inQuotes {43                if c == "\"" {44                    if i + 1 < scalars.count, scalars[i + 1] == "\"" { field.append("\""); i += 1 } else { inQuotes = false }45                } else { field.append(c) }46            } else if c == "\"" && field.isEmpty && !fieldWasQuoted {47                inQuotes = true; fieldWasQuoted = true48            } else if c == delimiter {49                endField()50            } else if c == "\n" || c == "\r" {51                if c == "\r", i + 1 < scalars.count, scalars[i + 1] == "\n" { i += 1 }52                try endRow()53            } else { field.append(c) }54            i += 155        }56        guard !inQuotes else { throw DataError("The file ends inside a quoted value.") }57        if !field.isEmpty || !row.isEmpty || fieldWasQuoted { try endRow() }58        return rows59    }6061    private static func detectDelimiter(_ scalars: [Unicode.Scalar]) -> Unicode.Scalar {62        var counts: [Unicode.Scalar: Int] = [",": 0, ";": 0, "\t": 0]63        var inQuotes = false64        for c in scalars.prefix(4000) {65            if c == "\"" { inQuotes.toggle() }66            if !inQuotes {67                if c == "\n" || c == "\r" { break }68                if counts[c] != nil { counts[c]! += 1 }69            }70        }71        return counts.max { $0.value < $1.value || ($0.value == $1.value && $0.key != ",") }?.key ?? ","72    }7374    public static func serialize(_ rows: [[String]]) -> String {75        rows.map { row in76            row.map { field in77                field.contains(where: { $0 == "," || $0 == "\"" || $0 == "\n" || $0 == "\r" })78                    ? "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : field79            }.joined(separator: ",")80        }.joined(separator: "\r\n") + "\r\n"81    }8283    /// Text that a spreadsheet would run as a formula is prefixed with `'` (CSV injection).84    public static func neutralize(_ text: String) -> String {85        guard let first = text.first, "=+-@\t\r".contains(first) else { return text }86        return "'" + text87    }88}8990public struct CSVImportReport: Sendable, Equatable {91    public var imported = 092    public var skipped = 093    /// Header name → table column it was mapped to.94    public var mapping: [String: String] = [:]95    public var unmappedHeaders: [String] = []96    /// First few row-level problems, e.g. "Row 7: Amount must be a number."97    public var problems: [String] = []98}99100extension AppDataStore {101    /// Imports a CSV whose first row is a header. Columns are matched by name or label, ignoring case and punctuation.102    /// Valid rows are stored in one transaction; invalid rows are skipped and reported. File content is only ever data.103    @discardableResult104    public func importCSV(_ data: Data, into table: String, limits: CSV.Limits = CSV.Limits()) throws -> CSVImportReport {105        let schema = try schema(table)106        let rows = try CSV.parse(data, limits: limits)107        guard let header = rows.first else { throw DataError("The file is empty.") }108        func key(_ s: String) -> String { s.lowercased().filter { $0.isLetter || $0.isNumber } }109        var report = CSVImportReport()110        var columnFor: [Int: ColumnSchema] = [:]111        for (i, h) in header.enumerated() {112            if let c = schema.columns.first(where: { key($0.name) == key(h) || key($0.label) == key(h) }),113               !columnFor.values.contains(where: { $0.name == c.name }) {114                columnFor[i] = c115                report.mapping[h] = c.name116            } else {117                report.unmappedHeaders.append(h)118            }119        }120        guard !columnFor.isEmpty else {121            throw DataError("None of the file's columns (\(header.joined(separator: ", "))) match this table (\(schema.columns.map(\.label).joined(separator: ", "))).")122        }123        var valid: [[String: JSONValue]] = []124        for (n, row) in rows.dropFirst().enumerated() {125            var record: [String: JSONValue] = [:]126            do {127                for (i, column) in columnFor where i < row.count {128                    record[column.name] = try schema.coerce(.string(row[i].trimmingCharacters(in: .whitespaces)), for: column)129                }130                for column in schema.columns where column.required && (record[column.name] ?? .null).isNull && column.defaultValue == nil {131                    throw DataError("\(column.label) is required.")132                }133                valid.append(record)134            } catch {135                report.skipped += 1136                if report.problems.count < 20 { report.problems.append("Row \(n + 2): \(error.localizedDescription)") }137            }138        }139        try insertAll(into: table, rows: valid)140        report.imported = valid.count141        return report142    }143144    public func exportCSV(rows: [[String: JSONValue]], columns: [ColumnSchema]) -> Data {145        var out: [[String]] = [columns.map(\.label)]146        for row in rows {147            out.append(columns.map { c in148                let v = row[c.name] ?? .null149                switch c.type {150                case .text: return CSV.neutralize(v.displayString)151                case .boolean: return v.isNull ? "" : (v.isTruthy ? "true" : "false")152                default: return v.displayString153                }154            })155        }156        return Data(CSV.serialize(out).utf8)157    }158}159
Files main
Menu

Theme