otgorm

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2021 License: MIT Imports: 28 Imported by: 1

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.Providers())

Then you can invoke gorm from the application.

c.Invoke(func(client *gorm.DB) {
	// use client
})

The database types you can specify in configs are "mysql", "sqlite" and "clickhouse". Other database types can be added by injecting the otgorm.Drivers type to the dependency graph.

For example, if we want to use postgres:

var c *core.C = core.New()
c.Provide(otgorm.Providers())
c.Provide(di.Deps{func() otgorm.Drivers {
	return otgorm.Drivers{
	    "mysql":      mysql.Open,
	    "sqlite":     sqlite.Open,
	    "clickhouse": clickhouse.Open,
	    "postgres":   postgres.Open,
    }
}}

Sometimes there are valid reasons to connect to more than one mysql 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
package main

import (
	"fmt"
	"github.com/DoNewsCode/core"
	"github.com/DoNewsCode/core/otgorm"
	"gorm.io/gorm"
)

func main() {
	// Suppress log output by gorm in this test.
	c := core.New(core.WithInline("log.level", "warn"))
	c.ProvideEssentials()
	c.Provide(otgorm.Providers())
	c.Invoke(func(db *gorm.DB) {
		fmt.Println(db.Name())
	})
}
Output:

sqlite
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.Providers())
	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

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 Providers added in v0.2.0

func Providers(opt ...ProvidersOptionFunc) di.Deps

Providers returns a set of database related providers for package core. It includes the Maker, database configs and the default *gorm.DB instance.

Depends On:
	contract.ConfigAccessor
	log.Logger
	opentracing.Tracer    `optional:"true"`
	Gauges `optional:"true"`
	contract.Dispatcher `optional:"true"`
Provide:
	Maker
	Factory
	*gorm.DB

Types

type Drivers added in v0.8.0

type Drivers map[string]func(dsn string) gorm.Dialector

Drivers is a map of string names and gorm.Dialector constructors. Inject Drivers to DI container to customize dialectors.

type Factory

type Factory struct {
	*di.Factory
}

Factory is the *di.Factory that creates *gorm.DB under a specific configuration entry.

func (Factory) Make

func (d Factory) Make(name string) (*gorm.DB, error)

Make creates *gorm.DB under a specific configuration entry.

type Gauges added in v0.5.0

type Gauges struct {
	Idle  metrics.Gauge
	InUse metrics.Gauge
	Open  metrics.Gauge
	// contains filtered or unexported fields
}

Gauges is a collection of metrics for database connection info.

func (*Gauges) DBName added in v0.9.0

func (g *Gauges) DBName(dbName string) *Gauges

DBName sets the dbname label of metrics.

func (*Gauges) Driver added in v0.9.0

func (g *Gauges) Driver(driver string) *Gauges

Driver sets the driver label of metrics.

func (*Gauges) Observe added in v0.9.0

func (g *Gauges) Observe(stats sql.DBStats)

Observe records the DBStats collected. It should be called periodically.

type GormConfigInterceptor

type GormConfigInterceptor func(name string, conf *gorm.Config)

GormConfigInterceptor is a function that allows user to Make last minute change to *gorm.Config when constructing *gorm.DB.

type GormLogAdapter

type GormLogAdapter struct {
	Logging log.Logger
}

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

func (GormLogAdapter) Trace

func (g GormLogAdapter) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

Trace implements logger.Interface

func (GormLogAdapter) Warn

func (g GormLogAdapter) Warn(ctx context.Context, s string, i ...interface{})

Warn implements logger.Interface

type Maker

type Maker interface {
	Make(name string) (*gorm.DB, error)
}

Maker models Factory

type MigrateFunc

type MigrateFunc func(*gorm.DB) error

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

type Migrations struct {
	Db         *gorm.DB
	Collection []*Migration
}

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 New

func New(in ModuleIn) Module

New creates a Module.

func (Module) ProvideCommand

func (m Module) ProvideCommand(command *cobra.Command)

ProvideCommand provides migration and seed command.

type ModuleIn added in v0.8.0

type ModuleIn struct {
	di.In

	Maker     Maker
	Env       contract.Env
	Logger    log.Logger
	Container contract.Container
	Conf      contract.ConfigAccessor
}

ModuleIn contains the input parameters needed for creating the new module.

type ProvidersOptionFunc added in v0.9.0

type ProvidersOptionFunc func(options *providersOption)

ProvidersOptionFunc is the type of functional providersOption for Providers. Use this type to change how Providers work.

func WithConfigInterceptor added in v0.9.0

func WithConfigInterceptor(interceptor GormConfigInterceptor) ProvidersOptionFunc

WithConfigInterceptor instructs the Providers to accept the GormConfigInterceptor so that users can change config during runtime. This can be useful when some dynamic computations on configs are required.

func WithDrivers added in v0.9.0

func WithDrivers(drivers Drivers) ProvidersOptionFunc

WithDrivers instructs the Providers to add new drivers or replace existing drivers. (By default, only "mysql", "sqlite", and "clickhouse" drivers are registered out of box.) For example, if SqlServer driver and mysql driver are need, we can pass in the following option

WithDriver(map[string]func(dsn string){"sqlserver": sqlServer.Open, "mysql": mysql.Open})

func WithReload added in v0.10.0

func WithReload(shouldReload bool) ProvidersOptionFunc

WithReload toggles whether the factory should reload cached instances upon OnReload event.

type RollbackFunc

type RollbackFunc func(*gorm.DB) error

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.

type Seeds

type Seeds struct {
	Logger     log.Logger
	Db         *gorm.DB
	Collection []*Seed
}

Seeds is a collection of seed.

func (*Seeds) Len

func (s *Seeds) Len() int

func (*Seeds) Less

func (s *Seeds) Less(i, j int) bool

func (*Seeds) Seed

func (s *Seeds) Seed() error

Seed runs all the seeds collected by the application.

func (*Seeds) Swap

func (s *Seeds) Swap(i, j int)

Directories

Path Synopsis
Package mock_metrics is a generated GoMock package.
Package mock_metrics is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL