How to ensure that all the database operations complete before database shuts down in Fluent?

94 views Asked by At

Fluent operations work in an Asynchronous way and returns the EventLoopFuture, when an operation gets completed. So, if the code uses the database shutdown call, is there a way to make sure that all the initiated database operations gets completed, before the database shuts down?

For example, the below code compiles well but does not ensure the insertion of the building object in the database (Building is a Fluent Model.). On the other hand, if I use the wait function with the create function, the operation gets synchronous, but ensures the creation a building-record in database.

func testExample() throws {
        let dbs = Databases(threadPool: .init(numberOfThreads: System.coreCount), on: MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount))
        try dbs.use(.postgres(url: "<CONNECTIONSTRING>"), as: .psql)
        
        let db = dbs.database(.psql, logger: Logger(label: "Test"), on: dbs.eventLoopGroup.next())!
    
        let building = Building(id: UUID("b0c8f088-df0a-4253-98e4-eb8943c054d4"), buildingName: "Building4")
        building.create(on: db)
        // This is synchronous and would create a record in the database.
        //try building.create(on: db).wait()
        
        dbs.shutdown()
        try dbs.threadPool.syncShutdownGracefully()
        try dbs.eventLoopGroup.syncShutdownGracefully()
    }

Is there a way to make dbs.shutdown() wait until the create operation (or any initiated database operation) completes?

1

There are 1 answers

1
0xTim On

The problem you're hitting is that you're trying to make an asynchronous operation work in a synchronous function. In short - you can't.

You either need to call wait() as you show in your comments to make the function synchronous or you need to make the function asynchronous and return a future. There's no other way around it.

But to answer your other question if you want call shutdown after the create function you need to wait for the future to return using either map or flatMap