2024-06-19 15:15:27 +00:00
|
|
|
import Combine
|
|
|
|
import Foundation
|
|
|
|
import GRDB
|
|
|
|
import SwiftUI
|
|
|
|
|
|
|
|
// MARK: - Models protocol
|
|
|
|
typealias DBStorable = Codable & FetchableRecord & Identifiable & PersistableRecord & TableRecord
|
|
|
|
|
|
|
|
// MARK: - Database init
|
|
|
|
final class Database {
|
|
|
|
static let shared = Database()
|
2024-09-03 15:13:58 +00:00
|
|
|
let dbQueue: DatabaseQueue
|
2024-10-04 15:58:04 +00:00
|
|
|
private var dbPath: String
|
2024-06-19 15:15:27 +00:00
|
|
|
|
|
|
|
private init() {
|
|
|
|
do {
|
|
|
|
// Create db folder if not exists
|
|
|
|
let fileManager = FileManager.default
|
|
|
|
let appSupportURL = try fileManager.url(
|
|
|
|
for: .applicationSupportDirectory, in: .userDomainMask,
|
|
|
|
appropriateFor: nil, create: true
|
|
|
|
)
|
|
|
|
let directoryURL = appSupportURL.appendingPathComponent("ConversationsClassic", isDirectory: true)
|
|
|
|
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
|
|
|
|
|
|
|
// Open or create the database
|
|
|
|
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
2024-09-03 15:13:58 +00:00
|
|
|
dbQueue = try DatabaseQueue(path: databaseURL.path, configuration: Database.config)
|
2024-10-04 15:58:04 +00:00
|
|
|
dbPath = databaseURL.path
|
2024-06-19 15:15:27 +00:00
|
|
|
|
|
|
|
// Some debug info
|
|
|
|
#if DEBUG
|
|
|
|
print("Database path: \(databaseURL.path)")
|
|
|
|
#endif
|
|
|
|
|
|
|
|
// Apply migrations
|
2024-09-03 15:13:58 +00:00
|
|
|
try Database.migrator.migrate(dbQueue)
|
2024-06-19 15:15:27 +00:00
|
|
|
} catch {
|
|
|
|
fatalError("Database initialization failed: \(error)")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Config
|
|
|
|
private extension Database {
|
|
|
|
static let config: Configuration = {
|
|
|
|
var config = Configuration()
|
|
|
|
#if DEBUG
|
|
|
|
// verbose and debugging in DEBUG builds only.
|
|
|
|
config.publicStatementArguments = true
|
|
|
|
config.prepareDatabase { db in
|
2024-07-14 19:22:46 +00:00
|
|
|
db.trace { print("SQL> \($0)\n") }
|
2024-06-19 15:15:27 +00:00
|
|
|
}
|
|
|
|
#endif
|
|
|
|
return config
|
|
|
|
}()
|
|
|
|
}
|
2024-10-04 15:58:04 +00:00
|
|
|
|
|
|
|
// MARK: - flush all data for debug
|
|
|
|
#if DEBUG
|
|
|
|
extension Database {
|
|
|
|
func flushAllData() {
|
|
|
|
// nullable queue and remove db file
|
|
|
|
do {
|
|
|
|
try FileManager.default.removeItem(atPath: dbPath)
|
|
|
|
} catch {
|
|
|
|
print("Error: \(error)")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|