Async db manager initializer and GRDBQuery #1668
-
My needs are met by the @Query Demo App except that my PlayerRepository equivalent has an asynchronous initializer which isn’t usable, as far as I can tell, as a DatabaseContext. It is asynchronous because it applies migrations from a I am a Swift app novice so there’s a reasonable chance I settled on anti-pattern 🙂 but what I have are basically these Xcode targets:
Each (relevant code:) private init(_ connection: any DatabaseWriter) async throws {
self.connection = connection
try await migrate()
}
private func migrate() async throws {
var migrator = DatabaseMigrator()
for m in coreMigrations { m.register(with: &migrator) }
for m in await ProviderRegistry.migrations { m.register(with: &migrator) }
try migrator.migrate(connection)
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Maybe the easy answer is to dispense with the registry notion and allow Barring a quick alternate solution for |
Beta Was this translation helpful? Give feedback.
-
Hello @Jason-Abbott, Is there something that prevents your app from waiting for the database to be migrated before registering the Here is a quick and dirty sample code: import GRDB
import GRDBQuery
struct LoaderView: View {
// Initially nil, then not nil when the database is ready
@State var databaseContext: DatabaseContext?
var body: some View {
Group {
if let databaseContext {
MyView().databaseContext(databaseContext)
} else {
ProgressView()
}
}
.task {
do {
let dbQueue = try DatabaseQueue()
try await Task.sleep(for: .seconds(1)) // migrate
databaseContext = DatabaseContext.readWrite { dbQueue }
} catch {
databaseContext = DatabaseContext.readWrite { throw error }
}
}
}
}
struct MyView: View {
@Environment(\.databaseContext) var databaseContext
var body: some View {
let value = try! databaseContext.reader.read { db in "Connected!" }
Text(value)
}
}
#Preview {
LoaderView()
} |
Beta Was this translation helpful? Give feedback.
-
@groue I think that should work perfectly. Thank you! |
Beta Was this translation helpful? Give feedback.
Hello @Jason-Abbott,
Is there something that prevents your app from waiting for the database to be migrated before registering the
DatabaseContext
?Here is a quick and dirty sample code: