gormkit
gormkit is a small set of composable helpers for GORM v2:
- explicit database lifecycle management with an optional process default;
- context-propagated required and nested transactions;
- an error-returning generic repository for pointer-to-struct models;
- safe ordering, association, query, and forced-zero-value update scopes;
- opt-in tenant isolation through a model field type;
- an optional configurable Unix timestamp plugin.
The module currently targets Go 1.23 or newer. The API is released as v0.x
while real-world usage is used to validate its shape.
Install
go get github.com/Heming9/gormkit@latest
Open a database
The primary API accepts a GORM dialector and configuration, so callers retain
control over the driver, logger, naming strategy, and migration behavior.
database, err := gormkit.Open(
mysql.Open(dsn),
&gorm.Config{Logger: logger.Default.LogMode(logger.Warn)},
gormkit.NewTimestampPlugin(),
)
if err != nil {
return err
}
defer database.Close()
db := database.Client(ctx)
OpenMySQL is a convenience for common MySQL connection and pool settings. It
uses a silent GORM logger unless a logger is supplied.
Default database
Libraries should prefer an explicit *gormkit.Database. Applications that use
a single process-wide database can install a default:
database, err := gormkit.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return err
}
if err := gormkit.UseDefault(database); err != nil {
return err
}
db, err := gormkit.SQLClient(ctx)
MustSQLClient is available at application boundaries where initialization is
already guaranteed.
Transactions
err := database.Transaction(ctx, func(txctx context.Context) error {
db := database.Client(txctx)
return db.Create(&record).Error
})
TPRequired is the default and reuses an existing transaction in the context.
TPNested asks GORM to create a nested transaction/savepoint when a transaction
already exists.
Driver transaction settings can be supplied with WithTxOptions:
err := database.Transaction(ctx, fn,
gormkit.WithPropagation(gormkit.TPRequired),
gormkit.WithTxOptions(&sql.TxOptions{
Isolation: sql.LevelReadCommitted,
ReadOnly: true,
}),
)
Passing TPRequired or TPNested directly remains supported. When an existing
transaction is reused or nested, explicit transaction settings must match its
settings because savepoints cannot change isolation or read-only state.
Existing calls therefore need no changes. Code that expands a prebuilt
[]TransactionPropagation should convert it to []TransactionOption (or pass
each value through WithPropagation) before expanding the slice.
Generic repository
Repositories accept pointer-to-struct models and return database errors. Record
not found errors remain compatible with errors.Is(err, gorm.ErrRecordNotFound).
repo := gormkit.NewRepo[*User](database.Client(ctx))
user := &User{Name: "example"}
if err := repo.Create(user); err != nil {
// Create is insert-only; primary/unique conflicts are returned.
}
user.Name = "updated"
if err := repo.Update(user); err != nil {
// Update requires a non-zero primary key and never inserts a missing row.
}
user, err := repo.FindByID(id)
if errors.Is(err, gorm.ErrRecordNotFound) {
// handle absence
}
users, err := repo.
WithScope(gormkit.OrderBy(gormkit.Desc("created_at"))).
FindBy("status = ?", "active")
RepoOf[T](ctx) creates a repository from the process-wide default database.
CreateAll performs a batch insert. UpdateAll updates entities by primary key
in one transaction and rolls back the batch when any record is missing. Use
UpdateBy when multiple records receive the same changes.
Tenant isolation
Use gormkit.TenantID as a model field to opt a model into tenant clauses:
type Project struct {
ID uint
TenantID gormkit.TenantID `gorm:"column:tenant_id;index"`
Name string
}
ctx = gormkit.WithTenantID(ctx, 42)
err := database.Client(ctx).Create(&Project{Name: "example"}).Error
Create, query, update, and delete operations require a tenant context for these
models. The tenant field is overwritten and always included on create—even when
the caller uses Select or Omit—and is omitted from updates. Conflict-updating
inserts, including GORM's Save fallback and OnConflict{UpdateAll: true}, are
rejected for tenant models because a conflict on a global unique key could
otherwise update another tenant's row. Use the repository's explicit Create
and Update operations instead.
Potentially bypassing APIs such as raw SQL, explicit table names, and joins are
rejected while automatic tenant mode is active. Use WithManualTenant when the
operation supplies its own tenant condition:
manualCtx := gormkit.WithManualTenant(ctx)
tenantID, _ := gormkit.GetTenantID(manualCtx)
err := database.Client(manualCtx).
Raw("SELECT * FROM projects WHERE tenant_id = ?", tenantID).
Scan(&projects).Error
Use WithDisableTenant only for an explicitly cross-tenant operation:
allTenantsCtx := gormkit.WithDisableTenant(ctx)
err := database.Client(allTenantsCtx).Find(&projects).Error
Unscoped() only bypasses GORM soft-delete filtering; tenant filtering remains
active. Combine it with WithDisableTenant when both behaviors are intended.
Timestamp plugin
NewTimestampPlugin maintains ctime and mtime Unix-second columns by
default. The column names and clock are configurable on TimestampPlugin.
plugin := gormkit.NewTimestampPlugin()
plugin.CreatedColumn = "created_unix"
plugin.UpdatedColumn = "updated_unix"
Tests
Default tests use a pure-Go in-memory SQLite driver:
go test ./...
go test -race ./...
go vet ./...
MySQL integration tests use the integration build tag and these environment
variables: MYSQL_ADDRESS, MYSQL_USERNAME, MYSQL_PASSWORD, and
MYSQL_DATABASE.
go test -tags integration ./integration
Compatibility
Before v1.0.0, minor releases may adjust APIs when doing so fixes ambiguous or
unsafe behavior. Release notes document every user-visible change.
License
MIT