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

时间:2018-12-14 21:14:55

标签: swift vapor

我正在尝试一个独立的脚本,该脚本将使用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的对象,但无法弄清楚如何正确地使该对象符合。

2 个答案:

答案 0 :(得分:1)

您将需要创建一个事件循环组才能发出数据库请求。 SwiftNIO的return对此非常有用:

MultiThreadedEventLoopGroup

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

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

let worker = MultiThreadedEventLoopGroup(numberOfThreads: 2)

以后会建立连接,因此您可以let conn = try database.newConnection(on: worker) 连接并在查询中传递连接:

map

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

完成工作后将其关闭

答案 1 :(得分:0)

上面的内容非常好,但是请澄清一下它的简单程度,当您获得它时,我为此做了一个小型测试示例。希望对您有帮助。

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