*DB instance for the lifetime of the connection.
The Plugin interface
Every plugin must satisfy thePlugin interface defined in gorm.io/gorm:
| Method | Description |
|---|---|
Name() string | Returns a unique identifier for the plugin. Used as the key in db.Plugins. |
Initialize(*DB) error | Called once when the plugin is registered. Receives the fully initialized *DB instance. Return a non-nil error to abort registration. |
Registering a plugin
Calldb.Use(plugin) to register a plugin:
plugin.Initialize(db) and then stores the plugin in db.Plugins under the name returned by plugin.Name(). If a plugin with the same name is already registered, db.Use returns gorm.ErrRegistered and does not call Initialize again.
Accessing registered plugins
Plugins are stored indb.Plugins, which is a map[string]Plugin:
Writing a custom plugin
A plugin’sInitialize method receives the *DB instance and can:
- Register or replace callbacks
- Modify configuration fields on
db.Config - Store state for later retrieval via
db.Plugins
CREATE statement:
Passing state from a plugin
If your plugin needs to share data with its callbacks at runtime, store it on the plugin struct and capture it via a closure or method value:Reporting errors from Initialize
Return a non-nil error fromInitialize to prevent the plugin from being registered and to surface the error to the caller:
Built-in plugins
GORM ships two official plugins in thegorm.io/plugin module:
Database Resolver
Database Resolver
The Database Resolver plugin (
gorm.io/plugin/dbresolver) adds support for multiple database connections with automatic read/write splitting.- Route writes to a primary database and reads to one or more replicas
- Define multiple sources and replicas per model or table name
- Supports connection pool configuration per resolver
Prometheus
Prometheus
The Prometheus plugin (
gorm.io/plugin/prometheus) exposes database metrics — connection pool stats, query counts, and latency histograms — in Prometheus format.Plugin naming convention
Choose plugin names that are:- Lowercase and hyphenated:
"db-resolver","my-plugin" - Namespaced to your package or organization:
"myorg-audit-log" - Stable: the name is used as the map key in
db.Plugins, so renaming a plugin is a breaking change for any code that looks it up by name
"gorm:" prefix (e.g., "gorm:create"). Avoid this prefix in third-party plugins.