53 lines
1.5 KiB
Swift
53 lines
1.5 KiB
Swift
import GRDB
|
|
|
|
struct User: Codable, FetchableRecord, PersistableRecord {
|
|
var userId: String
|
|
var publicKey: String
|
|
var isSpammer: Bool
|
|
}
|
|
|
|
final class Database: Sendable {
|
|
|
|
private var dbWriter: any DatabaseWriter
|
|
|
|
init(_ dbWriter: any GRDB.DatabaseWriter) throws {
|
|
self.dbWriter = dbWriter
|
|
try migrator.migrate(dbWriter)
|
|
}
|
|
|
|
let dbQueue = try DatabaseQueue(path: "./db.sqlite")
|
|
|
|
let db = try Connection("./db.sqlite")
|
|
|
|
#if DEBUG
|
|
// Speed up development by nuking the database when migrations change
|
|
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations#The-eraseDatabaseOnSchemaChange-Option>
|
|
migrator.eraseDatabaseOnSchemaChange = true
|
|
#endif
|
|
private var migrator: DatabaseMigrator {
|
|
var migrator = DatabaseMigrator()
|
|
migrator.registerMigration("v1") { db in
|
|
try db.create(table: "users", { t in
|
|
t.primaryKey("userId", .text).NotNull()
|
|
t.column("publicKey", .text).NotNull()
|
|
t.column("isSpammer", .bool)
|
|
})
|
|
return migrator
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Database {
|
|
static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
|
var config = base
|
|
return config
|
|
}
|
|
}
|
|
|
|
extension Database {
|
|
func saveUser(_ userId: String, _ publicKey: String, _ isSpammer: Bool) throws {
|
|
try dbWriter.write { db in
|
|
try User.init(userId: userId, publicKey: publicKey, isSpammer: isSpammer).insert(db)
|
|
}
|
|
}
|
|
}
|