Full-featured ORM library for Golang with associations, hooks, transactions, migrations, and developer-friendly chainable API
npx @tessl/cli install tessl/golang-gorm-io--gorm@1.31.0GORM is a full-featured Object-Relational Mapping (ORM) library for Go, providing a developer-friendly API for database operations with support for associations, hooks, transactions, migrations, and advanced query building.
go get -u gorm.io/gormimport (
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
)Database drivers are separate packages:
import (
"gorm.io/driver/sqlite"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
)package main
import (
"gorm.io/gorm"
"gorm.io/driver/sqlite"
)
// Define model
type User struct {
gorm.Model
Name string
Email string `gorm:"uniqueIndex"`
Age int
}
func main() {
// Open database connection
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Auto migrate schema
db.AutoMigrate(&User{})
// Create
db.Create(&User{Name: "Alice", Email: "alice@example.com", Age: 25})
// Read
var user User
db.First(&user, "email = ?", "alice@example.com")
// Update
db.Model(&user).Update("Age", 26)
// Delete
db.Delete(&user)
}GORM follows a chainable API design where most methods return *gorm.DB, allowing you to build complex queries through method chaining. The key components are:
Open a database connection with a dialector and optional configuration.
func Open(dialector Dialector, opts ...Option) (*DB, error)Insert new records into the database with support for batch operations.
// Create single record
func (db *DB) Create(value interface{}) *DB
// Create records in batches
func (db *DB) CreateInBatches(value interface{}, batchSize int) *DB
// Save all fields (insert or update)
func (db *DB) Save(value interface{}) *DBRetrieve records with flexible query conditions.
// Find first record ordered by primary key
func (db *DB) First(dest interface{}, conds ...interface{}) *DB
// Find all matching records
func (db *DB) Find(dest interface{}, conds ...interface{}) *DB
// Find last record ordered by primary key
func (db *DB) Last(dest interface{}, conds ...interface{}) *DB
// Find one record without ordering
func (db *DB) Take(dest interface{}, conds ...interface{}) *DBUpdate records with or without lifecycle hooks.
// Update single column with hooks
func (db *DB) Update(column string, value interface{}) *DB
// Update multiple columns with hooks
func (db *DB) Updates(values interface{}) *DB
// Update single column without hooks
func (db *DB) UpdateColumn(column string, value interface{}) *DB
// Update multiple columns without hooks
func (db *DB) UpdateColumns(values interface{}) *DBDelete records with soft delete support.
// Delete records (soft delete if DeletedAt field exists)
func (db *DB) Delete(value interface{}, conds ...interface{}) *DB
// Include soft deleted records in queries
func (db *DB) Unscoped() *DBBuild complex queries with chainable methods.
// Specify model for operation
func (db *DB) Model(value interface{}) *DB
// Add WHERE conditions
func (db *DB) Where(query interface{}, args ...interface{}) *DB
// Add OR conditions
func (db *DB) Or(query interface{}, args ...interface{}) *DB
// Specify fields to select
func (db *DB) Select(query interface{}, args ...interface{}) *DB
// Add ORDER BY clause
func (db *DB) Order(value interface{}) *DB
// Add LIMIT clause
func (db *DB) Limit(limit int) *DB
// Add OFFSET clause
func (db *DB) Offset(offset int) *DB
// Add JOIN clause
func (db *DB) Joins(query string, args ...interface{}) *DBManage relationships between models.
// Get association manager for a relationship
func (db *DB) Association(column string) *Association
// Association methods
func (association *Association) Find(out interface{}, conds ...interface{}) error
func (association *Association) Append(values ...interface{}) error
func (association *Association) Replace(values ...interface{}) error
func (association *Association) Delete(values ...interface{}) error
func (association *Association) Clear() error
func (association *Association) Count() (int64, error)Execute operations within database transactions.
// Execute function in a transaction
func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) error
// Manual transaction control
func (db *DB) Begin(opts ...*sql.TxOptions) *DB
func (db *DB) Commit() *DB
func (db *DB) Rollback() *DB
// Savepoints
func (db *DB) SavePoint(name string) *DB
func (db *DB) RollbackTo(name string) *DBAutomatically migrate database schema from Go structs.
// Auto migrate schema
func (db *DB) AutoMigrate(dst ...interface{}) error
// Get migrator for manual migrations
func (db *DB) Migrator() MigratorImplement interfaces to hook into CRUD lifecycle events.
// Hook interfaces from gorm.io/gorm/callbacks
type BeforeCreateInterface interface {
BeforeCreate(*gorm.DB) error
}
type AfterCreateInterface interface {
AfterCreate(*gorm.DB) error
}
type BeforeUpdateInterface interface {
BeforeUpdate(*gorm.DB) error
}
type AfterUpdateInterface interface {
AfterUpdate(*gorm.DB) error
}
type BeforeDeleteInterface interface {
BeforeDelete(*gorm.DB) error
}
type AfterDeleteInterface interface {
AfterDelete(*gorm.DB) error
}Parse and inspect model schemas at runtime.
import "gorm.io/gorm/schema"
// Parse schema from model
func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error)
// Schema represents parsed model structure
type Schema struct {
Name string
ModelType reflect.Type
Table string
PrimaryFields []*Field
Fields []*Field
Relationships Relationships
// ... additional fields
}Build SQL clauses programmatically for advanced queries.
import "gorm.io/gorm/clause"
// Add custom clauses to query
func (db *DB) Clauses(conds ...clause.Expression) *DB
// Common clause types
type Where struct {
Exprs []Expression
}
type Select struct {
Distinct bool
Columns []Column
}
type Join struct {
Type JoinType
Table Table
ON Where
}Configure logging for database operations.
import "gorm.io/gorm/logger"
// Logger interface
type Interface interface {
LogMode(LogLevel) Interface
Info(context.Context, string, ...interface{})
Warn(context.Context, string, ...interface{})
Error(context.Context, string, ...interface{})
Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)
}
// Create new logger
func New(writer Writer, config Config) Interface// DB is the primary database handle
type DB struct {
Error error
RowsAffected int64
Statement *Statement
// ... internal fields
}
// Config holds database configuration options
type Config struct {
SkipDefaultTransaction bool
DefaultTransactionTimeout time.Duration
DefaultContextTimeout time.Duration
NamingStrategy schema.Namer
FullSaveAssociations bool
Logger logger.Interface
NowFunc func() time.Time
DryRun bool
PrepareStmt bool
PrepareStmtMaxSize int
PrepareStmtTTL time.Duration
DisableAutomaticPing bool
DisableForeignKeyConstraintWhenMigrating bool
IgnoreRelationshipsWhenMigrating bool
DisableNestedTransaction bool
AllowGlobalUpdate bool
QueryFields bool
CreateBatchSize int
TranslateError bool
PropagateUnscoped bool
ClauseBuilders map[string]clause.ClauseBuilder
ConnPool ConnPool
Dialector Dialector
Plugins map[string]Plugin
}
// Session configuration for customizing operations
type Session struct {
DryRun bool
PrepareStmt bool
NewDB bool
Initialized bool
SkipHooks bool
SkipDefaultTransaction bool
DisableNestedTransaction bool
AllowGlobalUpdate bool
FullSaveAssociations bool
PropagateUnscoped bool
QueryFields bool
Context context.Context
Logger logger.Interface
NowFunc func() time.Time
CreateBatchSize int
}
// Model is the base model with common fields
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt DeletedAt `gorm:"index"`
}
// DeletedAt is a nullable time field for soft delete
type DeletedAt sql.NullTimevar (
ErrRecordNotFound error // Record not found
ErrInvalidTransaction error // Invalid transaction
ErrNotImplemented error // Feature not implemented
ErrMissingWhereClause error // WHERE clause required but missing
ErrUnsupportedRelation error // Unsupported relationship type
ErrPrimaryKeyRequired error // Primary key required
ErrModelValueRequired error // Model value required
ErrModelAccessibleFieldsRequired error // Model accessible fields required
ErrSubQueryRequired error // Sub query required
ErrInvalidData error // Invalid data type
ErrUnsupportedDriver error // Unsupported database driver
ErrRegistered error // Already registered
ErrInvalidField error // Invalid field
ErrEmptySlice error // Empty slice provided
ErrDryRunModeUnsupported error // Dry run mode not supported
ErrInvalidDB error // Invalid database handle
ErrInvalidValue error // Invalid value
ErrInvalidValueOfLength error // Invalid association values, length doesn't match
ErrPreloadNotAllowed error // Preload is not allowed when count is used
ErrDuplicatedKey error // Duplicated key constraint violation
ErrForeignKeyViolated error // Foreign key constraint violation
ErrCheckConstraintViolated error // Check constraint violation
)// Create new session with custom configuration
func (db *DB) Session(config *Session) *DB
// Set context for operation
func (db *DB) WithContext(ctx context.Context) *DB
// Enable debug mode (logs SQL)
func (db *DB) Debug() *DB
// Set/Get session settings
func (db *DB) Set(key string, value interface{}) *DB
func (db *DB) Get(key string) (interface{}, bool)
// Set/Get instance-specific settings (stored in context)
func (db *DB) InstanceSet(key string, value interface{}) *DB
func (db *DB) InstanceGet(key string) (interface{}, bool)// Execute raw SQL query
func (db *DB) Raw(sql string, values ...interface{}) *DB
// Execute raw SQL statement
func (db *DB) Exec(sql string, values ...interface{}) *DB
// Get sql.Row from query
func (db *DB) Row() *sql.Row
// Get sql.Rows from query
func (db *DB) Rows() (*sql.Rows, error)
// Scan results into struct
func (db *DB) Scan(dest interface{}) *DB
// Scan sql.Rows into struct
func (db *DB) ScanRows(rows *sql.Rows, dest interface{}) errorKey interfaces for extending GORM functionality.
// Dialector defines database driver interface
type Dialector interface {
Name() string
Initialize(*DB) error
Migrator(db *DB) Migrator
DataTypeOf(*schema.Field) string
DefaultValueOf(*schema.Field) clause.Expression
BindVarTo(writer clause.Writer, stmt *Statement, v interface{})
QuoteTo(clause.Writer, string)
Explain(sql string, vars ...interface{}) string
}
// Plugin interface for GORM plugins
type Plugin interface {
Name() string
Initialize(*DB) error
}
// ConnPool defines database connection pool interface
type ConnPool interface {
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}
// Valuer interface for custom value types
type Valuer interface {
GormValue(context.Context, *DB) clause.Expr
}
// ErrorTranslator for translating database-specific errors
type ErrorTranslator interface {
Translate(err error) error
}
// ParamsFilter for filtering SQL parameters
type ParamsFilter interface {
ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{})
}
// GetDBConnector for getting underlying sql.DB connection
type GetDBConnector interface {
GetDBConn() (*sql.DB, error)
}
// Rows interface for scanning query results
type Rows interface {
Columns() ([]string, error)
ColumnTypes() ([]*sql.ColumnType, error)
Next() bool
Scan(dest ...interface{}) error
Err() error
Close() error
}
// SavePointerDialectorInterface for savepoint support
type SavePointerDialectorInterface interface {
SavePoint(tx *DB, name string) error
RollbackTo(tx *DB, name string) error
}
// TxBeginner for beginning transactions
type TxBeginner interface {
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}
// ConnPoolBeginner for connection pool transactions
type ConnPoolBeginner interface {
BeginTx(ctx context.Context, opts *sql.TxOptions) (ConnPool, error)
}
// TxCommitter for committing/rolling back transactions
type TxCommitter interface {
Commit() error
Rollback() error
}
// Tx represents a database transaction
type Tx interface {
ConnPool
TxCommitter
StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt
}// Get underlying sql.DB
func (db *DB) DB() (*sql.DB, error)
// Convert query to SQL string without executing
func (db *DB) ToSQL(queryFn func(tx *DB) *DB) string
// Register plugin
func (db *DB) Use(plugin Plugin) error
// Setup custom join table for many2many relationship
func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error