Documentation
¶
Overview ¶
Package otgorm provides gorm with opentracing. For documentation about gorm usage, see https://gorm.io/index.html
Integration ¶
package otgorm exports the configuration in the following format:
gorm: default: database: mysql dsn: root@tcp(127.0.0.1:3306)/app?charset=utf8mb4&parseTime=True&loc=Local
Add the gorm dependency to core:
var c *core.C = core.New() c.Provide(otgorm.Provide)
Then you can invoke gorm from the application.
c.Invoke(func(client *gorm.DB) {
// use client
})
Sometimes there are valid reasons to connect to more than one mongo server. Inject otgorm.Maker to factory a *gorm.DB with a specific configuration entry.
c.Invoke(function(maker otgorm.Maker) {
client, err := maker.Make("default")
// do something with client
})
Migration and Seeding ¶
package otgorm comes with migration and seeding support. Other modules can register migration and seeding that are to be run by the command included in this package.
To invoke the command, add the module to core first:
c.AddModuleFunc(otgorm.New)
Then you can migrate the database by running:
go run main.go database migrate
See examples to learn more.
Example (MigrationAndSeeding) ¶
package main
import (
"fmt"
"github.com/DoNewsCode/core"
"github.com/DoNewsCode/core/otgorm"
"github.com/spf13/cobra"
"gorm.io/gorm"
)
type User struct {
gorm.Model
UserName string
}
type Module struct{}
func (m Module) ProvideMigration() []*otgorm.Migration {
return []*otgorm.Migration{
{
ID: "202010280100",
Migrate: func(db *gorm.DB) error {
type User struct {
gorm.Model
UserName string
}
return db.AutoMigrate(
&User{},
)
},
Rollback: func(db *gorm.DB) error {
type User struct{}
return db.Migrator().DropTable(&User{})
},
},
}
}
func (m Module) ProvideSeed() []*otgorm.Seed {
return []*otgorm.Seed{
{
ID: "202010280200",
Name: "seeding mysql",
Run: func(db *gorm.DB) error {
for i := 0; i < 100; i++ {
db.Create(&User{
UserName: "foo",
})
}
return nil
},
},
}
}
func main() {
c := core.New(
core.WithInline("log.level", "error"),
core.WithInline("gorm.default.database", "sqlite"),
core.WithInline("gorm.default.dsn", "file::memory:?cache=shared"),
)
c.ProvideEssentials()
c.Provide(otgorm.Provide)
c.AddModule(&Module{})
c.AddModuleFunc(otgorm.New)
rootCmd := cobra.Command{}
c.ApplyRootCommand(&rootCmd)
rootCmd.SetArgs([]string{"database", "migrate"})
rootCmd.Execute()
rootCmd.SetArgs([]string{"database", "seed"})
rootCmd.Execute()
c.Invoke(func(db *gorm.DB) {
var user User
db.Last(&user)
fmt.Println(user.UserName)
})
}
Output: foo
Index ¶
- func AddGormCallbacks(db *gorm.DB, tracer opentracing.Tracer)
- func ProvideDialector(conf *databaseConf) (gorm.Dialector, error)
- func ProvideGormConfig(l log.Logger, conf *databaseConf) *gorm.Config
- func ProvideGormDB(dialector gorm.Dialector, config *gorm.Config, tracer opentracing.Tracer) (*gorm.DB, func(), error)
- func ProvideMemoryDatabase() *gorm.DB
- type DatabaseIn
- type DatabaseOut
- type Factory
- type GormConfigInterceptor
- type GormLogAdapter
- func (g GormLogAdapter) Error(ctx context.Context, s string, i ...interface{})
- func (g GormLogAdapter) Info(ctx context.Context, s string, i ...interface{})
- func (g GormLogAdapter) LogMode(logLevel logger.LogLevel) logger.Interface
- func (g GormLogAdapter) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
- func (g GormLogAdapter) Warn(ctx context.Context, s string, i ...interface{})
- type Maker
- type MigrateFunc
- type Migration
- type MigrationProvider
- type Migrations
- type Module
- type RollbackFunc
- type Seed
- type SeedProvider
- type Seeds
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddGormCallbacks ¶
func AddGormCallbacks(db *gorm.DB, tracer opentracing.Tracer)
AddGormCallbacks adds callbacks for tracing, you should call SetSpanToGorm to make them work Copied from https://github.com/smacker/opentracing-gorm/blob/master/otgorm.go Under MIT License: https://github.com/smacker/opentracing-gorm/blob/master/LICENSE
func ProvideDialector ¶
ProvideDialector provides a gorm.Dialector. Mean to be used as an intermediate step to create *gorm.DB
func ProvideGormConfig ¶
ProvideGormConfig provides a *gorm.Config. Mean to be used as an intermediate step to create *gorm.DB
func ProvideGormDB ¶
func ProvideGormDB(dialector gorm.Dialector, config *gorm.Config, tracer opentracing.Tracer) (*gorm.DB, func(), error)
ProvideGormDB provides a *gorm.DB. It is intended to be used with ProvideDialector and ProvideGormConfig. Gorm opens connection to database while building *gorm.db. This means if the database is not available, the system will fail when initializing dependencies.
func ProvideMemoryDatabase ¶
ProvideMemoryDatabase provides a sqlite database in memory mode. This is useful for testing.
Types ¶
type DatabaseIn ¶
type DatabaseIn struct {
di.In
Conf contract.ConfigAccessor
Logger log.Logger
GormConfigInterceptor GormConfigInterceptor `optional:"true"`
Tracer opentracing.Tracer `optional:"true"`
}
DatabaseIn is the injection parameter for Provide.
type DatabaseOut ¶
type DatabaseOut struct {
di.Out
Database *gorm.DB
Factory Factory
Maker Maker
ExportedConfig []config.ExportedConfig `group:"config,flatten"`
}
DatabaseOut is the result of Provide. *gorm.DB is not a interface type. It is up to the users to define their own database repository interface.
func Provide ¶
func Provide(p DatabaseIn) (DatabaseOut, func(), error)
Provide creates Factory and *gorm.DB. It is a valid dependency for package core.
type Factory ¶
Factory is the *di.Factory that creates *gorm.DB under a specific configuration entry.
type GormConfigInterceptor ¶
GormConfigInterceptor is a function that allows user to make last minute change to *gorm.Config when constructing *gorm.DB.
type GormLogAdapter ¶
GormLogAdapter is an adapter between kitlog and gorm logger interface
func (GormLogAdapter) Error ¶
func (g GormLogAdapter) Error(ctx context.Context, s string, i ...interface{})
Error implements logger.Interface
func (GormLogAdapter) Info ¶
func (g GormLogAdapter) Info(ctx context.Context, s string, i ...interface{})
Info implements logger.Interface
func (GormLogAdapter) LogMode ¶
func (g GormLogAdapter) LogMode(logLevel logger.LogLevel) logger.Interface
LogMode implements logger.Interface
type MigrateFunc ¶
MigrateFunc is the func signature for migrating.
type Migration ¶
type Migration struct {
// ID is the migration identifier. Usually a timestamp like "201601021504".
ID string
// Connection is the preferred database connection name, like "default".
Connection string
// Migrate is a function that will br executed while running this migration.
Migrate MigrateFunc
// Rollback will be executed on rollback. Can be nil.
Rollback RollbackFunc
}
Migration represents a database migration (a modification to be made on the database).
type MigrationProvider ¶
type MigrationProvider interface {
ProvideMigration() []*Migration
}
MigrationProvider is an interface for database migrations. modules implementing this interface are migration providers. migrations will be collected in migrate command.
type Migrations ¶
Migrations is a collection of migrations in the application.
func (Migrations) Migrate ¶
func (m Migrations) Migrate() error
Migrate migrates all migrations registered in the application
func (Migrations) Rollback ¶
func (m Migrations) Rollback(id string) error
Rollback rollbacks migrations to a specified ID. If that id is -1, the last migration is rolled back.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is the registration unit for package core. It provides migration and seed command.
func (Module) ProvideCommand ¶
ProvideCommand provides migration and seed command.
type RollbackFunc ¶
RollbackFunc is the func signature for rollbacking.
type Seed ¶
type Seed struct {
// ID is the sorting key. Usually a timestamp like "201601021504".
ID string
// Name is the human-readable identifier used in logs.
Name string
// Connection is the preferred database connection name, like "default".
Connection string
// Run is a function that seeds the database
Run func(*gorm.DB) error
}
Seed is a action to populate the database with predefined values.
type SeedProvider ¶
type SeedProvider interface {
ProvideSeed() []*Seed
}
SeedProvider is an interface for database seeding. modules implementing this interface are seed providers. seeds will be collected in seed command.