postgresql - Vapor 中的多个数据库

标签 postgresql fluent vapor

对于我的 Vapor 项目,我想主要使用一个 Postgres 数据库。但是,对于某些长时间运行的请求,我想使用同一数据库的单独只读克隆。

这方面的文档非常少。如何在现有默认数据库旁边添加另一个数据库连接?

static func configureDatabase(_ app: Application) throws {
    try app.databases.use(.postgres(url: "postgresql://user@localhost:5432/user"), as: .psql)
}

运行查询时,我如何告诉 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))

关于postgresql - Vapor 中的多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65386033/

相关文章:

postgresql - 将 CSV 上传到 Postgres 表时输入语法无效

sql - 使用像素检测正方形

postgresql - 从头开始为 Heroku 应用程序运行所有迁移

go - 在 go 中从外部包扩展一个流畅的 API

java - 是否有任何库可以将 SQL 查询表示为 Java 代码中的对象?

postgresql - 如何查询 "has no linked records in this table"

nhibernate - 非主键上的 Fluent Nhibernate HasMany

swift - 从 Vapor 2.0 中的请求对象获取 IP 地址?

swift - 安装 Vapor 用于 Swift 后端开发

swift - Vapor 4 无法使用 Put HTTP 请求更新可选父级