【问题标题】:Multiple Databases in VaporVapor 中的多个数据库
【发布时间】:2021-03-30 19:39:36
【问题描述】:

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

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

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

在运行查询时,我如何告诉 Fluent 在第二个数据库上运行这些查询?

【问题讨论】:

    标签: postgresql fluent vapor


    【解决方案1】:

    多个数据库的魔力在于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 和 Fluent 版本 4.x
    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 2021-12-06
    • 2019-05-21
    • 2019-04-22
    • 1970-01-01
    • 2021-12-14
    • 2022-08-11
    • 1970-01-01
    相关资源
    最近更新 更多