Skip to content
Merged
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
799 changes: 658 additions & 141 deletions Sources/Lithe/Application/DatabaseFeatureModel.swift

Large diffs are not rendered by default.

140 changes: 119 additions & 21 deletions Sources/Lithe/Application/DatabaseSQLSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ enum DatabaseSQLStatementKind: String, Codable, Equatable, Sendable {
case mutation
case definition
case transaction
case batch
case unknown

var usesQueryEndpoint: Bool {
Expand All @@ -38,8 +39,28 @@ struct DatabaseSQLAnalysis: Equatable, Sendable {
let statementCount: Int
let requiresConfirmation: Bool
let warning: String?
let statements: [String]

var canExecute: Bool { statementCount == 1 }
var canExecute: Bool { !statements.isEmpty || statementCount == 1 }

init(
kind: DatabaseSQLStatementKind,
statementCount: Int,
requiresConfirmation: Bool,
warning: String?,
statements: [String] = []
) {
self.kind = kind
self.statementCount = statementCount
self.requiresConfirmation = requiresConfirmation
self.warning = warning
self.statements = statements
}
}

enum DatabaseSQLExecutionScope: Equatable, Sendable {
case all
case selection(String)
}

struct DatabaseSQLTab: Identifiable, Equatable, Sendable {
Expand Down Expand Up @@ -111,18 +132,37 @@ struct DatabaseSQLHistoryEntry: Codable, Equatable, Identifiable, Sendable {
enum DatabaseSQLAnalyzer {
static func analyze(_ sql: String) -> DatabaseSQLAnalysis {
let statements = DatabaseSQLLexing.statements(in: sql)
guard statements.count == 1, let statement = statements.first else {
guard !statements.isEmpty else {
return DatabaseSQLAnalysis(
kind: .unknown,
statementCount: statements.count,
requiresConfirmation: false,
warning: statements.isEmpty ? "Enter a SQL statement." : "Run one SQL statement at a time."
warning: "Enter a SQL statement.",
statements: statements
)
}

let analyses = statements.map(analyzeSingle)
let kinds = analyses.map(\.kind)
let kind = statements.count > 1 ? .batch : kinds[0]
return DatabaseSQLAnalysis(
kind: kind,
statementCount: statements.count,
requiresConfirmation: analyses.contains(where: \.requiresConfirmation),
warning: warning(for: analyses),
statements: statements
)
}

private static func warning(for analyses: [DatabaseSQLAnalysis]) -> String? {
let warnings = analyses.compactMap(\.warning)
return warnings.first(where: { !$0.contains("not recognized") }) ?? warnings.first
}

private static func analyzeSingle(_ statement: String) -> DatabaseSQLAnalysis {
let tokens = DatabaseSQLLexing.keywords(in: statement)
guard let first = tokens.first else {
return DatabaseSQLAnalysis(kind: .unknown, statementCount: 0, requiresConfirmation: false, warning: "Enter a SQL statement.")
return DatabaseSQLAnalysis(kind: .unknown, statementCount: 0, requiresConfirmation: false, warning: "Enter a SQL statement.", statements: [])
}

let kind: DatabaseSQLStatementKind
Expand All @@ -139,19 +179,19 @@ enum DatabaseSQLAnalyzer {

let isUnqualifiedWrite = (tokens.contains("UPDATE") || tokens.contains("DELETE")) && !tokens.contains("WHERE")
let isDestructive = tokens.contains("DROP") || tokens.contains("TRUNCATE")
let isUnknownWrite = kind == .unknown
let requiresConfirmation = isUnqualifiedWrite || isDestructive || isUnknownWrite
let isUnknownStatement = kind == .unknown
let requiresConfirmation = isUnqualifiedWrite || isDestructive
let warning: String?
if isUnqualifiedWrite {
warning = "This UPDATE or DELETE has no WHERE clause and can affect every row."
} else if isDestructive {
warning = "This statement can permanently remove database objects or data."
} else if isUnknownWrite {
warning = "This statement could change the database and needs confirmation."
} else if isUnknownStatement {
warning = "This statement type is not recognized locally; the database will validate it."
} else {
warning = nil
}
return DatabaseSQLAnalysis(kind: kind, statementCount: 1, requiresConfirmation: requiresConfirmation, warning: warning)
return DatabaseSQLAnalysis(kind: kind, statementCount: 1, requiresConfirmation: requiresConfirmation, warning: warning, statements: [statement])
}
}

Expand Down Expand Up @@ -287,41 +327,99 @@ private enum DatabaseSQLLexing {
var lineComment = false
var blockComment = false

func appendCurrentStatement() {
guard !sanitized(current).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
statements.append(current)
}

while index < characters.count {
let character = characters[index]
let next = index + 1 < characters.count ? characters[index + 1] : nil
if lineComment {
if character == "\n" { lineComment = false; current.append(" ") }
index += 1; continue
current.append(character)
if character == "\n" { lineComment = false }
index += 1
continue
}
if blockComment {
if character == "*", next == "/" { blockComment = false; index += 2; current.append(" ") }
else { index += 1 }
current.append(character)
if character == "*", next == "/" {
current.append("/")
blockComment = false
index += 2
} else {
index += 1
}
continue
}
if let activeQuote = quote {
current.append(" ")
current.append(character)
if character == "\\", next != nil {
current.append(next!)
index += 2
continue
}
if character == activeQuote {
if next == activeQuote { index += 1; current.append(" ") }
if next == activeQuote { index += 1; current.append(activeQuote) }
else { quote = nil }
}
index += 1; continue
}
if character == "-", next == "-" { lineComment = true; index += 2; current.append(" "); continue }
if character == "/", next == "*" { blockComment = true; index += 2; current.append(" "); continue }
if character == "'" || character == "\"" || character == "`" { quote = character; current.append(" "); index += 1; continue }
if character == "-", next == "-" { lineComment = true; current.append(character); current.append(next!); index += 2; continue }
if character == "/", next == "*" { blockComment = true; current.append(character); current.append(next!); index += 2; continue }
if character == "'" || character == "\"" || character == "`" { quote = character; current.append(character); index += 1; continue }
if character == ";" {
if !current.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { statements.append(current) }
appendCurrentStatement()
current = ""; index += 1; continue
}
current.append(character)
index += 1
}
if !current.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { statements.append(current) }
appendCurrentStatement()
return statements
}

private static func sanitized(_ sql: String) -> String {
statements(in: sql).joined(separator: " ")
let characters = Array(sql)
var output = ""
var index = 0
var quote: Character?
var lineComment = false
var blockComment = false
while index < characters.count {
let character = characters[index]
let next = index + 1 < characters.count ? characters[index + 1] : nil
if lineComment {
if character == "\n" { lineComment = false; output.append(" ") }
index += 1
continue
}
if blockComment {
if character == "*", next == "/" { blockComment = false; index += 2; output.append(" ") }
else { index += 1 }
continue
}
if let activeQuote = quote {
if character == "\\", next != nil {
output.append(" ")
index += 2
continue
}
if character == activeQuote {
if next == activeQuote { index += 2 }
else { quote = nil; index += 1 }
} else {
index += 1
}
output.append(" ")
continue
}
if character == "-", next == "-" { lineComment = true; index += 2; output.append(" "); continue }
if character == "/", next == "*" { blockComment = true; index += 2; output.append(" "); continue }
if character == "'" || character == "\"" || character == "`" { quote = character; index += 1; output.append(" "); continue }
output.append(character)
index += 1
}
return output
}
}
53 changes: 53 additions & 0 deletions Sources/Lithe/Services/DatabaseRecoveryStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,34 @@ struct DatabaseAuditEntry: Codable, Equatable, Identifiable, Sendable {
let errorMessage: String?
}

enum DatabaseExecutionSource: String, Codable, Equatable, Sendable {
case sql
case redis
case nacos
}

enum DatabaseExecutionStatus: String, Codable, Equatable, Sendable {
case succeeded
case failed
case cancelled
}

struct DatabaseExecutionEvent: Codable, Equatable, Identifiable, Sendable {
let id: UUID
let profileID: UUID
let profileName: String
let source: DatabaseExecutionSource
let operation: String
let startedAt: Date
let durationMilliseconds: Int
let status: DatabaseExecutionStatus
let rowsReturned: Int?
let rowsAffected: UInt64?
let errorMessage: String?
}

final class DatabaseRecoveryStore: @unchecked Sendable {
private static let executionLogLock = NSRecursiveLock()
private let rootURL: URL
private let fileManager: FileManager
private let encoder: JSONEncoder
Expand Down Expand Up @@ -168,13 +195,39 @@ final class DatabaseRecoveryStore: @unchecked Sendable {
return entries.filter { $0.profileID == profileID }
}

func appendExecutionEvent(_ event: DatabaseExecutionEvent, maximumEntries: Int = 1_000) throws {
Self.executionLogLock.lock()
defer { Self.executionLogLock.unlock() }
try fileManager.createDirectory(at: rootURL, withIntermediateDirectories: true)
var entries = executionEvents().filter { $0.id != event.id }
entries.insert(event, at: 0)
try encoder.encode(Array(entries.prefix(maximumEntries))).write(to: executionURL, options: [.atomic])
}

func executionEvents(for profileID: UUID? = nil) -> [DatabaseExecutionEvent] {
Self.executionLogLock.lock()
defer { Self.executionLogLock.unlock() }
let entries = (try? decoder.decode([DatabaseExecutionEvent].self, from: Data(contentsOf: executionURL))) ?? []
guard let profileID else { return entries }
return entries.filter { $0.profileID == profileID }
}

func deleteExecutionEvents(for profileID: UUID) throws {
Self.executionLogLock.lock()
defer { Self.executionLogLock.unlock() }
let remaining = executionEvents().filter { $0.profileID != profileID }
try fileManager.createDirectory(at: rootURL, withIntermediateDirectories: true)
try encoder.encode(remaining).write(to: executionURL, options: [.atomic])
}

private func loadRecoveryPoints() throws -> [DatabaseRecoveryPoint] {
guard fileManager.fileExists(atPath: manifestURL.path) else { return [] }
return try decoder.decode([DatabaseRecoveryPoint].self, from: Data(contentsOf: manifestURL))
}

private var manifestURL: URL { rootURL.appendingPathComponent("recovery-points.json") }
private var auditURL: URL { rootURL.appendingPathComponent("audit.json") }
private var executionURL: URL { rootURL.appendingPathComponent("execution-events.json") }

private func validated(_ data: Data, for point: DatabaseRecoveryPoint) throws -> Data {
if !point.sha256.isEmpty && Self.sha256(data: data) != point.sha256 {
Expand Down
Loading
Loading