otgorm

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2021 License: MIT Imports: 24 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
})

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 (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() []interface{}

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
	GormConfigInterceptor `optional:"true"`
	opentracing.Tracer    `optional:"true"`
Provide:
	Maker
	Factory
	*gorm.DB

Types

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 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(make Maker, env contract.Env, logger log.Logger, container contract.Container) Module

New creates Module

func (Module) ProvideCommand

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

ProvideCommand provides migration and seed command.

type RollbackFunc

type RollbackFunc func(*gorm.DB) error

RollbackFunc is the func signature for rollbacking.

type SQLite added in v0.2.0

type SQLite gorm.DB

SQLite is an alias of gorm.DB. This is useful when injecting test db.

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)

Jump to

Keyboard shortcuts

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