repositorygorm

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2024 License: MIT Imports: 9 Imported by: 0

README

介绍

这是一个使用gorm.io/gorm作为驱动的 repository 库,支持 github.com/ace-zhaoy/go-repository 协议。

使用

go get github.com/ace-zhaoy/go-repository-gorm

快速使用

假设表名为users

package main

import (
	"context"
	"fmt"
	goid "github.com/ace-zhaoy/go-id"
	repositorygorm "github.com/ace-zhaoy/go-repository-gorm"
	"github.com/ace-zhaoy/go-repository/contract"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

func (u *User) GetID() int64 {
	return u.ID
}

func (u *User) SetID(id int64) {
	u.ID = id
}

type UserRepository struct {
	contract.CrudRepository[int64, *User]
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	return &UserRepository{
		CrudRepository: repositorygorm.NewCrudRepository[int64, *User](db),
	}
}

func main() {
	rootPassword := ""
	mysqlEndpoint := ""
	databaseName := ""
	dsn := fmt.Sprintf("root:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", rootPassword, mysqlEndpoint, databaseName)
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{
		TranslateError: true,
	})
	userRepository := NewUserRepository(db)
	id, err := userRepository.Create(context.Background(), &User{
		ID:   goid.GenID(),
		Name: "test",
	})
	fmt.Printf("id = %d, err = %+v\n", id, err)
}

假设表名为user

package main

import (
	"context"
	"fmt"
	goid "github.com/ace-zhaoy/go-id"
	repositorygorm "github.com/ace-zhaoy/go-repository-gorm"
	"github.com/ace-zhaoy/go-repository/contract"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

func (u *User) GetID() int64 {
	return u.ID
}

func (u *User) SetID(id int64) {
	u.ID = id
}

type UserRepository struct {
	contract.CrudRepository[int64, *User]
}

func (u *UserRepository) Table() string {
	return "user"
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	u := &UserRepository{}
	u.CrudRepository = repositorygorm.NewCrudRepository[int64, *User](db.Table(u.Table()))
	return u
}

func main() {
	rootPassword := ""
	mysqlEndpoint := ""
	databaseName := ""
	dsn := fmt.Sprintf("root:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", rootPassword, mysqlEndpoint, databaseName)
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{
		TranslateError: true,
	})
	userRepository := NewUserRepository(db)
	id, err := userRepository.Create(context.Background(), &User{
		ID:   goid.GenID(),
		Name: "test",
	})
	fmt.Printf("id = %d, err = %+v\n", id, err)
}

使用软删

增加 DeletedAt 属性即可

package main

import (
	"context"
	"fmt"
	"github.com/ace-zhaoy/errors"
	goid "github.com/ace-zhaoy/go-id"
	"github.com/ace-zhaoy/go-repository"
	repositorygorm "github.com/ace-zhaoy/go-repository-gorm"
	"github.com/ace-zhaoy/go-repository/contract"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/soft_delete"
	"log"
)

type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at"`
}

func (u *User) GetID() int64 {
	return u.ID
}

func (u *User) SetID(id int64) {
	u.ID = id
}

type UserRepository struct {
	contract.CrudRepository[int64, *User]
}

func (u *UserRepository) Table() string {
	return "user"
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	u := &UserRepository{}
	u.CrudRepository = repositorygorm.NewCrudRepository[int64, *User](db.Table(u.Table()))
	return u
}

func main() {
	defer errors.Recover(func(e error) { 
		log.Fatalf("err: %+v\n", e)
	})
	rootPassword := ""
	mysqlEndpoint := ""
	databaseName := ""
	dsn := fmt.Sprintf("root:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", rootPassword, mysqlEndpoint, databaseName)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		TranslateError: true,
	})
	errors.Check(err)
	userRepository := NewUserRepository(db)
	ctx := context.Background()
	id, err := userRepository.Create(ctx, &User{
		ID:   goid.GenID(),
		Name: "test",
	})
	errors.Check(err)

	err = userRepository.DeleteByID(ctx, id)
	errors.Check(err)
	
	// 常规查找(无法找到被删除的数据)
	_, err = userRepository.FindByID(ctx, id)
	fmt.Println(errors.Is(err, repository.ErrNotFound))
	
	// 使用 Unscoped 查找(可以找到被删除的数据)
	user, err := userRepository.Unscoped().FindByID(ctx, id)
	errors.Check(err)
	fmt.Println(user.DeletedAt)
}

自定义方法

例如增加 OtherMethod 方法

package main

import (
	"fmt"
	"github.com/ace-zhaoy/errors"
	repositorygorm "github.com/ace-zhaoy/go-repository-gorm"
	"github.com/ace-zhaoy/go-repository/contract"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/soft_delete"
	"log"
)

type User struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at"`
}

func (u *User) GetID() int64 {
	return u.ID
}

func (u *User) SetID(id int64) {
	u.ID = id
}

type UserRepository struct {
	contract.CrudRepository[int64, *User]
	db *gorm.DB
}

func (u *UserRepository) Table() string {
	return "user"
}

func (u *UserRepository) connect() *gorm.DB {
	if u.IsUnscoped() {
		return u.db.Unscoped()
	}
	return u.db
}

func (u *UserRepository) OtherMethod() {
	// r.connect().xxx
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	u := &UserRepository{}
	u.db = db.Table(u.Table())
	u.CrudRepository = repositorygorm.NewCrudRepository[int64, *User](u.db)
	return u
}

func main() {
	defer errors.Recover(func(e error) { 
		log.Fatalf("err: %+v\n", e)
	})
	rootPassword := ""
	mysqlEndpoint := ""
	databaseName := ""
	dsn := fmt.Sprintf("root:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", rootPassword, mysqlEndpoint, databaseName)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		TranslateError: true,
	})
	errors.Check(err)
	userRepository := NewUserRepository(db)
	userRepository.OtherMethod()
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CrudRepository

type CrudRepository[ID comparable, ENTITY contract.ENTITY[ID]] struct {
	// contains filtered or unexported fields
}
Example
defer errors.Recover(func(e error) { log.Fatalf("%+v", e) })
var ctx = context.Background()
var db *gorm.DB
userRepository := NewUserRepository(db)
id, err := userRepository.Create(ctx, &User{
	ID:   idGen.Generate(),
	Name: "test",
})
errors.Check(err)
user, err := userRepository.FindByID(ctx, id)
if errors.Is(err, repository.ErrNotFound) {
	// TODO: handle not found
	return
}
errors.Check(err)
_ = user
Output:

func NewCrudRepository

func NewCrudRepository[ID comparable, ENTITY contract.ENTITY[ID]](db *gorm.DB) *CrudRepository[ID, ENTITY]

func (*CrudRepository[ID, ENTITY]) Count

func (c *CrudRepository[ID, ENTITY]) Count(ctx context.Context) (count int, err error)

func (*CrudRepository[ID, ENTITY]) CountByFilter

func (c *CrudRepository[ID, ENTITY]) CountByFilter(ctx context.Context, filter map[string]any) (count int, err error)

func (*CrudRepository[ID, ENTITY]) Create

func (c *CrudRepository[ID, ENTITY]) Create(ctx context.Context, entity ENTITY) (id ID, err error)

func (*CrudRepository[ID, ENTITY]) Delete

func (c *CrudRepository[ID, ENTITY]) Delete(ctx context.Context, filter map[string]any) (err error)

func (*CrudRepository[ID, ENTITY]) DeleteAll

func (c *CrudRepository[ID, ENTITY]) DeleteAll(ctx context.Context) (err error)

func (*CrudRepository[ID, ENTITY]) DeleteByID

func (c *CrudRepository[ID, ENTITY]) DeleteByID(ctx context.Context, id ID) (err error)

func (*CrudRepository[ID, ENTITY]) DeleteByIDs

func (c *CrudRepository[ID, ENTITY]) DeleteByIDs(ctx context.Context, ids []ID) (err error)

func (*CrudRepository[ID, ENTITY]) Exists

func (c *CrudRepository[ID, ENTITY]) Exists(ctx context.Context, filter map[string]any) (exists bool, err error)

func (*CrudRepository[ID, ENTITY]) ExistsByID

func (c *CrudRepository[ID, ENTITY]) ExistsByID(ctx context.Context, id ID) (exists bool, err error)

func (*CrudRepository[ID, ENTITY]) ExistsByIDs

func (c *CrudRepository[ID, ENTITY]) ExistsByIDs(ctx context.Context, ids []ID) (exists contract.Dict[ID, bool], err error)

func (*CrudRepository[ID, ENTITY]) FindAll

func (c *CrudRepository[ID, ENTITY]) FindAll(ctx context.Context) (collection contract.Collection[ID, ENTITY], err error)

func (*CrudRepository[ID, ENTITY]) FindByFilter

func (c *CrudRepository[ID, ENTITY]) FindByFilter(ctx context.Context, filter map[string]any) (collection contract.Collection[ID, ENTITY], err error)

func (*CrudRepository[ID, ENTITY]) FindByFilterWithPage

func (c *CrudRepository[ID, ENTITY]) FindByFilterWithPage(ctx context.Context, filter map[string]any, limit, offset int, orders ...contract.Order) (collection contract.Collection[ID, ENTITY], err error)

func (*CrudRepository[ID, ENTITY]) FindByID

func (c *CrudRepository[ID, ENTITY]) FindByID(ctx context.Context, id ID) (entity ENTITY, err error)

func (*CrudRepository[ID, ENTITY]) FindByIDs

func (c *CrudRepository[ID, ENTITY]) FindByIDs(ctx context.Context, ids []ID) (collection contract.Collection[ID, ENTITY], err error)

func (*CrudRepository[ID, ENTITY]) FindByPage

func (c *CrudRepository[ID, ENTITY]) FindByPage(ctx context.Context, limit, offset int, orders ...contract.Order) (collection contract.Collection[ID, ENTITY], err error)

func (*CrudRepository[ID, ENTITY]) IDField

func (c *CrudRepository[ID, ENTITY]) IDField() string

func (*CrudRepository[ID, ENTITY]) IsUnscoped

func (c *CrudRepository[ID, ENTITY]) IsUnscoped() bool

func (*CrudRepository[ID, ENTITY]) SoftDeleteEnabled

func (c *CrudRepository[ID, ENTITY]) SoftDeleteEnabled() bool

func (*CrudRepository[ID, ENTITY]) SoftDeleteField

func (c *CrudRepository[ID, ENTITY]) SoftDeleteField() string

func (*CrudRepository[ID, ENTITY]) Unscoped

func (c *CrudRepository[ID, ENTITY]) Unscoped() contract.CrudRepository[ID, ENTITY]

func (*CrudRepository[ID, ENTITY]) Update

func (c *CrudRepository[ID, ENTITY]) Update(ctx context.Context, filter map[string]any, data map[string]any) (err error)

func (*CrudRepository[ID, ENTITY]) UpdateByID

func (c *CrudRepository[ID, ENTITY]) UpdateByID(ctx context.Context, id ID, data map[string]any) (err error)

func (*CrudRepository[ID, ENTITY]) UpdateNonZero

func (c *CrudRepository[ID, ENTITY]) UpdateNonZero(ctx context.Context, filter map[string]any, entity ENTITY) (err error)

func (*CrudRepository[ID, ENTITY]) UpdateNonZeroByID

func (c *CrudRepository[ID, ENTITY]) UpdateNonZeroByID(ctx context.Context, id ID, entity ENTITY) (err error)

Jump to

Keyboard shortcuts

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