storeit

package module
v0.8.7 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2024 License: MIT Imports: 13 Imported by: 0

README

storeit

Tag List

Tag Value Type SQL Statment DESC
field:eq any feild = value
field:neq any feild <> value
field:gt any feild > value
field:gte any feild >= value
field:lt any feild < value
field:lte any feild <= value
field:like string feild LIKE "%value%"
field:llike string feild LIKE "%value"
field:rlike string feild LIKE "value%"
field:in []any feild IN (value)
field:notin []any feild IN (value)
field:isnull any feild IS NULL
field:notnull []any feild IS NOT NULL
field:between []any (len==2) feild BETWEEN value[0] AND value[1]
-:sort string ORDER BY a DESC, b, c DESC value is a-,b+,c-
-:page int OFFSET (value-1)*per_page Default per_page is 50
-:per_page int LIMIT value Default 50
-:limit int LIMIT value
-:offset int OFFSET value

在 gin 里面使用

package main

import (
	"context"
	"database/sql"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/brianvoe/gofakeit/v6"
	"github.com/feymanlee/storeit"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID        int64        `gorm:"column:id;primarykey" json:"id"`
	Username  string       `gorm:"column:username" json:"username"`
	Email     string       `gorm:"column:email" json:"email"`
	Mobile    string       `gorm:"column:mobile" json:"mobile"`
	Status    string       `gorm:"column:status" json:"status"`
	Weight    int          `gorm:"column:weight" json:"weight"`
	Source    string       `gorm:"column:source" json:"source"`
	CreatedAt time.Time    `gorm:"column:created_at" json:"created_at"`
	UpdatedAt time.Time    `gorm:"column:updated_at" json:"updated_at"`
	DeletedAt sql.NullTime `gorm:"column:email;index"`
}

var db *gorm.DB

func init() {
	var err error
	db, err = gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}
}

func main() {
	router := gin.Default()
	v1 := router.Group("/api/v1")
	{
		v1.GET("/users", SearchUser)
		v1.POST("/users", CreateUser)
		v1.GET("/user/:id", FindUser)
		v1.PUT("/users/:id", UpdateUser)
		v1.DELETE("/users/:id", DeleteUser)
	}
	router.Run(":8180")
}
func SearchUser(c *gin.Context) {
	var req struct {
		ID      int    `form:"id" criteria:"id,eq"`
		Keyword string `form:"keyword" criteria:"phone,email:like"`
		Name    string `form:"name" criteria:"name:llike"`
		Phone   int    `form:"phone" criteria:"phone:eq"`
		Status  string `form:"status" criteria:"status:eq"`
		Weight  int    `form:"weight" criteria:"weight:eq"`
		Source  string `form:"source"`
		Page    int    `form:"page" criteria:"-:page"`
		PerPage int    `form:"per_page" criteria:"-:per_page"`
		Sorts   string `form:"sorts" criteria:"-:sort"`
	}
	if err := c.ShouldBindQuery(&req); err != nil {
		log.Println(err)
	}
	criteria, _ := storeit.ExtractCriteria(req)
	// source 是多个值,使用英文逗号分隔
	criteria.WhereIn("source", strings.Split(req.Source, ","))
	// 实现自动分页
	ret, _ := storeit.New[User](db).Paginate(c, criteria)

	c.JSON(http.StatusOK, ret)
}

func FindUser(c *gin.Context) {
	user, _ := storeit.New[User](db).FindByID(c, c.Params.ByName("id"))

	c.JSON(200, user)
}

func CreateUser(c *gin.Context) {
	var user User
	_ = c.ShouldBindJSON(&user)
	storeit.New[User](db).Insert(c, &user)
	c.JSON(200, user)
}

func UpdateUser(c *gin.Context) {
	var user User
	_ = c.ShouldBindJSON(&user)
	id, _ := strconv.Atoi(c.Params.ByName("id"))
	user.ID = int64(id)
	storeit.New[User](db).Save(c, &user)
	c.JSON(200, user)
}

func DeleteUser(c *gin.Context) {
	tx := storeit.New[User](db).DeleteById(c, c.Params.ByName("id"))
	if tx.Error != nil {
		c.AbortWithStatus(http.StatusBadRequest)
	}
	c.JSON(200, gin.H{
		"id": c.Params.ByName("id"),
	})
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnyToInt

func AnyToInt(in any) (iVal int, err error)

func AnyToString

func AnyToString(val any) (str string, err error)

func IsEmpty added in v0.7.0

func IsEmpty(val any) bool

Types

type Criteria

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

func ExtractCriteria

func ExtractCriteria(source any) (*Criteria, error)

ExtractCriteria 从结构体导出 Criteria

func NewCriteria

func NewCriteria() *Criteria

func (*Criteria) AddPreload added in v0.7.0

func (c *Criteria) AddPreload(name string, args ...any) *Criteria

func (*Criteria) GetLimit

func (c *Criteria) GetLimit() int

func (*Criteria) GetOffset

func (c *Criteria) GetOffset() int

func (*Criteria) GetPage

func (c *Criteria) GetPage() int

func (*Criteria) GetPerPage

func (c *Criteria) GetPerPage() int

func (*Criteria) Group

func (c *Criteria) Group(query string) *Criteria

func (*Criteria) GroupOr

func (c *Criteria) GroupOr(group groupConditionSpec) *Criteria

func (*Criteria) Having

func (c *Criteria) Having(query any, values ...any) *Criteria

func (*Criteria) Joins

func (c *Criteria) Joins(query string, values ...any) *Criteria

func (*Criteria) Limit

func (c *Criteria) Limit(limit int) *Criteria

func (*Criteria) Offset

func (c *Criteria) Offset(offset int) *Criteria

func (*Criteria) OrWhere

func (c *Criteria) OrWhere(query any, values ...any) *Criteria

func (*Criteria) Order

func (c *Criteria) Order(value string, isDescending bool) *Criteria

func (*Criteria) OrderAsc added in v0.7.5

func (c *Criteria) OrderAsc(value string) *Criteria

func (*Criteria) OrderDesc added in v0.7.0

func (c *Criteria) OrderDesc(value string) *Criteria

func (*Criteria) Page

func (c *Criteria) Page(page int) *Criteria

func (*Criteria) PerPage

func (c *Criteria) PerPage(perPage int) *Criteria

func (*Criteria) Where

func (c *Criteria) Where(query any, values ...any) *Criteria

func (*Criteria) WhereBetween

func (c *Criteria) WhereBetween(field string, start, end any) *Criteria

func (*Criteria) WhereIn

func (c *Criteria) WhereIn(field string, values any) *Criteria

func (*Criteria) WhereIsNull

func (c *Criteria) WhereIsNull(field string) *Criteria

func (*Criteria) WhereNot

func (c *Criteria) WhereNot(query any, values ...any) *Criteria

func (*Criteria) WhereNotIn

func (c *Criteria) WhereNotIn(field string, values any) *Criteria

func (*Criteria) WhereNotNull

func (c *Criteria) WhereNotNull(field string) *Criteria

type GormStore

type GormStore[M interface{}] struct {
	// contains filtered or unexported fields
}

func New

func New[M any](db *gorm.DB) *GormStore[M]

func (*GormStore[M]) AddPreload

func (r *GormStore[M]) AddPreload(name string, args ...any) *GormStore[M]

func (*GormStore[M]) All

func (r *GormStore[M]) All(ctx context.Context) ([]M, error)

func (*GormStore[M]) Avg

func (r *GormStore[M]) Avg(ctx context.Context, column string, criteria *Criteria) (avg float64, err error)

Avg Retrieve the average of the values of a given column.

func (*GormStore[M]) Columns

func (r *GormStore[M]) Columns(fields []string) *GormStore[M]

func (*GormStore[M]) Count

func (r *GormStore[M]) Count(ctx context.Context, criteria *Criteria) (i int64, err error)

Count Retrieve the "count" result of the query.

func (*GormStore[M]) Create added in v0.6.5

func (r *GormStore[M]) Create(ctx context.Context, model *M) *gorm.DB

func (*GormStore[M]) CreateInBatches

func (r *GormStore[M]) CreateInBatches(ctx context.Context, models []M, batchSize int) *gorm.DB

func (*GormStore[M]) Creates

func (r *GormStore[M]) Creates(ctx context.Context, models []M) *gorm.DB

func (*GormStore[M]) Delete

func (r *GormStore[M]) Delete(ctx context.Context, model *M) *gorm.DB

func (*GormStore[M]) DeleteById

func (r *GormStore[M]) DeleteById(ctx context.Context, id any) *gorm.DB

func (*GormStore[M]) Deletes

func (r *GormStore[M]) Deletes(ctx context.Context, criteria *Criteria) *gorm.DB

func (*GormStore[M]) Emit added in v0.6.6

func (r *GormStore[M]) Emit(fields []string) *GormStore[M]

func (*GormStore[M]) Exists added in v0.8.4

func (r *GormStore[M]) Exists(ctx context.Context, criteria *Criteria) (bool, error)

Exists check if the result exists

func (*GormStore[M]) Find

func (r *GormStore[M]) Find(ctx context.Context, criteria *Criteria) ([]M, error)

func (*GormStore[M]) FindByID

func (r *GormStore[M]) FindByID(ctx context.Context, id any) (*M, error)

FindByID find the result by ID

func (*GormStore[M]) FindByIDs

func (r *GormStore[M]) FindByIDs(ctx context.Context, ids []int64) ([]M, error)

FindByIDs find the result by IDs

func (*GormStore[M]) FindInBatches added in v0.6.8

func (r *GormStore[M]) FindInBatches(ctx context.Context, models *[]M, batchSize int, fc func(tx *gorm.DB, batch int) error, criteria *Criteria) error

FindInBatches finds all records in batches of batchSize

func (*GormStore[M]) First

func (r *GormStore[M]) First(ctx context.Context, criteria *Criteria) (*M, error)

First Execute the query and get the first result.

func (*GormStore[M]) Hidden

func (r *GormStore[M]) Hidden(fields []string) *GormStore[M]

func (*GormStore[M]) Insert

func (r *GormStore[M]) Insert(ctx context.Context, model *M) *gorm.DB

func (*GormStore[M]) Paginate

func (r *GormStore[M]) Paginate(ctx context.Context, criteria *Criteria) (*Pagination[M], error)

func (*GormStore[M]) Pluck added in v0.6.9

func (r *GormStore[M]) Pluck(ctx context.Context, column string, dest any, criteria *Criteria) error

func (*GormStore[M]) Save

func (r *GormStore[M]) Save(ctx context.Context, model M) *gorm.DB

func (*GormStore[M]) ScopeClosure

func (r *GormStore[M]) ScopeClosure(closure gormClosure) *GormStore[M]

func (*GormStore[M]) SetTx added in v0.7.6

func (r *GormStore[M]) SetTx(tx *gorm.DB) *GormStore[M]

func (*GormStore[M]) Sum

func (r *GormStore[M]) Sum(ctx context.Context, column string, criteria *Criteria) (sum float64, err error)

Sum Retrieve the sum of the values of a given column.

func (*GormStore[M]) Unscoped added in v0.7.3

func (r *GormStore[M]) Unscoped() *GormStore[M]

func (*GormStore[M]) Update

func (r *GormStore[M]) Update(ctx context.Context, column string, value interface{}, criteria *Criteria) *gorm.DB

func (*GormStore[M]) UpdateById added in v0.7.10

func (r *GormStore[M]) UpdateById(ctx context.Context, id any, column string, value interface{}) *gorm.DB

func (*GormStore[M]) Updates

func (r *GormStore[M]) Updates(ctx context.Context, attributes any, criteria *Criteria) *gorm.DB

func (*GormStore[M]) UpdatesById added in v0.7.10

func (r *GormStore[M]) UpdatesById(ctx context.Context, id any, updates interface{}) *gorm.DB

func (*GormStore[M]) WithTrashed added in v0.7.11

func (r *GormStore[M]) WithTrashed(with bool) *GormStore[M]

type Pagination

type Pagination[M any] struct {
	Total   int64 `json:"total"`
	PerPage int   `json:"per_page"`
	Page    int   `json:"page"`
	Items   []M   `json:"items"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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