Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
winsmith Avatar asked Mar 20 '26 22:03

winsmith


1 Answers

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))
like image 163
Caleb Kleveter Avatar answered Mar 22 '26 16:03

Caleb Kleveter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!