Vapor 中的多个数据库
Multiple Databases in Vapor
对于我的 Vapor 项目,我想主要使用一个 Postgres 数据库。但是,对于某些长 运行ning 请求,我想使用同一数据库的单独的只读克隆。
这方面的文档非常少。如何在现有默认数据库旁边添加另一个数据库连接?
static func configureDatabase(_ app: Application) throws {
try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/user"), as: .psql)
}
当 运行ning 查询时,我如何告诉 Fluent 运行 第二个数据库上的那些查询?
多数据库的魔力在于DatabaseID
。您可以定义 DatabaseID
的新实例,并向其注册连接。
extension DatabaseID {
static let readOnly = DatabaseID("readOnly")
}
static func configureDatabase(_ app: Application) throws {
try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/user"), as: .psql)
try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/read_only"), as: .readOnly)
}
然后,当您想 运行 查询时,不要使用 request.db
数据库,而是使用 .db(_:)
方法并传入您的标识符:
User.query(on: request.db(.readOnly))
对于我的 Vapor 项目,我想主要使用一个 Postgres 数据库。但是,对于某些长 运行ning 请求,我想使用同一数据库的单独的只读克隆。
这方面的文档非常少。如何在现有默认数据库旁边添加另一个数据库连接?
static func configureDatabase(_ app: Application) throws {
try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/user"), as: .psql)
}
当 运行ning 查询时,我如何告诉 Fluent 运行 第二个数据库上的那些查询?
多数据库的魔力在于DatabaseID
。您可以定义 DatabaseID
的新实例,并向其注册连接。
extension DatabaseID {
static let readOnly = DatabaseID("readOnly")
}
static func configureDatabase(_ app: Application) throws {
try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/user"), as: .psql)
try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/read_only"), as: .readOnly)
}
然后,当您想 运行 查询时,不要使用 request.db
数据库,而是使用 .db(_:)
方法并传入您的标识符:
User.query(on: request.db(.readOnly))