508 lines
23 KiB
Swift
508 lines
23 KiB
Swift
import Foundation
|
|
import SQLite3
|
|
|
|
struct Conversation: Identifiable {
|
|
let id: UUID
|
|
let title: String
|
|
}
|
|
|
|
struct WorkspaceSnippet: Identifiable {
|
|
enum Kind: String, CaseIterable, Identifiable {
|
|
case skill = "Skill"
|
|
case context = "Context"
|
|
case prompt = "Prompt"
|
|
case webClip = "Web Clip"
|
|
|
|
var id: Self { self }
|
|
}
|
|
|
|
let id: UUID
|
|
let kind: Kind
|
|
let title: String
|
|
let content: String
|
|
var notes = ""
|
|
var tags = ""
|
|
}
|
|
|
|
struct PromptVersion: Identifiable {
|
|
let id: String
|
|
let savedAt: String
|
|
let title: String
|
|
let content: String
|
|
let notes: String
|
|
let tags: String
|
|
}
|
|
|
|
final class Store {
|
|
private let db: OpaquePointer
|
|
private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
|
|
|
init(url: URL) throws {
|
|
var connection: OpaquePointer?
|
|
let status = sqlite3_open_v2(url.path, &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil)
|
|
guard status == SQLITE_OK, let connection else {
|
|
if let connection { sqlite3_close(connection) }
|
|
throw StudioError("Could not open the chat database.")
|
|
}
|
|
db = connection
|
|
sqlite3_busy_timeout(db, 3000)
|
|
try execute("PRAGMA foreign_keys = ON")
|
|
try execute("""
|
|
CREATE TABLE IF NOT EXISTS chats(
|
|
id TEXT PRIMARY KEY, title TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS knowledge_stacks(
|
|
id TEXT PRIMARY KEY REFERENCES chats(id) ON DELETE CASCADE
|
|
);
|
|
CREATE TABLE IF NOT EXISTS workspace_snippets(
|
|
id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS messages(
|
|
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
role TEXT NOT NULL, content TEXT NOT NULL, thinking TEXT NOT NULL, backend TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS messages_chat ON messages(chat);
|
|
CREATE TABLE IF NOT EXISTS documents(
|
|
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
|
title TEXT NOT NULL
|
|
);
|
|
CREATE VIRTUAL TABLE IF NOT EXISTS document_index USING fts5(
|
|
document UNINDEXED, content, tokenize='unicode61'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS document_vectors(
|
|
chunk INTEGER PRIMARY KEY, document TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
|
language TEXT NOT NULL, vector TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS document_vectors_document ON document_vectors(document, language);
|
|
CREATE TRIGGER IF NOT EXISTS documents_delete AFTER DELETE ON documents BEGIN
|
|
DELETE FROM document_index WHERE document=old.id;
|
|
END;
|
|
""")
|
|
try preparePromptLibrary()
|
|
try prepareWebSources()
|
|
}
|
|
|
|
private func prepareWebSources() throws {
|
|
try execute("""
|
|
CREATE TABLE IF NOT EXISTS message_web_sources (
|
|
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
|
sources TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS message_documents (
|
|
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
|
names TEXT NOT NULL
|
|
);
|
|
|
|
""")
|
|
}
|
|
|
|
private func preparePromptLibrary() throws {
|
|
try execute("""
|
|
CREATE TABLE IF NOT EXISTS prompt_metadata (
|
|
prompt TEXT PRIMARY KEY REFERENCES workspace_snippets(id) ON DELETE CASCADE,
|
|
notes TEXT NOT NULL, tags TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS prompt_versions (
|
|
id TEXT PRIMARY KEY, prompt TEXT NOT NULL REFERENCES workspace_snippets(id) ON DELETE CASCADE,
|
|
saved_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
title TEXT NOT NULL, content TEXT NOT NULL, notes TEXT NOT NULL, tags TEXT NOT NULL
|
|
);
|
|
""")
|
|
}
|
|
|
|
deinit { sqlite3_close(db) }
|
|
|
|
func conversations() throws -> [Conversation] {
|
|
try query("SELECT id,title FROM chats WHERE id NOT IN (SELECT id FROM knowledge_stacks) ORDER BY rowid DESC") {
|
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func searchConversations(_ term: String) throws -> [Conversation] {
|
|
let term = term.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !term.isEmpty else { return try conversations() }
|
|
return try query("""
|
|
SELECT c.id, c.title FROM chats c
|
|
WHERE c.id NOT IN (SELECT id FROM knowledge_stacks) AND (
|
|
instr(lower(c.title), lower(?)) > 0 OR EXISTS (
|
|
SELECT 1 FROM messages m WHERE m.chat=c.id AND instr(lower(m.content), lower(?)) > 0
|
|
)
|
|
)
|
|
ORDER BY c.rowid DESC
|
|
""", [term, term]) {
|
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func knowledgeStacks() throws -> [Conversation] {
|
|
try query("SELECT c.id,c.title FROM chats c JOIN knowledge_stacks s ON s.id=c.id ORDER BY c.rowid DESC") {
|
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func createKnowledgeStack(title: String) throws -> Conversation {
|
|
try execute("BEGIN IMMEDIATE")
|
|
do {
|
|
let entry = try create(title: title)
|
|
try mutate("INSERT INTO knowledge_stacks(id) VALUES(?)", [entry.id.uuidString])
|
|
try execute("COMMIT")
|
|
return entry
|
|
} catch {
|
|
try? execute("ROLLBACK")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func snippets() throws -> [WorkspaceSnippet] {
|
|
try query("SELECT s.id,s.kind,s.title,s.content,m.notes,m.tags FROM workspace_snippets s LEFT JOIN prompt_metadata m ON m.prompt=s.id ORDER BY s.rowid DESC") {
|
|
guard let kind = WorkspaceSnippet.Kind(rawValue: string($0, 1)) else {
|
|
throw StudioError("Invalid workspace resource.")
|
|
}
|
|
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
|
|
}
|
|
}
|
|
|
|
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) throws {
|
|
try mutate("""
|
|
INSERT INTO workspace_snippets(id,kind,title,content) VALUES(?,?,?,?)
|
|
ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, title=excluded.title, content=excluded.content
|
|
""", [id.uuidString, kind.rawValue, title, content])
|
|
}
|
|
|
|
func promptVersions(_ id: UUID) throws -> [PromptVersion] {
|
|
try query("SELECT id,saved_at,title,content,notes,tags FROM prompt_versions WHERE prompt=? ORDER BY rowid DESC", [id.uuidString]) {
|
|
PromptVersion(id: string($0, 0), savedAt: string($0, 1), title: string($0, 2),
|
|
content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
|
|
}
|
|
}
|
|
|
|
func savePrompt(id: UUID, title: String, content: String, notes: String, tags: String) throws {
|
|
try execute("BEGIN IMMEDIATE")
|
|
do {
|
|
try saveSnippet(id: id, kind: .prompt, title: title, content: content)
|
|
try mutate("""
|
|
INSERT INTO prompt_metadata(prompt,notes,tags) VALUES(?,?,?)
|
|
ON CONFLICT(prompt) DO UPDATE SET notes=excluded.notes, tags=excluded.tags
|
|
""", [id.uuidString, notes, tags])
|
|
try mutate("""
|
|
INSERT INTO prompt_versions(id,prompt,title,content,notes,tags) VALUES(?,?,?,?,?,?)
|
|
""", [UUID().uuidString, id.uuidString, title, content, notes, tags])
|
|
try execute("COMMIT")
|
|
} catch {
|
|
try? execute("ROLLBACK")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func deleteSnippet(_ id: UUID) throws {
|
|
try mutate("DELETE FROM workspace_snippets WHERE id=?", [id.uuidString])
|
|
}
|
|
|
|
func rename(_ id: UUID, title: String) throws {
|
|
try mutate("UPDATE chats SET title=? WHERE id=?", [title, id.uuidString])
|
|
}
|
|
|
|
func create(title: String) throws -> Conversation {
|
|
let chat = Conversation(id: UUID(), title: title)
|
|
try mutate("INSERT INTO chats(id,title) VALUES(?,?)", [chat.id.uuidString, title])
|
|
return chat
|
|
}
|
|
|
|
func delete(_ id: UUID) throws {
|
|
try mutate("DELETE FROM chats WHERE id=?", [id.uuidString])
|
|
}
|
|
|
|
func save(_ message: Message, in chat: UUID) throws {
|
|
func insertMessage() throws {
|
|
try mutate("INSERT INTO messages(id,chat,role,content,thinking,backend) VALUES(?,?,?,?,?,?)",
|
|
[message.id.uuidString, chat.uuidString, message.role.rawValue, message.content, message.thinking, message.backend])
|
|
}
|
|
|
|
guard !message.webSources.isEmpty || !message.documentNames.isEmpty else { try insertMessage(); return }
|
|
let encoder = JSONEncoder()
|
|
try execute("SAVEPOINT save_message_sources")
|
|
do {
|
|
try insertMessage()
|
|
if !message.webSources.isEmpty {
|
|
let sources = try encoder.encode(message.webSources)
|
|
try mutate("INSERT INTO message_web_sources(message,sources) VALUES(?,?)",
|
|
[message.id.uuidString, String(decoding: sources, as: UTF8.self)])
|
|
}
|
|
if !message.documentNames.isEmpty {
|
|
let names = try encoder.encode(message.documentNames)
|
|
try mutate("INSERT INTO message_documents(message,names) VALUES(?,?)",
|
|
[message.id.uuidString, String(decoding: names, as: UTF8.self)])
|
|
}
|
|
try execute("RELEASE save_message_sources")
|
|
} catch {
|
|
try? execute("ROLLBACK TO save_message_sources")
|
|
try? execute("RELEASE save_message_sources")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func messages(in chat: UUID) throws -> [Message] {
|
|
try query("""
|
|
SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names
|
|
FROM messages m
|
|
LEFT JOIN message_web_sources w ON w.message=m.id
|
|
LEFT JOIN message_documents d ON d.message=m.id
|
|
WHERE m.chat=? ORDER BY m.rowid
|
|
""", [chat.uuidString]) { row in
|
|
guard let role = Role(rawValue: string(row, 1)) else { throw StudioError("Invalid stored message role.") }
|
|
let decoder = JSONDecoder()
|
|
let sources = (try? decoder.decode([WebReplySource].self, from: Data(string(row, 5).utf8))) ?? []
|
|
let documents = (try? decoder.decode([String].self, from: Data(string(row, 6).utf8))) ?? []
|
|
return Message(id: try uuid(row, 0), role: role, content: string(row, 2),
|
|
thinking: string(row, 3), backend: string(row, 4), webSources: sources, documentNames: documents)
|
|
}
|
|
}
|
|
|
|
func memory(matching prompt: String, in chat: UUID, excluding: Set<UUID> = []) throws -> [String] {
|
|
let terms = Array(Set(prompt.lowercased().split { !$0.isLetter && !$0.isNumber }
|
|
.filter { $0.count >= 4 }.prefix(12).map(String.init))).sorted()
|
|
guard !terms.isEmpty else { return [] }
|
|
let termsSQL = Array(repeating: "instr(lower(content), ?) > 0", count: terms.count).joined(separator: " OR ")
|
|
let excluded = excluding.map(\.uuidString).sorted()
|
|
let exclusion = excluded.isEmpty ? "" :
|
|
" AND id NOT IN (" + Array(repeating: "?", count: excluded.count).joined(separator: ",") + ")"
|
|
return try query("""
|
|
SELECT substr(content,1,1200) FROM messages
|
|
WHERE chat=? AND role='user' AND (\(termsSQL))\(exclusion)
|
|
ORDER BY rowid DESC LIMIT 4
|
|
""", [chat.uuidString] + terms + excluded) { string($0, 0) }
|
|
}
|
|
|
|
func vectorCount(in owner: UUID) throws -> Int {
|
|
try query("""
|
|
SELECT count(*) FROM document_vectors v
|
|
JOIN documents d ON d.id=v.document WHERE d.chat=?
|
|
""", [owner.uuidString]) { Int(sqlite3_column_int64($0, 0)) }.first ?? 0
|
|
}
|
|
|
|
func documents(in chat: UUID) throws -> [LibraryDocument] {
|
|
try query("SELECT id,title FROM documents WHERE chat=? ORDER BY rowid DESC", [chat.uuidString]) {
|
|
LibraryDocument(id: try uuid($0, 0), title: string($0, 1))
|
|
}
|
|
}
|
|
|
|
func openingExcerpts(in chat: UUID) throws -> [DocumentExcerpt] {
|
|
try query("""
|
|
SELECT d.title, substr((SELECT i.content FROM document_index i WHERE i.document=d.id
|
|
ORDER BY i.rowid LIMIT 1),1,1600)
|
|
FROM documents d WHERE d.chat=? ORDER BY d.rowid DESC LIMIT 4
|
|
""", [chat.uuidString]) { DocumentExcerpt(title: string($0, 0), text: string($0, 1)) }
|
|
.filter { !$0.text.isEmpty }
|
|
}
|
|
|
|
func addDocument(title: String, chunks: [String], vectors: [DocumentVector?] = [], in chat: UUID) throws {
|
|
let id = UUID().uuidString
|
|
try execute("BEGIN IMMEDIATE")
|
|
do {
|
|
try mutate("INSERT INTO documents(id,chat,title) VALUES(?,?,?)", [id, chat.uuidString, title])
|
|
for (index, chunk) in chunks.enumerated() {
|
|
try mutate("INSERT INTO document_index(document,content) VALUES(?,?)", [id, chunk])
|
|
if vectors.indices.contains(index), let vector = vectors[index] {
|
|
let row = String(sqlite3_last_insert_rowid(db))
|
|
try mutate("INSERT INTO document_vectors(chunk,document,language,vector) VALUES(?,?,?,?)",
|
|
[row, id, vector.language, vector.encoded])
|
|
}
|
|
}
|
|
try execute("COMMIT")
|
|
} catch {
|
|
try? execute("ROLLBACK")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func deleteDocument(_ id: UUID, in chat: UUID) throws {
|
|
try mutate("DELETE FROM documents WHERE id=? AND chat=?", [id.uuidString, chat.uuidString])
|
|
}
|
|
|
|
func excerpts(matching prompt: String, in chat: UUID, vector: DocumentVector? = nil) throws -> [DocumentExcerpt] {
|
|
let match = LibraryImport.matchQuery(prompt)
|
|
let lexical: [DocumentExcerpt]
|
|
if match.isEmpty {
|
|
lexical = []
|
|
} else {
|
|
lexical = try query("""
|
|
SELECT d.title, substr(i.content,1,1600)
|
|
FROM document_index i JOIN documents d ON d.id=i.document
|
|
WHERE document_index MATCH ? AND d.chat=?
|
|
ORDER BY i.rank LIMIT 4
|
|
""", [match, chat.uuidString]) {
|
|
DocumentExcerpt(title: string($0, 0), text: string($0, 1))
|
|
}
|
|
}
|
|
guard let vector else { return lexical }
|
|
let candidates: [(score: Float, id: String)] = try query("""
|
|
SELECT v.chunk, v.vector FROM document_vectors v
|
|
JOIN documents d ON d.id=v.document WHERE d.chat=? AND v.language=?
|
|
ORDER BY v.chunk DESC LIMIT 3000
|
|
""", [chat.uuidString, vector.language]) { row in
|
|
(vector.similarity(to: string(row, 1)) ?? -1, string(row, 0))
|
|
}
|
|
var excerpts = Array(lexical.prefix(2))
|
|
for candidate in candidates.sorted(by: { $0.score > $1.score }).prefix(8) where candidate.score >= 0.35 {
|
|
let matches = try query("""
|
|
SELECT d.title, substr(i.content,1,1600)
|
|
FROM document_index i JOIN documents d ON d.id=i.document WHERE i.rowid=? AND d.chat=?
|
|
""", [candidate.id, chat.uuidString]) { row in
|
|
DocumentExcerpt(title: string(row, 0), text: string(row, 1))
|
|
}
|
|
if let excerpt = matches.first, !excerpts.contains(excerpt) { excerpts.append(excerpt) }
|
|
if excerpts.count == 4 { return excerpts }
|
|
}
|
|
for excerpt in lexical where excerpts.count < 4 && !excerpts.contains(excerpt) { excerpts.append(excerpt) }
|
|
return excerpts
|
|
}
|
|
|
|
static func isWorkspaceBackup(_ url: URL) -> Bool {
|
|
var input: OpaquePointer?
|
|
let result = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
|
|
defer { if let input { sqlite3_close(input) } }
|
|
guard result == SQLITE_OK, let input else { return false }
|
|
return hasWorkspaceSchema(input)
|
|
}
|
|
|
|
private static func hasWorkspaceSchema(_ input: OpaquePointer) -> Bool {
|
|
let sql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('chats','messages','documents','workspace_snippets','knowledge_stacks')"
|
|
var statement: OpaquePointer?
|
|
guard sqlite3_prepare_v2(input, sql, -1, &statement, nil) == SQLITE_OK, let statement else { return false }
|
|
defer { sqlite3_finalize(statement) }
|
|
return sqlite3_step(statement) == SQLITE_ROW && sqlite3_column_int(statement, 0) == 5
|
|
}
|
|
|
|
func importMstyChats(from url: URL) throws -> Int {
|
|
var input: OpaquePointer?
|
|
let opened = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
|
|
defer { if let input { sqlite3_close(input) } }
|
|
guard opened == SQLITE_OK, let input else { throw StudioError("Could not open the Msty database.") }
|
|
let sql = """
|
|
SELECT s.id, c.title, m.role, m.content
|
|
FROM conversationTexts c
|
|
JOIN conversationTextChatSplits s ON s.conversationId = c.id
|
|
JOIN conversationTextMessages m ON m.chatSplitId = s.id
|
|
WHERE m.role IN ('user','assistant') AND length(m.content) > 0
|
|
ORDER BY c.createdAt, s.createdAt, s.id, m.createdAt, m.rowid
|
|
"""
|
|
var statement: OpaquePointer?
|
|
guard sqlite3_prepare_v2(input, sql, -1, &statement, nil) == SQLITE_OK, let statement else {
|
|
throw StudioError("The database does not match the supported Msty Studio chat format.")
|
|
}
|
|
defer { sqlite3_finalize(statement) }
|
|
try execute("BEGIN IMMEDIATE")
|
|
var count = 0
|
|
do {
|
|
try execute("CREATE TABLE IF NOT EXISTS msty_imports (source_id TEXT PRIMARY KEY)")
|
|
var previous = ""
|
|
var destination: UUID?
|
|
while true {
|
|
let step = sqlite3_step(statement)
|
|
if step == SQLITE_DONE { break }
|
|
guard step == SQLITE_ROW else { throw StudioError("The Msty chat database could not be read.") }
|
|
let split = string(statement, 0)
|
|
if split != previous {
|
|
previous = split
|
|
destination = nil
|
|
let exists = try query("SELECT source_id FROM msty_imports WHERE source_id=?", [split]) { string($0, 0) }
|
|
if exists.isEmpty {
|
|
destination = try create(title: String(string(statement, 1).prefix(100))).id
|
|
try mutate("INSERT INTO msty_imports(source_id) VALUES(?)", [split])
|
|
count += 1
|
|
}
|
|
}
|
|
if let destination, let role = Role(rawValue: string(statement, 2)) {
|
|
try save(Message(role: role, content: string(statement, 3)), in: destination)
|
|
}
|
|
}
|
|
try execute("COMMIT")
|
|
return count
|
|
} catch {
|
|
try? execute("ROLLBACK")
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func exportWorkspace(to url: URL) throws {
|
|
guard !FileManager.default.fileExists(atPath: url.path) else {
|
|
throw StudioError("Choose a new filename for the workspace backup.")
|
|
}
|
|
try mutate("VACUUM INTO ?", [url.path])
|
|
}
|
|
|
|
func restoreWorkspace(from url: URL) throws {
|
|
var input: OpaquePointer?
|
|
let opened = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
|
|
guard opened == SQLITE_OK, let input else {
|
|
if let input { sqlite3_close(input) }
|
|
throw StudioError("The workspace backup could not be opened.")
|
|
}
|
|
defer { sqlite3_close(input) }
|
|
guard Self.hasWorkspaceSchema(input) else {
|
|
throw StudioError("The selected file is not an AI Studio workspace backup.")
|
|
}
|
|
var checkHandle: OpaquePointer?
|
|
guard sqlite3_prepare_v2(input, "PRAGMA quick_check", -1, &checkHandle, nil) == SQLITE_OK,
|
|
let integrity = checkHandle else { throw StudioError("Could not verify backup integrity.") }
|
|
let healthy = sqlite3_step(integrity) == SQLITE_ROW && string(integrity, 0) == "ok"
|
|
sqlite3_finalize(integrity)
|
|
guard healthy else { throw StudioError("The selected backup did not pass SQLite integrity checks.") }
|
|
guard let backup = sqlite3_backup_init(db, "main", input, "main") else { throw failure }
|
|
let step = sqlite3_backup_step(backup, -1)
|
|
let finish = sqlite3_backup_finish(backup)
|
|
guard step == SQLITE_DONE, finish == SQLITE_OK else { throw failure }
|
|
try preparePromptLibrary()
|
|
try prepareWebSources()
|
|
}
|
|
|
|
private func execute(_ sql: String) throws {
|
|
guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { throw failure }
|
|
}
|
|
|
|
private func mutate(_ sql: String, _ values: [String]) throws {
|
|
try statement(sql, values) {
|
|
guard sqlite3_step($0) == SQLITE_DONE else { throw failure }
|
|
}
|
|
}
|
|
|
|
private func query<T>(_ sql: String, _ values: [String] = [], map: (OpaquePointer) throws -> T) throws -> [T] {
|
|
try statement(sql, values) { statement in
|
|
var rows: [T] = []
|
|
while true {
|
|
switch sqlite3_step(statement) {
|
|
case SQLITE_ROW: rows.append(try map(statement))
|
|
case SQLITE_DONE: return rows
|
|
default: throw failure
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func statement<T>(_ sql: String, _ values: [String], run: (OpaquePointer) throws -> T) throws -> T {
|
|
var handle: OpaquePointer?
|
|
guard sqlite3_prepare_v2(db, sql, -1, &handle, nil) == SQLITE_OK, let handle else { throw failure }
|
|
defer { sqlite3_finalize(handle) }
|
|
for (index, value) in values.enumerated() {
|
|
let result = value.withCString {
|
|
sqlite3_bind_text(handle, Int32(index + 1), $0, Int32(value.utf8.count), transient)
|
|
}
|
|
guard result == SQLITE_OK else { throw failure }
|
|
}
|
|
return try run(handle)
|
|
}
|
|
|
|
private func uuid(_ row: OpaquePointer, _ column: Int32) throws -> UUID {
|
|
guard let id = UUID(uuidString: string(row, column)) else { throw StudioError("Invalid stored ID.") }
|
|
return id
|
|
}
|
|
|
|
private func string(_ row: OpaquePointer, _ column: Int32) -> String {
|
|
guard let text = sqlite3_column_text(row, column) else { return "" }
|
|
let count = Int(sqlite3_column_bytes(row, column))
|
|
return String(decoding: UnsafeBufferPointer(start: text, count: count), as: UTF8.self)
|
|
}
|
|
|
|
private var failure: StudioError { StudioError(String(cString: sqlite3_errmsg(db))) }
|
|
}
|