DBResolver adds multiple databases support to GORM, the following features are supported:
- Multiple sources, replicas
- Read/Write Splitting
- Automatic connection switching based on the working table/struct
- Manual connection switching
- Sources/Replicas load balancing
- Works for RAW SQL
- Transaction
https://github.com/go-gorm/dbresolver
Usage
import ( |
Automatic connection switching
DBResolver will automatically switch connection based on the working table/struct
For RAW SQL, DBResolver will extract the table name from the SQL to match the resolver, and will use sources
unless the SQL begins with SELECT
(excepts SELECT... FOR UPDATE
), for example:
// `User` Resolver Examples |
Read/Write Splitting
Read/Write splitting with DBResolver based on the current used GORM callbacks.
For Query
, Row
callback, will use replicas
unless Write
mode specified
For Raw
callback, statements are considered read-only and will use replicas
if the SQL starts with SELECT
Manual connection switching
// Use Write Mode: read user from sources `db1` |
Transaction
When using transaction, DBResolver will keep using the transaction and won’t switch to sources/replicas based on configuration
But you can specifies which DB to use before starting a transaction, for example:
// Start transaction based on default replicas db |
Load Balancing
GORM supports load balancing sources/replicas based on policy, the policy should be a struct implements following interface:
type Policy interface { |
Currently only the RandomPolicy
implemented and it is the default option if no other policy specified.
Connection Pool
db.Use( |