Documentation
¶
Overview ¶
Package gormkit provides small, composable helpers for GORM v2.
The package includes database lifecycle management, context-aware transactions, a generic repository, reusable scopes, tenant isolation, and an optional Unix timestamp plugin. Applications can use an explicit Database instance or install one as the process default for legacy-style package functions.
Index ¶
- Variables
- func Asc(name string) clause.OrderByColumn
- func Connect(config *MySQLConfig) error
- func ConnectMySQL(config *MySQLConfig) error
- func Connected() bool
- func Desc(name string) clause.OrderByColumn
- func RawOrder(expression string) (clause.OrderByColumn, error)
- func Transaction(ctx context.Context, fn func(context.Context) error, ...) error
- func UseDefault(db *Database) error
- func WithTenantID(ctx context.Context, id TenantID) context.Context
- type Client
- type Database
- type JSONData
- type JsonData
- type MySQLConfig
- type Paging
- type Query
- type Repository
- type Scope
- type TenantID
- func (TenantID) CreateClauses(field *schema.Field) []clause.Interface
- func (TenantID) DeleteClauses(field *schema.Field) []clause.Interface
- func (id TenantID) Int64() int64
- func (TenantID) QueryClauses(field *schema.Field) []clause.Interface
- func (id TenantID) String() string
- func (TenantID) UpdateClauses(field *schema.Field) []clause.Interface
- type Timestamp
- type TimestampPlugin
- type TransactionPropagation
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotInitialized indicates that no process-wide default database exists. ErrNotInitialized = errors.New("gormkit: default database is not initialized") // ErrNilDatabase indicates that a nil GORM database was supplied. ErrNilDatabase = errors.New("gormkit: database must not be nil") )
var ( ErrInvalidModel = errors.New("gormkit: repository model must be a concrete type") ErrInvalidPaging = errors.New("gormkit: paging offset and limit must not be negative") ErrMultipleRows = errors.New("gormkit: more than one row matches the save condition") )
var ErrInvalidTransactionPropagation = errors.New("gormkit: invalid transaction propagation")
var ErrTenantRequired = errors.New("gormkit: tenant context is required")
Functions ¶
func Asc ¶
func Asc(name string) clause.OrderByColumn
Asc returns an ascending, quoted order column.
func Connect ¶
func Connect(config *MySQLConfig) error
Connect is retained for source compatibility. Deprecated: use ConnectMySQL.
func ConnectMySQL ¶
func ConnectMySQL(config *MySQLConfig) error
ConnectMySQL opens MySQL and installs it as the process-wide default database.
func Connected ¶
func Connected() bool
Connected reports whether a process-wide default database is installed.
func Desc ¶
func Desc(name string) clause.OrderByColumn
Desc returns a descending, quoted order column.
func RawOrder ¶
func RawOrder(expression string) (clause.OrderByColumn, error)
RawOrder returns an explicitly raw order expression.
func Transaction ¶
func Transaction(ctx context.Context, fn func(context.Context) error, options ...TransactionPropagation) error
Transaction executes fn using the process-wide default database.
func UseDefault ¶
UseDefault installs db as the process-wide default database.
Types ¶
type Client ¶
Client is an alias for GORM's database handle.
func GetTransaction ¶
GetTransaction returns the transaction stored in ctx, if any.
func MustSQLClient ¶
MustSQLClient returns the default database session bound to ctx and panics when no default database has been installed.
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database owns a configured GORM database handle.
func Open ¶
Open creates a Database from a GORM dialector and configuration. Force update support is registered on every database opened by this function.
func OpenMySQL ¶
func OpenMySQL(config MySQLConfig) (*Database, error)
OpenMySQL opens a MySQL database without installing it as the process default.
func Wrap ¶
Wrap creates a Database around an existing GORM handle. It does not register callbacks or plugins on the supplied handle.
func (*Database) Client ¶
Client returns a session bound to ctx. A nil context is treated as context.Background().
func (*Database) Transaction ¶
func (d *Database) Transaction(ctx context.Context, fn func(context.Context) error, options ...TransactionPropagation) error
Transaction executes fn in a transaction and propagates the transaction through the callback context.
type JSONData ¶
type JSONData []byte
JSONData provides explicit JSON encoding helpers for byte slices.
type JsonData ¶
type JsonData = JSONData
JsonData is retained for source compatibility. Deprecated: use JSONData.
type MySQLConfig ¶
type MySQLConfig struct {
Username string
Password string
Address string
Database string
Charset string
TablePrefix string
Location *time.Location
Logger logger.Interface
Plugins []gorm.Plugin
SingularTable bool
DisableForeignKeyConstraintsWhenMigrating bool
MaxIdleConnections int
MaxOpenConnections int
ConnectionMaxIdleTime time.Duration
ConnectionMaxLifetime time.Duration
}
MySQLConfig configures the optional MySQL convenience opener.
type Repository ¶
type Repository[T any] interface { FindByID(id any) (T, error) FindOneBy(where any, args ...any) (T, error) FindLastOneBy(where any, args ...any) (T, error) FindByIDs(ids ...any) ([]T, error) FindBy(where any, args ...any) ([]T, error) FindAll() ([]T, error) Create(entity T) error CreateAll(entities ...T) error Save(entity T, where ...any) error SaveAll(entities ...T) error UpdateBy(data any, where any, args ...any) error DeleteBy(where any, args ...any) error CountBy(where ...any) (int64, error) Exists(where any, args ...any) (bool, error) WithPaging(paging Paging) Repository[T] WithScope(scopes ...Scope) Repository[T] Unscoped() Repository[T] DB() (Client, error) }
Repository provides common CRUD operations for pointer-to-struct model T. Query methods return database errors instead of panicking.
func NewRepository ¶
func NewRepository[T any](db Client) Repository[T]
NewRepository creates a repository from an explicit GORM database handle.
type Scope ¶
Scope is a reusable GORM scope.
func ApplyQuery ¶
ApplyQuery combines Query implementations into one scope.
func Force ¶
Force includes the named zero-valued struct fields in an Updates operation. It has no effect when Select or Omit is already present.
func LoadAllAssociations ¶
func LoadAllAssociations() Scope
LoadAllAssociations preloads all model associations.
func LoadAssociation ¶
LoadAssociation preloads one association with optional GORM conditions.
func LoadAssociations ¶
LoadAssociations preloads the named associations.
func OrderBy ¶
func OrderBy(columns ...clause.OrderByColumn) Scope
OrderBy applies structured order clauses. Callers must set Raw explicitly on a clause.Column when an unquoted database expression is intended.
type TenantID ¶
type TenantID int64
TenantID is a numeric tenant identifier stored as int64.
func GetTenantID ¶
GetTenantID returns the tenant stored in ctx, if any.
func (TenantID) CreateClauses ¶
func (TenantID) DeleteClauses ¶
type TimestampPlugin ¶
TimestampPlugin maintains configurable Unix-second timestamp columns. Empty fields use ctime and mtime. A nil Now function uses time.Now.
func NewTimeAutoUpdatePlugin ¶
func NewTimeAutoUpdatePlugin() *TimestampPlugin
NewTimeAutoUpdatePlugin is retained for source compatibility. Deprecated: use NewTimestampPlugin.
func NewTimestampPlugin ¶
func NewTimestampPlugin() *TimestampPlugin
NewTimestampPlugin returns a timestamp plugin with conventional defaults.
func (*TimestampPlugin) Initialize ¶
func (plugin *TimestampPlugin) Initialize(db *gorm.DB) error
func (*TimestampPlugin) Name ¶
func (plugin *TimestampPlugin) Name() string
type TransactionPropagation ¶
type TransactionPropagation uint8
TransactionPropagation controls how a transaction interacts with an existing transaction stored in the context.
const ( // TPRequired reuses an existing transaction or starts a new one. TPRequired TransactionPropagation = iota // TPNested creates a nested transaction when one already exists. TPNested )