-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathSchema.swift
68 lines (63 loc) · 1.84 KB
/
Schema.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import Dependencies
import Foundation
import GRDB
import Sharing
struct Player: Equatable {
var id: Int64?
var name = ""
var isInjured = false
}
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
static let databaseTableName = "players"
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension DatabaseWriter {
func migrate() throws {
var migrator = DatabaseMigrator()
defer {
try! migrator.migrate(self)
}
#if DEBUG
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("Create 'players' table") { db in
try db.create(table: Player.databaseTableName) { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("isInjured", .boolean).defaults(to: false).notNull()
}
#if targetEnvironment(simulator)
if !isTesting {
try Player.deleteAll(db)
for (index, name) in ["Blob", "Blob Jr.", "Blob Sr.", "Blob Esq."].enumerated() {
_ = try Player(name: name, isInjured: index.isMultiple(of: 2))
.inserted(db)
}
}
#endif
}
}
}
extension DatabaseWriter where Self == DatabaseQueue {
static var appDatabase: Self {
var configuration = Configuration()
configuration.prepareDatabase { db in
db.trace { event in
print(event)
}
}
let databaseQueue: DatabaseQueue
@Dependency(\.context) var context
if context == .live {
let path = URL.documentsDirectory.appending(component: "db.sqlite").path()
print("open", path)
databaseQueue = try! DatabaseQueue(path: path, configuration: configuration)
} else {
databaseQueue = try! DatabaseQueue(configuration: configuration)
}
try! databaseQueue.migrate()
return databaseQueue
}
}