orm

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2024 License: MIT Imports: 14 Imported by: 0

README

Kratos ORM

Kratos ORM is a GORM for Kratos Framework.

  • Support OpenTelemetry (Statement.SkipHooks skip the reporting if not recording)

Installation

with cgo

Docs

$ go get -u gorm.io/driver/sqlite

without cgo

Docs

$ go get -u github.com/glebarez/sqlite

Usage

crud

type MyModel struct {
    ID int64
    Name string

    crud.DBModel
}

// or interface.
type myRepo struct {
    crud.CRUD[MyModel]
}

func NewMyRepo(db *gorm.DB) *myRepo {
    return &myRepo{crud.New(db)}
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrDriverNotFound = errors.New("gorm: driver not found")
)

Functions

func New

func New(opts ...Option) (*gorm.DB, error)
Example
package main

import (
	"context"
	"fmt"
	"time"

	// "gorm.io/driver/sqlite" // with cgo sqlite3
	"github.com/glebarez/sqlite" // without cgo sqlite3
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/gorm"

	"github.com/omalloc/contrib/kratos/orm"
	"github.com/omalloc/contrib/kratos/orm/crud"
	"github.com/omalloc/contrib/protobuf"
)

type User struct {
	ID   int64  `json:"id" gorm:"column:id;primaryKey;autoIncrement;"`
	Name string `json:"name" gorm:"column:name;"`

	orm.DBModel
}

type userRepo struct {
	crud.CRUD[User]

	db *gorm.DB
}

func NewUserRepo(db *gorm.DB) *userRepo {
	return &userRepo{
		CRUD: crud.New[User](db),
		db:   db,
	}
}

func main() {
	db, err := orm.New(
		orm.WithDriver(sqlite.Open("file:test.db?cache=shared&mode=memory&charset=utf8mb4&parseTime=true&loc=Local")),
		orm.WithTracingOpts(orm.WithDatabaseName("test")),
		orm.WithLogger(
			orm.WithDebug(),
			orm.WIthSlowThreshold(time.Second*2),
			orm.WithSkipCallerLookup(true),
			orm.WithSkipErrRecordNotFound(true),
			orm.WithLogHelper(log.NewFilter(log.GetLogger(), log.FilterLevel(log.LevelDebug))),
		),
	)
	if err != nil {
		panic(err)
	}

	// 创建测试表
	_ = db.Session(&gorm.Session{SkipHooks: true}).AutoMigrate(&User{})

	repo := NewUserRepo(db)

	if err := repo.Create(context.Background(), &User{Name: "test1"}); err != nil {
		println(err.Error())
	}

	if err := repo.Create(context.Background(), &User{Name: "test1"}); err != nil {
		println(err.Error())
	}

	// 自动分页
	pagination := protobuf.PageWrap(nil)
	users, err := repo.SelectList(context.Background(), pagination)
	if err != nil {
		println(err.Error())
	}

	if len(users) != int(pagination.Resp().Total) {
		println("data total size not equal, got %d want %d", len(users), pagination.Resp().Total)
	}

	for _, user := range users {
		fmt.Printf("%d--%s\n", user.ID, user.Name)
	}

}
Output:

1--test1
2--test1

func NewLogger

func NewLogger(opts ...GormLoggerOption) *gormLogger

func WithOmitVariablesFromTrace

func WithOmitVariablesFromTrace(ctx context.Context) context.Context

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config a gorm custom config

type DBModel

type DBModel struct {
	CreatedAt time.Time      `json:"created_at" gorm:"column:created_at;comment:创建时间"`
	UpdatedAt time.Time      `json:"updated_at" gorm:"column:updated_at;comment:更新时间"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index;column:deleted_at;comment:删除时间"`
}

type DataConf

type DataConf interface {
	GetDriver() string
	GetSource() string
}

type GormLoggerOption

type GormLoggerOption func(*gormLogger)

func WIthSlowThreshold

func WIthSlowThreshold(threshold time.Duration) GormLoggerOption

func WithDebug

func WithDebug() GormLoggerOption

func WithLogHelper

func WithLogHelper(klog log.Logger) GormLoggerOption

WithLogHelper set gorm-logger and log filters..

func WithSkipCallerLookup

func WithSkipCallerLookup(skip bool) GormLoggerOption

func WithSkipErrRecordNotFound

func WithSkipErrRecordNotFound(skip bool) GormLoggerOption

type GormOpenTelemetryPlugin

type GormOpenTelemetryPlugin struct {
	// contains filtered or unexported fields
}

func NewTracer

func NewTracer(opts ...TraceOption) *GormOpenTelemetryPlugin

func (*GormOpenTelemetryPlugin) Initialize

func (op *GormOpenTelemetryPlugin) Initialize(db *gorm.DB) error

func (*GormOpenTelemetryPlugin) Name

func (op *GormOpenTelemetryPlugin) Name() string

type Option

type Option func(*Config)

func WithDriver

func WithDriver(driver gorm.Dialector) Option

WithDriver set gorm-driver.

func WithLogger

func WithLogger(opts ...GormLoggerOption) Option

WithLogger set gorm-logger and has debug logger writer..

func WithTracing

func WithTracing() Option

WithTracing set gorm-tracing. used for opentelemetry.

func WithTracingOpts

func WithTracingOpts(opts ...TraceOption) Option

WithTracingOpts set gorm-tracing some opts. used for opentelemetry.

type TraceOption

type TraceOption interface {
	// contains filtered or unexported methods
}

TraceOption allows for managing options for the tracing plugin.

func WithAlwaysOmitVariables

func WithAlwaysOmitVariables() TraceOption

WithAlwaysOmitVariables will omit variables from the span attributes

func WithDatabaseName

func WithDatabaseName(dbName string) TraceOption

WithDatabaseName specified the database name to be used in span names

since its not possible to extract this information from gorm

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) TraceOption

WithTracerProvider sets the tracer provider to use for opentelemetry.

If none is specified, the global provider is used.

type Transaction added in v1.0.9

type Transaction interface {
	WithContext(context.Context, func(ctx context.Context, tx *gorm.DB) error) error
}

func NewTransactionManager added in v1.0.9

func NewTransactionManager(dataSource *gorm.DB) Transaction

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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