SPB Git

Repository Public MIT

Support.swift 13.1 KB 280 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraPersistence/Sources/Support.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import CryptoKit90import GRDB91import AstraCore9293/// Errors raised by the store itself (SQLite errors surface as GRDB's `DatabaseError`).94public enum AstraStoreError: Error, LocalizedError, Sendable, Hashable {95    case notFound(String)96    case attachmentTooLarge(limit: Int, actual: Int)97    case invalidAttachmentReference98    case missingAttachmentData(String)99    case invalidOperation(String)100    /// The database was written by a newer version of the app: this build must not touch it.101    case newerDatabase([String])102    /// The file is not a readable database (damaged, truncated, or not a database at all).103    case damagedDatabase(String)104105    public var errorDescription: String? {106        switch self {107        case .newerDatabase:108            "This data was saved by a newer version of ORIX Astra. Update the app to open it. Your data was left as it is."109        case .damagedDatabase:110            "The database file is damaged and cannot be opened. Your attachments and downloaded models are untouched."111        case .notFound(let what): "\(what) no longer exists."112        case .attachmentTooLarge(let limit, let actual):113            "This file is too large (\(ByteCountFormatter.string(fromByteCount: Int64(actual), countStyle: .file)); the limit is \(ByteCountFormatter.string(fromByteCount: Int64(limit), countStyle: .file)))."114        case .invalidAttachmentReference: "The attachment reference is not valid."115        case .missingAttachmentData(let name): "The file for “\(name)” is missing from this device."116        case .invalidOperation(let message): message117        }118    }119}120121extension FetchableRecord {122    /// Fetches a list, leaving out rows this build cannot decode (a provider or an option added by a newer version, a value123    /// damaged on disk). One unreadable row must never make every other row disappear.124    static func fetchReadable(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments()) throws -> [Self] {125        try Row.fetchAll(db, sql: sql, arguments: arguments).compactMap { try? Self(row: $0) }126    }127}128129/// A record stored in one SQLite table. Dates are stored as seconds since the reference date (lossless round trip),130/// nested value types as JSON text.131public protocol AstraRecord: Codable, Hashable, Identifiable, Sendable, FetchableRecord, PersistableRecord where ID == String {}132133public extension AstraRecord {134    static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy { .timeIntervalSinceReferenceDate }135    static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { .timeIntervalSinceReferenceDate }136}137138extension AstraRecord {139    static func find(_ db: Database, id: String) throws -> Self? { try filter(Column("id") == id).fetchOne(db) }140141    static func require(_ db: Database, id: String) throws -> Self {142        guard let record = try find(db, id: id) else { throw AstraStoreError.notFound("This item") }143        return record144    }145146    /// Updates every column of the row whose `id` matches, whatever the table's primary key is.147    func updateByID(_ db: Database) throws {148        let values = try databaseDictionary149        let columns = values.keys.filter { $0 != "id" }.sorted()150        let assignments = columns.map { "\"\($0)\" = :\($0)" }.joined(separator: ", ")151        try db.execute(sql: "UPDATE \"\(Self.databaseTableName)\" SET \(assignments) WHERE id = :id", arguments: StatementArguments(values))152        if db.changesCount == 0 { throw AstraStoreError.notFound("This item") }153    }154155    @discardableResult156    static func remove(_ db: Database, id: String) throws -> Bool { try filter(Column("id") == id).deleteAll(db) > 0 }157}158159enum DBJSON {160    /// Lossless local coding: dates stay exact doubles, keys are sorted so the text is stable.161    static func encode<T: Encodable>(_ value: T) throws -> String {162        let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]163        return String(decoding: try encoder.encode(value), as: UTF8.self)164    }165    static func decode<T: Decodable>(_ type: T.Type, _ text: String) throws -> T { try JSONDecoder().decode(type, from: Data(text.utf8)) }166    static func decodeIfPresent<T: Decodable>(_ type: T.Type, _ text: String?) -> T? { text.flatMap { try? decode(type, $0) } }167}168169enum ExportCoding {170    static var encoder: JSONEncoder {171        let encoder = JSONEncoder()172        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]173        encoder.dateEncodingStrategy = .iso8601174        return encoder175    }176    static var decoder: JSONDecoder { let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601; return decoder }177    static func iso(_ date: Date) -> String { date.formatted(.iso8601) }178}179180extension Date {181    var dbValue: Double { timeIntervalSinceReferenceDate }182    init(dbValue: Double) { self.init(timeIntervalSinceReferenceDate: dbValue) }183}184185enum AstraID {186    static func new() -> String { UUID().uuidString }187}188189enum Hashing {190    static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }191    static func isSHA256(_ text: String) -> Bool {192        text.utf8.count == 64 && text.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) }193    }194}195196/// RFC 4180 CSV writing, plus a guard against spreadsheet formula injection for text cells.197public enum CSVWriter {198    public static func field(_ raw: String) -> String {199        var text = raw200        if let first = text.unicodeScalars.first, "=+-@\t\r".unicodeScalars.contains(first), Double(text) == nil { text = "'" + text }201        let needsQuotes = text.contains { $0 == "," || $0 == "\"" || $0.isNewline } || text.hasPrefix(" ") || text.hasSuffix(" ")202        return needsQuotes ? "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : text203    }204    public static func line(_ fields: [String]) -> String { fields.map(field).joined(separator: ",") }205    public static func document(header: [String], rows: [[String]]) -> String {206        ([line(header)] + rows.map(line)).joined(separator: "\r\n") + "\r\n"207    }208    static func number(_ value: Double?) -> String { value.map { String($0) } ?? "" }209    static func number(_ value: Int?) -> String { value.map { String($0) } ?? "" }210}211212/// Builds FTS5 `MATCH` expressions from arbitrary text. Every term is a quoted string made only of letters and digits,213/// so nothing a person or a model types can be read as FTS5 syntax (`"`, `*`, `NEAR`, `AND`, column filters...).214public enum FTSQuery {215    public enum Mode: Sendable { case allPrefixes, anyTerm }216217    public static func terms(_ text: String, limit: Int = 24) -> [String] {218        var out: [String] = []; var current = ""219        func flush() { if !current.isEmpty { out.append(String(current.prefix(64))); current = "" } }220        for character in text {221            if character.isLetter || character.isNumber { current.append(character) } else { flush() }222            if out.count >= limit { return out }223        }224        flush()225        return Array(out.prefix(limit))226    }227228    /// Returns nil when the text has no searchable term.229    public static func pattern(_ text: String, mode: Mode = .allPrefixes) -> String? {230        var seen = Set<String>()231        let unique = terms(text).filter { seen.insert($0.lowercased()).inserted }232        guard !unique.isEmpty else { return nil }233        switch mode {234        case .allPrefixes: return unique.map { "\"\($0)\"*" }.joined(separator: " ")235        case .anyTerm:236            let useful = unique.filter { $0.count > 1 || containsUnsegmentedScript($0) }237            return (useful.isEmpty ? unique : useful).map { "\"\($0)\"" }.joined(separator: " OR ")238        }239    }240241    /// Scripts written without spaces (CJK, Thai...) are indexed as whole runs by `unicode61`; substring search serves them better.242    public static func containsUnsegmentedScript(_ text: String) -> Bool {243        text.unicodeScalars.contains { scalar in244            switch scalar.value {245            case 0x0E00...0x0E7F, 0x3040...0x30FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xAC00...0xD7AF, 0xF900...0xFAFF, 0x20000...0x2FA1F: true246            default: false247            }248        }249    }250251    /// A `LIKE` pattern matching `text` literally anywhere (use with `ESCAPE '\'`).252    public static func likePattern(_ text: String) -> String {253        var out = "%"254        for character in text.trimmingCharacters(in: .whitespacesAndNewlines) {255            if character == "%" || character == "_" || character == "\\" { out.append("\\") }256            out.append(character)257        }258        return out + "%"259    }260261    static func snippet(of text: String, around query: String, radius: Int = 48) -> String {262        let needle = query.trimmingCharacters(in: .whitespacesAndNewlines)263        guard let range = text.range(of: needle, options: [.caseInsensitive, .diacriticInsensitive]) else { return String(text.prefix(radius * 2)) }264        let start = text.index(range.lowerBound, offsetBy: -radius, limitedBy: text.startIndex) ?? text.startIndex265        let end = text.index(range.upperBound, offsetBy: radius, limitedBy: text.endIndex) ?? text.endIndex266        let body = text[start..<end].replacingOccurrences(of: "\n", with: " ")267        return (start > text.startIndex ? "…" : "") + body + (end < text.endIndex ? "…" : "")268    }269}270271extension Array where Element == Float {272    var blob: Data { withUnsafeBufferPointer { Data(buffer: $0) } }273    init(blob: Data) {274        self = blob.withUnsafeBytes { raw in275            let count = raw.count / MemoryLayout<Float>.size276            return (0..<count).map { raw.loadUnaligned(fromByteOffset: $0 * MemoryLayout<Float>.size, as: Float.self) }277        }278    }279}280
Files main
Menu

Theme