是否可以在独立脚本中使用 Vapor 3 Postgres Fluent?

Is is possible to use Vapor 3 Postgres Fluent in a standalone script?

我正在试验一个独立脚本,该脚本将使用 Vapor 和 Fluent 查询 Postgres 数据库。在普通的 Vapor API 应用程序中,这只需通过以下方式完成:

router.get("products") { request in
    return Product.query(on: request).all()
}

但是,在独立脚本中,由于没有 "request",我不知道用什么替换 "request" 或 DatabaseConnectable。这是我卡住的地方:

import Fluent
import FluentPostgreSQL

let databaseConfig = PostgreSQLDatabaseConfig(hostname: "localhost",
                                              username: "test",
                                              database: "test",
                                              password: nil)

let database = PostgreSQLDatabase(config: databaseConfig)

let foo = Product.query(on: <??WhatDoIPutHere??>)

我尝试创建一个符合 DatabaseConnectable 的对象,但无法弄清楚如何正确地使该对象符合。

您需要创建一个事件循环组才能发出数据库请求。 SwiftNIO 的 MultiThreadedEventLoopGroup 对此有好处:

let worker = MultiThreadedEventLoopGroup(numberOfThreads: 2)

您可以根据需要更改使用的线程数。

现在您可以使用该工作人员创建到数据库的连接:

let conn = try database.newConnection(on: worker)

连接在未来,因此您可以 map 它并在您的查询中传递连接:

conn.flatMap { connection in
    return Product.query(on: connection)...
}

确保在使用 shutdownGracefully(queue:_:)

完成后关闭您的工作器

上面写的很好,只是说明它是多么简单,等你明白了,我已经为此做了一个小测试例子。希望对你有帮助。

final class StandAloneTest : XCTestCase{
    var expectation : XCTestExpectation?
    func testDbConnection() -> Void {
        expectation = XCTestExpectation(description: "Wating")
        let databaseConfig = PostgreSQLDatabaseConfig(hostname: "your.hostname.here",
                                                      username: "username",
                                                      database: "databasename",
                                                      password: "topsecretpassword")
        let database = PostgreSQLDatabase(config: databaseConfig)
        let worker = MultiThreadedEventLoopGroup(numberOfThreads: 2)
        let conn = database.newConnection(on: worker)

        let sc = SomeClass( a:1, b:2, c:3  ) //etc

        //get all the tupples for this Class type in the base
        let futureTest = conn.flatMap { connection in
              return SomeClass.query(on: connection).all()
        }
        //or save a new tupple by uncommenting the below
        //let futureTest = conn.flatMap { connection in
        //    return someClassInstantiated.save(on: connection)
        //}

        //lets just wait for the future to test it 
        //(PS: this blocks the thread and should not be used in production)
        do{
            let test = try futureTest.wait()
            expectation?.fulfill()
            worker.syncShutdownGracefully()
            print( test )
        }catch{
            expectation?.fulfill()
            print(error)
        }
    }
}

//Declare the class you want to test here using the Fluent stuff in some extension