winsmith
winsmith

Reputation: 21572

Multiple Databases in Vapor

For my Vapor project, I want to mostly use a single Postgres database. However, for certain long-running requests, I want to use a separate, read-only clone of the same database.

The documentation for this is very sparse. How do I add another database connection next to the existing default database?

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

When running queries, how do I tell Fluent to run those queries on the second database?

Upvotes: 3

Views: 756

Answers (1)

Caleb Kleveter
Caleb Kleveter

Reputation: 11494

The magic of multiple databases lies with the DatabaseID. You can define a new instance of DatabaseID, and register a connection with it.

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)
}

Then, when you want to run a query, instead of using the request.db database, use the .db(_:) method and pass in your identifier:

User.query(on: request.db(.readOnly))

Upvotes: 9

Related Questions