我正在尝试使用Vapor和Fluent查询Postgres数据库的独立脚本。在普通的Vapor API应用程序中,这可以通过以下方式完成:
router.get("products") { request in
return Product.query(on: request).all()
}
但是,在一个独立的脚本中,由于没有“请求”,我无法用什么来代替“请求”或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)
您可以根据需要更改使用的线程数。
现在,您可以使用该worker创建与数据库的连接:
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