gormx

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: MIT Imports: 16 Imported by: 0

README

GORMX - GORM Utils

Functions

package gormx // import "github.com/go-zoox/gormx"

var Version = "1.0.0"
func Create[T any](one *T) (*T, error)
func Delete[T any, W WhereCondition](where W) (err error)
func DeleteOneByID[T any](id uint) (err error)
func Exists[T any, W WhereCondition](where W) (bool, error)
func Find[T any](page, pageSize uint, where *Where, orderBy *OrderBy) (data []*T, total int64, err error)
func FindAll[T any](where *Where, orderBy *OrderBy) (data []*T, err error)
func FindByID[T any](id uint) (*T, error)
func FindOne[T any, W WhereCondition](where W) (*T, error)
func FindOneAndDelete[T any, W WhereCondition](where W) (*T, error)
func FindOneAndUpdate[T any, W WhereCondition](where W, callback func(*T)) (*T, error)
func FindOneByIDAndDelete[T any](id uint) (*T, error)
func FindOneByIDAndUpdate[T any](id uint, callback func(*T)) (*T, error)
func FindOneByIDOrCreate[T any](id uint, callback func(*T)) (*T, error)
func FindOneOrCreate[T any, W WhereCondition](where W, callback func(*T)) (*T, error)
func GetDB() *gorm.DB
func GetMany[T any](ids []uint) (data []*T, err error)
func GetOrCreate[T any, W WhereCondition](where W, callback func(*T)) (*T, error)
func Has[T any](where map[string]any) bool
func List[T any](page, pageSize uint, where *Where, orderBy *OrderBy) (data []*T, total int64, err error)
func ListALL[T any](where *Where, orderBy *OrderBy) (data []*T, err error)
func LoadDB(engine string, dsn string) (err error)
func Retrieve[T any](id uint) (*T, error)
func Save[T any](one *T) error
func Update[T any](id uint, uc func(*T)) (err error)

// Aggregate Functions
func Sum[T any](field string, where *Where) (float64, error)
func Avg[T any](field string, where *Where) (float64, error)
func Min[T any](field string, where *Where) (interface{}, error)
func Max[T any](field string, where *Where) (interface{}, error)
func CountDistinct[T any](field string, where *Where) (int64, error)
func GroupBy[T any](fields []string, where *Where, aggregates []string) ([]GroupByResult, error)
func Aggregate[T any](field string, where *Where, operations []string) (map[string]interface{}, error)

// Types
type WhereCondition interface{ map[any]any | *Where }  // Generic type constraint for where conditions
type OrderBy []OrderByOne
type OrderByOne struct{ ... }
type Page struct{ ... }
type SetWhereOptions struct{ ... }
type Where []WhereOne
type WhereOne struct{ ... }
type GroupByResult struct{ ... }
type AggregateResult struct{ ... }

Generic Where Support

GORMX now supports both map[any]any and *Where types for where conditions using Go generics. This provides flexibility while maintaining type safety.

Using map[any]any (Simple Queries)
// Find one
user, err := gormx.FindOne[User](map[any]any{"name": "Alice"})

// Check existence
exists, err := gormx.Exists[User](map[any]any{"email": "alice@example.com"})

// Delete
err := gormx.Delete[User](map[any]any{"id": 1})
Using *Where (Complex Queries)
// Fuzzy search
where := gormx.NewWhere()
where.Set("name", "Alice", &gormx.SetWhereOptions{IsFuzzy: true})
user, err := gormx.FindOne[User](where)

// NOT equal
where := gormx.NewWhere()
where.Set("age", 25, &gormx.SetWhereOptions{IsNotEqual: true})
users, err := gormx.FindOne[User](where)

// IN query
where := gormx.NewWhere()
where.Set("status", []string{"active", "pending"}, &gormx.SetWhereOptions{IsIn: true})
user, err := gormx.FindOne[User](where)

// Multiple conditions
where := gormx.NewWhere()
where.Set("category", "electronics")
where.Set("price", 1000, &gormx.SetWhereOptions{IsNotEqual: true})
where.Set("name", "Pro", &gormx.SetWhereOptions{IsFuzzy: true})
product, err := gormx.FindOne[Product](where)
Supported Methods

The following methods support both map[any]any and *Where:

  • FindOne[T, W]
  • FindOneAndDelete[T, W]
  • FindOneAndUpdate[T, W]
  • FindOneOrCreate[T, W]
  • GetOrCreate[T, W]
  • Delete[T, W]
  • Exists[T, W]

See WHERE_GENERIC.md for complete documentation.

Aggregate Query Examples

Basic Aggregate Functions
// Sum
total, err := gormx.Sum[Product](&gormx.Where{}, "price")

// Average
avgPrice, err := gormx.Avg[Product](&gormx.Where{}, "price")

// Min/Max
minPrice, err := gormx.Min[Product](&gormx.Where{}, "price")
maxPrice, err := gormx.Max[Product](&gormx.Where{}, "price")

// Count Distinct
uniqueCategories, err := gormx.CountDistinct[Product](&gormx.Where{}, "category")
Group By Queries
// Group by category with count
results, err := gormx.GroupBy[Product](
    []string{"category"}, 
    &gormx.Where{}, 
    []string{"COUNT(*) as count", "SUM(price) as sum"}
)

// Multiple aggregations in one query
aggregates, err := gormx.Aggregate[Product](
    "price", 
    &gormx.Where{}, 
    []string{"sum", "avg", "min", "max", "count"}
)
With Where Conditions
where := &gormx.Where{}
where.Set("category", "electronics")
where.Set("price", 100, &gormx.SetWhereOptions{IsFuzzy: true})

// Sum with conditions
total, err := gormx.Sum[Product](where, "price")

Chain Query Builder

GORMX provides a fluent chain query builder for constructing complex queries:

// Simple query
products, err := gormx.NewQuery[Product]().
    Where("category", "Electronics").
    OrderByDesc("price").
    Limit(10).
    Find()

// Complex query with multiple conditions
products, total, err := gormx.NewQuery[Product]().
    WhereIn("category", []string{"Electronics", "Books"}).
    Where("in_stock", true).
    WhereLike("name", "Pro").
    OrderByDesc("price").
    OrderByAsc("name").
    Paginate(1, 20)

// Aggregate queries
totalValue, err := gormx.NewQuery[Product]().
    Where("category", "Electronics").
    Sum("price")

avgPrice, err := gormx.NewQuery[Product]().
    Where("in_stock", true).
    Avg("price")

// Transactions
err := gormx.NewQuery[Product]().Transaction(func(tx *gormx.QueryBuilder[Product]) error {
    if err := tx.Create(&product); err != nil {
        return err
    }
    return tx.Where("quantity", 0).Update(updates)
})

See CHAIN.md for complete documentation on the chain query builder.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRecordNotFound record not found error
	ErrRecordNotFound = gorm.ErrRecordNotFound
	// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
	ErrInvalidTransaction = gorm.ErrInvalidTransaction
	// ErrNotImplemented not implemented
	ErrNotImplemented = gorm.ErrNotImplemented
	// ErrMissingWhereClause missing where clause
	ErrMissingWhereClause = gorm.ErrMissingWhereClause
	// ErrUnsupportedRelation unsupported relations
	ErrUnsupportedRelation = gorm.ErrUnsupportedRelation
	// ErrPrimaryKeyRequired primary keys required
	ErrPrimaryKeyRequired = gorm.ErrPrimaryKeyRequired
	// ErrModelValueRequired model value required
	ErrModelValueRequired = gorm.ErrModelValueRequired
	// ErrModelAccessibleFieldsRequired model accessible fields required
	ErrModelAccessibleFieldsRequired = gorm.ErrModelAccessibleFieldsRequired
	// ErrSubQueryRequired sub query required
	ErrSubQueryRequired = gorm.ErrSubQueryRequired
	// ErrInvalidData unsupported data
	ErrInvalidData = gorm.ErrInvalidData
	// ErrUnsupportedDriver unsupported driver
	ErrUnsupportedDriver = gorm.ErrUnsupportedDriver
	// ErrRegistered registered
	ErrRegistered = gorm.ErrRegistered
	// ErrInvalidField invalid field
	ErrInvalidField = gorm.ErrInvalidField
	// ErrEmptySlice empty slice found
	ErrEmptySlice = gorm.ErrEmptySlice
	// ErrDryRunModeUnsupported dry run mode unsupported
	ErrDryRunModeUnsupported = gorm.ErrDryRunModeUnsupported
	// ErrInvalidDB invalid db
	ErrInvalidDB = gorm.ErrInvalidDB
	// ErrInvalidValue invalid value
	ErrInvalidValue = gorm.ErrInvalidValue
	// ErrInvalidValueOfLength invalid values do not match length
	ErrInvalidValueOfLength = gorm.ErrInvalidValueOfLength
	// ErrPreloadNotAllowed preload is not allowed when count is used
	ErrPreloadNotAllowed = gorm.ErrPreloadNotAllowed
	// ErrDuplicatedKey occurs when there is a unique key constraint violation
	ErrDuplicatedKey = gorm.ErrDuplicatedKey
	// ErrForeignKeyViolated occurs when there is a foreign key constraint violation
	ErrForeignKeyViolated = gorm.ErrForeignKeyViolated
)
View Source
var Version = "1.6.1"

Version is the version of this package.

Functions

func Aggregate added in v1.6.0

func Aggregate[T any](field string, where *Where, operations []string) (map[string]interface{}, error)

Aggregate performs multiple aggregate operations in a single query

func Avg added in v1.6.0

func Avg[T any](field string, where *Where) (float64, error)

Avg calculates the average of a numeric field

func Connect added in v1.5.0

func Connect(engine string, dsn string, opts ...func(*LoadDBOptions)) (db *gorm.DB, err error)

Connect connects the database

func Count added in v1.2.0

func Count[T any](where *Where) (count int64, err error)

Count counts records.

func CountALL added in v1.2.0

func CountALL[T any]() (total int64, err error)

CountALL counts all records.

func CountDistinct added in v1.6.0

func CountDistinct[T any](field string, where *Where) (int64, error)

CountDistinct counts distinct values of a field

func Create

func Create[T any](one *T) (*T, error)

Create creates a record.

func Delete

func Delete[T any, W WhereCondition](where W) (err error)

Delete deletes the record from database by the given conditions. Supports both map[any]any and *Where as where condition.

func DeleteOneByID

func DeleteOneByID[T any](id uint) (err error)

DeleteOneByID deletes one record by id.

func Exists

func Exists[T any, W WhereCondition](where W) (bool, error)

Exists returns true if the record exists. Supports both map[any]any and *Where as where condition.

func Find

func Find[T any](page, pageSize uint, where *Where, orderBy *OrderBy) (data []*T, total int64, err error)

Find finds records.

func FindAll

func FindAll[T any](where *Where, orderBy *OrderBy) (data []*T, err error)

FindAll finds all records.

func FindByID

func FindByID[T any](id uint) (*T, error)

FindByID finds a record by id.

func FindOne

func FindOne[T any, W WhereCondition](where W) (*T, error)

FindOne finds one record. Supports both map[any]any and *Where as where condition.

func FindOneAndDelete

func FindOneAndDelete[T any, W WhereCondition](where W) (*T, error)

FindOneAndDelete finds one record and delete it. Supports both map[any]any and *Where as where condition.

func FindOneAndUpdate

func FindOneAndUpdate[T any, W WhereCondition](where W, callback func(*T)) (*T, error)

FindOneAndUpdate finds one and update it. Supports both map[any]any and *Where as where condition.

func FindOneByIDAndDelete

func FindOneByIDAndDelete[T any](id uint) (*T, error)

FindOneByIDAndDelete finds one record by id and delete it.

func FindOneByIDAndUpdate

func FindOneByIDAndUpdate[T any](id uint, callback func(*T)) (*T, error)

FindOneByIDAndUpdate finds one by id and update.

func FindOneByIDOrCreate

func FindOneByIDOrCreate[T any](id uint, callback func(*T)) (*T, error)

FindOneByIDOrCreate finds one record by id or create a new one.

func FindOneOrCreate

func FindOneOrCreate[T any, W WhereCondition](where W, callback func(*T)) (*T, error)

FindOneOrCreate find one or create one. Supports both map[any]any and *Where as where condition.

func FindOneWithComplexConditions added in v1.4.2

func FindOneWithComplexConditions[T any](where *Where, orderBy *OrderBy) (*T, error)

FindOneWithComplexConditions finds one record.

func Get added in v1.4.0

func Get[T any](id string) T

Get returns the model by the given id.

func GetDB

func GetDB() *gorm.DB

GetDB returns the gorm.DB instance

func GetDSN added in v1.3.6

func GetDSN() string

GetDSN returns the database DSN

func GetEngine added in v1.3.6

func GetEngine() string

GetEngine returns the database engine

func GetFieldType added in v1.6.0

func GetFieldType[T any](field string) (reflect.Type, error)

GetFieldType returns the type of a field in a struct

func GetMany

func GetMany[T any](ids []uint) (data []*T, err error)

GetMany gets many records by ids.

func GetOrCreate

func GetOrCreate[T any, W WhereCondition](where W, callback func(*T)) (*T, error)

GetOrCreate gets or creates a record. Supports both map[any]any and *Where as where condition.

func Has

func Has[T any](where map[string]any) bool

Has returns true if the record exists.

func IsDryRunModeUnsupportedError added in v1.0.9

func IsDryRunModeUnsupportedError(err error) bool

IsDryRunModeUnsupportedError returns true if err is related to dry run mode unsupported error

func IsDuplicatedKeyError added in v1.0.9

func IsDuplicatedKeyError(err error) bool

IsDuplicatedKeyError returns true if err is related to duplicated key error

func IsEmptySliceError added in v1.0.9

func IsEmptySliceError(err error) bool

IsEmptySliceError returns true if err is related to empty slice error

func IsForeignKeyViolatedError added in v1.0.9

func IsForeignKeyViolatedError(err error) bool

IsForeignKeyViolatedError returns true if err is related to foreign key violated error

func IsInvalidDBError added in v1.0.9

func IsInvalidDBError(err error) bool

IsInvalidDBError returns true if err is related to invalid db error

func IsInvalidDataError added in v1.0.9

func IsInvalidDataError(err error) bool

IsInvalidDataError returns true if err is related to invalid data error

func IsInvalidFieldError added in v1.0.9

func IsInvalidFieldError(err error) bool

IsInvalidFieldError returns true if err is related to invalid field error

func IsInvalidTransactionError added in v1.0.9

func IsInvalidTransactionError(err error) bool

IsInvalidTransactionError returns true if err is related to invalid transaction error

func IsInvalidValueError added in v1.0.9

func IsInvalidValueError(err error) bool

IsInvalidValueError returns true if err is related to invalid value error

func IsInvalidValueOfLengthError added in v1.0.9

func IsInvalidValueOfLengthError(err error) bool

IsInvalidValueOfLengthError returns true if err is related to invalid value of length error

func IsMissingWhereClauseError added in v1.0.9

func IsMissingWhereClauseError(err error) bool

IsMissingWhereClauseError returns true if err is related to missing where clause error

func IsModelAccessibleFieldsRequiredError added in v1.0.9

func IsModelAccessibleFieldsRequiredError(err error) bool

IsModelAccessibleFieldsRequiredError returns true if err is related to model accessible fields required error

func IsModelValueRequiredError added in v1.0.9

func IsModelValueRequiredError(err error) bool

IsModelValueRequiredError returns true if err is related to model value required error

func IsNotImplementedError added in v1.0.9

func IsNotImplementedError(err error) bool

IsNotImplementedError returns true if err is related to not implemented error

func IsPreloadNotAllowedError added in v1.0.9

func IsPreloadNotAllowedError(err error) bool

IsPreloadNotAllowedError returns true if err is related to preload not allowed error

func IsPrimaryKeyRequiredError added in v1.0.9

func IsPrimaryKeyRequiredError(err error) bool

IsPrimaryKeyRequiredError returns true if err is related to primary key required error

func IsRecordNotFoundError added in v1.0.9

func IsRecordNotFoundError(err error) bool

IsRecordNotFoundError returns true if err is related to record not found error

func IsRegisteredError added in v1.0.9

func IsRegisteredError(err error) bool

IsRegisteredError returns true if err is related to registered error

func IsSubQueryRequiredError added in v1.0.9

func IsSubQueryRequiredError(err error) bool

IsSubQueryRequiredError returns true if err is related to sub query required error

func IsUnsupportedDriverError added in v1.0.9

func IsUnsupportedDriverError(err error) bool

IsUnsupportedDriverError returns true if err is related to unsupported driver error

func IsUnsupportedRelationError added in v1.0.9

func IsUnsupportedRelationError(err error) bool

IsUnsupportedRelationError returns true if err is related to unsupported relation error

func List

func List[T any](page, pageSize uint, where *Where, orderBy *OrderBy) (data []*T, total int64, err error)

List lists records.

func ListALL added in v1.2.1

func ListALL[T any](where *Where, orderBy *OrderBy) (data []*T, err error)

ListALL lists all records.

func LoadDB

func LoadDB(engine string, dsn string, opts ...func(*LoadDBOptions)) (err error)

LoadDB loads the database

func Max added in v1.6.0

func Max[T any](field string, where *Where) (interface{}, error)

Max finds the maximum value of a field

func Migrate added in v1.4.0

func Migrate()

Migrate migrates the models to the database.

func Min added in v1.6.0

func Min[T any](field string, where *Where) (interface{}, error)

Min finds the minimum value of a field

func Register added in v1.0.6

func Register(name string, m Model)

Register registers the model.

func Retrieve

func Retrieve[T any](id uint) (*T, error)

Retrieve retrieves a record.

func SQL added in v1.3.5

func SQL[T any](sql string, values ...any) (*T, error)

SQL finds one record by id or create a new one.

func Save

func Save[T any](one *T) error

Save saves a record.

func SetDB added in v1.5.3

func SetDB(d *gorm.DB)

SetDB sets the global gorm.DB instance. This is useful for old projects that already use gorm.

func Sum added in v1.6.0

func Sum[T any](field string, where *Where) (float64, error)

Sum calculates the sum of a numeric field

func Update

func Update[T any](id uint, uc func(*T)) (err error)

Update updates a record.

Types

type AggregateResult added in v1.6.0

type AggregateResult struct {
	Value interface{}
	Error error
}

AggregateResult represents the result of an aggregate query

type Controller added in v1.0.5

type Controller interface {
	Name() string
	//
	Params(ctx *zoox.Context) *Params
}

Controller is the interface that wraps the basic methods.

type ControllerImpl added in v1.0.5

type ControllerImpl struct {
}

ControllerImpl is the implementation of the Controller interface.

func (*ControllerImpl) Params added in v1.0.7

func (c *ControllerImpl) Params(ctx *zoox.Context) *Params

Params returns the params.

type Date added in v1.5.7

type Date = datatypes.Date

Date is a date.

type GroupByResult added in v1.6.0

type GroupByResult struct {
	Group map[string]interface{}
	Count int64
	Sum   float64
	Avg   float64
	Min   interface{}
	Max   interface{}
}

GroupByResult represents the result of a group by query

func GroupBy added in v1.6.0

func GroupBy[T any](fields []string, where *Where, aggregates []string) ([]GroupByResult, error)

GroupBy performs group by operations with optional aggregations

type JSON added in v1.5.7

type JSON = datatypes.JSON

JSON is a JSON.

type JSONArray added in v1.5.7

type JSONArray[T any] datatypes.JSONSlice[T]

JSONArray is a JSON array. @TODO

type JSONObject added in v1.5.7

type JSONObject = datatypes.JSONMap

JSONObject is a JSON object.

type JoinClause added in v1.6.0

type JoinClause struct {
	Type      string // "INNER", "LEFT", "RIGHT", "FULL"
	Table     string
	Condition string
	Args      []interface{}
}

JoinClause represents a join clause

type ListParams added in v1.0.7

type ListParams struct {
	Page     uint
	PageSize uint
	Where    *Where
	OrderBy  *OrderBy
}

ListParams is the struct that wraps the basic fields.

type ListParamsDefault added in v1.0.7

type ListParamsDefault struct {
	Page     uint
	PageSize uint
}

ListParamsDefault is the struct that wraps the basic fields.

type LoadDBOptions added in v1.0.3

type LoadDBOptions struct {
	IsProd bool
	//
	TablePrefix string
	//
	DryRun bool
}

LoadDBOptions is the options for LoadDB

type Model added in v1.0.5

type Model interface {
	ModelName() string
	Model() ioc.Container
}

Model is the interface that wraps the basic methods.

type ModelGeneric added in v1.0.10

type ModelGeneric[T any] struct {
}

ModelGeneric ...

func (*ModelGeneric[T]) Create added in v1.0.10

func (m *ModelGeneric[T]) Create(one *T) (*T, error)

Create ...

func (*ModelGeneric[T]) Delete added in v1.0.10

func (m *ModelGeneric[T]) Delete(id uint) (err error)

Delete ...

func (*ModelGeneric[T]) Exists added in v1.0.10

func (m *ModelGeneric[T]) Exists(where map[any]any) (bool, error)

Exists ...

func (*ModelGeneric[T]) FindAll added in v1.0.10

func (m *ModelGeneric[T]) FindAll(where *Where, orderBy *OrderBy) ([]*T, error)

FindAll ...

func (*ModelGeneric[T]) FindByID added in v1.0.10

func (m *ModelGeneric[T]) FindByID(id uint) (*T, error)

FindByID ...

func (*ModelGeneric[T]) FindOne added in v1.0.10

func (m *ModelGeneric[T]) FindOne(where map[any]any) (*T, error)

FindOne ...

func (*ModelGeneric[T]) FindOneAndDelete added in v1.0.10

func (m *ModelGeneric[T]) FindOneAndDelete(where map[any]any) (*T, error)

FindOneAndDelete ...

func (*ModelGeneric[T]) FindOneAndUpdate added in v1.0.10

func (m *ModelGeneric[T]) FindOneAndUpdate(where map[any]any, callback func(*T)) (*T, error)

FindOneAndUpdate ...

func (*ModelGeneric[T]) FindOneOrCreate added in v1.0.10

func (m *ModelGeneric[T]) FindOneOrCreate(where map[any]any, callback func(*T)) (*T, error)

FindOneOrCreate ...

func (*ModelGeneric[T]) GetMany added in v1.0.10

func (m *ModelGeneric[T]) GetMany(ids []uint) (data []*T, err error)

GetMany ...

func (*ModelGeneric[T]) List added in v1.0.10

func (m *ModelGeneric[T]) List(page, pageSize uint, where *Where, orderBy *OrderBy) (data []*T, total int64, err error)

List ...

func (*ModelGeneric[T]) Retrieve added in v1.0.10

func (m *ModelGeneric[T]) Retrieve(id uint) (*T, error)

Retrieve ...

func (*ModelGeneric[T]) Save added in v1.0.10

func (m *ModelGeneric[T]) Save() error

Save ...

func (*ModelGeneric[T]) Update added in v1.0.10

func (m *ModelGeneric[T]) Update(id uint, uc func(*T)) (err error)

Update ...

type ModelImpl added in v1.0.5

type ModelImpl struct {
	ID        uint           `gorm:"primarykey" json:"id"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"`
	//
	Creator  uint `json:"creator"`
	Modifier uint `json:"modifier"`
}

ModelImpl is the implementation of the Model interface.

func (*ModelImpl) Model added in v1.0.5

func (m *ModelImpl) Model() ioc.Container

Model returns the model container.

func (*ModelImpl) ModelName added in v1.0.5

func (m *ModelImpl) ModelName() string

ModelName returns the name of the model.

type OrderBy

type OrderBy []OrderByOne

OrderBy is a list of order bys.

func NewOrderBy added in v1.6.0

func NewOrderBy() *OrderBy

NewOrderBy returns a new order by.

func (*OrderBy) Add added in v1.5.8

func (w *OrderBy) Add(key string, IsDESC bool)

Add adds a order by.

func (*OrderBy) AddClause added in v1.5.8

func (w *OrderBy) AddClause(clause string)

AddClause adds a order by clause.

func (*OrderBy) Build

func (w *OrderBy) Build() string

Build builds the order bys.

func (*OrderBy) Debug

func (w *OrderBy) Debug()

Debug prints the order bys.

func (*OrderBy) Del added in v1.0.8

func (w *OrderBy) Del(key string)

Del deletes a order by.

func (*OrderBy) Get

func (w *OrderBy) Get(key string) (bool, bool)

Get gets a order by.

func (*OrderBy) GetClause added in v1.5.8

func (w *OrderBy) GetClause(key string) string

GetClause gets the order by clause.

func (*OrderBy) Length

func (w *OrderBy) Length() int

Length returns the length of the order bys.

func (*OrderBy) Reset added in v1.3.4

func (w *OrderBy) Reset()

Reset resets the order bys.

func (*OrderBy) Set

func (w *OrderBy) Set(key string, IsDESC bool)

Set sets a order by.

type OrderByOne

type OrderByOne struct {
	Key    string
	IsDESC bool
	// contains filtered or unexported fields
}

OrderByOne is a single order by.

func (*OrderByOne) Clause added in v1.5.8

func (w *OrderByOne) Clause() string

Clause returns the clause of the order by.

func (*OrderByOne) String added in v1.5.8

func (w *OrderByOne) String() string

String returns the string of the order by.

type Page

type Page struct {
	Page     int64 `query:"page,default=1"`
	PageSize int64 `query:"pageSize,default=10"`
}

Page is the page query.

type Params added in v1.0.7

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

Params is the interface that wraps the basic methods.

func NewParams added in v1.0.7

func NewParams(ctx *zoox.Context) *Params

NewParams returns the params.

func (*Params) GetList added in v1.0.7

func (c *Params) GetList(defaults ...*ListParamsDefault) (*ListParams, error)

GetList is the struct that wraps the basic fields.

func (*Params) ID added in v1.0.7

func (c *Params) ID() (uint, error)

ID is the struct that wraps the basic fields.

func (*Params) OrderBy added in v1.0.7

func (c *Params) OrderBy() *OrderBy

OrderBy is the struct that wraps the basic fields.

func (*Params) Page added in v1.0.7

func (c *Params) Page() (uint, error)

Page is the struct that wraps the basic fields.

func (*Params) PageSize added in v1.0.7

func (c *Params) PageSize() (uint, error)

PageSize is the struct that wraps the basic fields.

func (*Params) Where added in v1.0.7

func (c *Params) Where() *Where

Where is the struct that wraps the basic fields.

type QueryBuilder added in v1.6.0

type QueryBuilder[T any] struct {
	// contains filtered or unexported fields
}

QueryBuilder provides a fluent interface for building database queries

func NewQuery added in v1.6.0

func NewQuery[T any]() *QueryBuilder[T]

NewQuery creates a new query builder for the given model type

func (*QueryBuilder[T]) Avg added in v1.6.0

func (q *QueryBuilder[T]) Avg(field string) (float64, error)

Avg calculates the average of a field

func (*QueryBuilder[T]) Chunk added in v1.6.0

func (q *QueryBuilder[T]) Chunk(chunkSize int, callback func([]*T) error) error

Chunk processes records in chunks

func (*QueryBuilder[T]) Clone added in v1.6.0

func (q *QueryBuilder[T]) Clone() *QueryBuilder[T]

Clone creates a copy of the query builder

func (*QueryBuilder[T]) Count added in v1.6.0

func (q *QueryBuilder[T]) Count() (int64, error)

Count executes the query and returns the count of matching records

func (*QueryBuilder[T]) Create added in v1.6.0

func (q *QueryBuilder[T]) Create(value *T) error

Create inserts a new record

func (*QueryBuilder[T]) CreateInBatches added in v1.6.0

func (q *QueryBuilder[T]) CreateInBatches(values []*T, batchSize int) error

CreateInBatches inserts records in batches

func (*QueryBuilder[T]) Delete added in v1.6.0

func (q *QueryBuilder[T]) Delete() error

Delete executes the query and deletes all matching records

func (*QueryBuilder[T]) Distinct added in v1.6.0

func (q *QueryBuilder[T]) Distinct() *QueryBuilder[T]

Distinct adds a DISTINCT clause

func (*QueryBuilder[T]) Exists added in v1.6.0

func (q *QueryBuilder[T]) Exists() (bool, error)

Exists checks if any records match the query conditions

func (*QueryBuilder[T]) Find added in v1.6.0

func (q *QueryBuilder[T]) Find() ([]*T, error)

Find executes the query and returns all matching records

func (*QueryBuilder[T]) FindInBatches added in v1.6.0

func (q *QueryBuilder[T]) FindInBatches(batchSize int, fn func(tx *gorm.DB, batch int) error) error

FindInBatches processes records in batches

func (*QueryBuilder[T]) First added in v1.6.0

func (q *QueryBuilder[T]) First() (*T, error)

First executes the query and returns the first matching record

func (*QueryBuilder[T]) GetDB added in v1.6.0

func (q *QueryBuilder[T]) GetDB() *gorm.DB

GetDB returns the underlying GORM DB instance

func (*QueryBuilder[T]) GetTableName added in v1.6.0

func (q *QueryBuilder[T]) GetTableName() string

GetTableName returns the table name for the model

func (*QueryBuilder[T]) GroupBy added in v1.6.0

func (q *QueryBuilder[T]) GroupBy(fields ...string) *QueryBuilder[T]

GroupBy adds a GROUP BY clause

func (*QueryBuilder[T]) Having added in v1.6.0

func (q *QueryBuilder[T]) Having(field string, value interface{}, opts ...*SetWhereOptions) *QueryBuilder[T]

Having adds a HAVING clause

func (*QueryBuilder[T]) Join added in v1.6.0

func (q *QueryBuilder[T]) Join(table, condition string, args ...interface{}) *QueryBuilder[T]

Join adds a JOIN clause

func (*QueryBuilder[T]) Last added in v1.6.0

func (q *QueryBuilder[T]) Last() (*T, error)

Last executes the query and returns the last matching record

func (*QueryBuilder[T]) LeftJoin added in v1.6.0

func (q *QueryBuilder[T]) LeftJoin(table, condition string, args ...interface{}) *QueryBuilder[T]

LeftJoin adds a LEFT JOIN clause

func (*QueryBuilder[T]) Limit added in v1.6.0

func (q *QueryBuilder[T]) Limit(limit int) *QueryBuilder[T]

Limit sets the LIMIT clause

func (*QueryBuilder[T]) Max added in v1.6.0

func (q *QueryBuilder[T]) Max(field string) (interface{}, error)

Max finds the maximum value of a field

func (*QueryBuilder[T]) Min added in v1.6.0

func (q *QueryBuilder[T]) Min(field string) (interface{}, error)

Min finds the minimum value of a field

func (*QueryBuilder[T]) Offset added in v1.6.0

func (q *QueryBuilder[T]) Offset(offset int) *QueryBuilder[T]

Offset sets the OFFSET clause

func (*QueryBuilder[T]) OrderBy added in v1.6.0

func (q *QueryBuilder[T]) OrderBy(field string, desc ...bool) *QueryBuilder[T]

OrderBy adds an ORDER BY clause

func (*QueryBuilder[T]) OrderByAsc added in v1.6.0

func (q *QueryBuilder[T]) OrderByAsc(field string) *QueryBuilder[T]

OrderByAsc adds an ascending ORDER BY clause

func (*QueryBuilder[T]) OrderByDesc added in v1.6.0

func (q *QueryBuilder[T]) OrderByDesc(field string) *QueryBuilder[T]

OrderByDesc adds a descending ORDER BY clause

func (*QueryBuilder[T]) Page added in v1.6.0

func (q *QueryBuilder[T]) Page(page, pageSize int) *QueryBuilder[T]

Page sets both LIMIT and OFFSET for pagination

func (*QueryBuilder[T]) Paginate added in v1.6.0

func (q *QueryBuilder[T]) Paginate(page, pageSize int) ([]*T, int64, error)

Paginate returns paginated results with total count

func (*QueryBuilder[T]) Pluck added in v1.6.0

func (q *QueryBuilder[T]) Pluck(column string, dest interface{}) error

Pluck retrieves a single column as a slice

func (*QueryBuilder[T]) Preload added in v1.6.0

func (q *QueryBuilder[T]) Preload(associations ...string) *QueryBuilder[T]

Preload adds a PRELOAD clause for eager loading associations

func (*QueryBuilder[T]) Raw added in v1.6.0

func (q *QueryBuilder[T]) Raw(sql string, values ...interface{}) *QueryBuilder[T]

Raw executes a raw SQL query and returns the result

func (*QueryBuilder[T]) RightJoin added in v1.6.0

func (q *QueryBuilder[T]) RightJoin(table, condition string, args ...interface{}) *QueryBuilder[T]

RightJoin adds a RIGHT JOIN clause

func (*QueryBuilder[T]) Save added in v1.6.0

func (q *QueryBuilder[T]) Save(value *T) error

Save saves the record (insert if not exists, update if exists)

func (*QueryBuilder[T]) Scan added in v1.6.0

func (q *QueryBuilder[T]) Scan(dest interface{}) error

Scan executes the query and scans the result into the provided destination

func (*QueryBuilder[T]) Select added in v1.6.0

func (q *QueryBuilder[T]) Select(columns ...string) *QueryBuilder[T]

Select specifies the columns to be selected

func (*QueryBuilder[T]) Sum added in v1.6.0

func (q *QueryBuilder[T]) Sum(field string) (float64, error)

Sum calculates the sum of a field

func (*QueryBuilder[T]) ToSQL added in v1.6.0

func (q *QueryBuilder[T]) ToSQL() (string, error)

ToSQL returns the generated SQL query as a string (for debugging)

func (*QueryBuilder[T]) Transaction added in v1.6.0

func (q *QueryBuilder[T]) Transaction(fn func(tx *QueryBuilder[T]) error) error

Transaction executes a function within a database transaction

func (*QueryBuilder[T]) Update added in v1.6.0

func (q *QueryBuilder[T]) Update(updates map[string]interface{}) error

Update executes the query and updates all matching records

func (*QueryBuilder[T]) UpdateColumn added in v1.6.0

func (q *QueryBuilder[T]) UpdateColumn(updates map[string]interface{}) error

UpdateColumn executes the query and updates specific columns

func (*QueryBuilder[T]) Where added in v1.6.0

func (q *QueryBuilder[T]) Where(field string, value interface{}, opts ...*SetWhereOptions) *QueryBuilder[T]

Where adds a WHERE condition to the query

func (*QueryBuilder[T]) WhereBetween added in v1.6.0

func (q *QueryBuilder[T]) WhereBetween(field string, start, end interface{}) *QueryBuilder[T]

WhereBetween adds a BETWEEN WHERE condition

func (*QueryBuilder[T]) WhereEqual added in v1.6.0

func (q *QueryBuilder[T]) WhereEqual(field string, value interface{}) *QueryBuilder[T]

WhereEqual adds an equality WHERE condition

func (*QueryBuilder[T]) WhereIn added in v1.6.0

func (q *QueryBuilder[T]) WhereIn(field string, values interface{}) *QueryBuilder[T]

WhereIn adds an IN WHERE condition

func (*QueryBuilder[T]) WhereLike added in v1.6.0

func (q *QueryBuilder[T]) WhereLike(field string, value string) *QueryBuilder[T]

WhereLike adds a LIKE WHERE condition

func (*QueryBuilder[T]) WhereNotEqual added in v1.6.0

func (q *QueryBuilder[T]) WhereNotEqual(field string, value interface{}) *QueryBuilder[T]

WhereNotEqual adds a not equal WHERE condition

func (*QueryBuilder[T]) WhereNotIn added in v1.6.0

func (q *QueryBuilder[T]) WhereNotIn(field string, values interface{}) *QueryBuilder[T]

WhereNotIn adds a NOT IN WHERE condition

func (*QueryBuilder[T]) WhereRaw added in v1.6.0

func (q *QueryBuilder[T]) WhereRaw(sql string, args ...interface{}) *QueryBuilder[T]

WhereRaw adds a raw WHERE condition

type RangeMode added in v1.6.1

type RangeMode string

RangeMode defines the type of range query

const (
	// RangeModeClosed represents [A, B] - both inclusive (default)
	RangeModeClosed RangeMode = "closed"
	// RangeModeOpen represents (A, B) - both exclusive
	RangeModeOpen RangeMode = "open"
	// RangeModeLeftClosed represents [A, B) - left inclusive, right exclusive
	RangeModeLeftClosed RangeMode = "left_closed"
	// RangeModeRightClosed represents (A, B] - left exclusive, right inclusive
	RangeModeRightClosed RangeMode = "right_closed"
)

type Service added in v1.0.5

type Service interface {
	Name() string
}

Service is the interface that wraps the basic methods.

type ServiceImpl added in v1.0.5

type ServiceImpl struct {
}

ServiceImpl is the implementation of the Service interface.

func (*ServiceImpl) Name added in v1.0.5

func (s *ServiceImpl) Name() string

Name returns the name of the service.

type SetWhereOptions

type SetWhereOptions struct {
	IsEqual              bool
	IsNotEqual           bool
	IsFuzzy              bool
	IsIn                 bool
	IsNotIn              bool
	IsPlain              bool
	IsRange              bool
	RangeMode            RangeMode // Range mode: closed (default), open, left_closed, right_closed
	IsGreaterThan        bool
	IsLessThan           bool
	IsGreaterOrEqualThan bool
	IsLessOrEqualThan    bool
	IsFullTextSearch     bool
	FullTextSearchFields []string
}

SetWhereOptions is the options for SetWhere.

type UUID added in v1.5.7

type UUID = datatypes.UUID

UUID is a UUID.

type Where

type Where struct {
	Items []WhereOne
	//
	FullTextSearchFields []string
}

Where is the where.

func NewWhere added in v1.6.0

func NewWhere() *Where

NewWhere returns a new where.

func ToWhere added in v1.6.0

func ToWhere[T WhereCondition](condition T) *Where

ToWhere converts a where condition to *Where. If the input is already *Where, return it directly. If the input is map[any]any, convert it to *Where.

func (*Where) Add added in v1.5.1

func (w *Where) Add(key string, value interface{}, opts ...*SetWhereOptions)

Add adds a where, if exists, append.

func (*Where) Build

func (w *Where) Build() (query string, args []interface{}, err error)

Build builds the wheres.

func (*Where) Debug

func (w *Where) Debug()

Debug prints the wheres.

func (*Where) Del added in v1.0.8

func (w *Where) Del(key string)

Del deletes a where.

func (*Where) Get

func (w *Where) Get(key string) (interface{}, bool)

Get gets a where.

func (*Where) Length

func (w *Where) Length() int

Length returns the length of the wheres.

func (*Where) Reset added in v1.3.4

func (w *Where) Reset()

Reset resets the wheres.

func (*Where) Set

func (w *Where) Set(key string, value interface{}, opts ...*SetWhereOptions)

Set sets a where, if exists, update.

type WhereCondition added in v1.6.0

type WhereCondition interface {
	map[any]any | *Where
}

WhereCondition is a type constraint for where conditions. It can be either map[any]any or *Where.

type WhereOne

type WhereOne struct {
	Key   string
	Value interface{}

	// IsEqual => =
	IsEqual bool
	// IsNotEqual => !=
	IsNotEqual bool

	// IsFuzzy => ILike
	IsFuzzy bool

	// IsIn => in (?)
	IsIn bool
	// IsNotIn => not in (?)
	IsNotIn bool

	// IsPlain => plain
	IsPlain bool

	// IsRange => BETWEEN ? AND ? (or other range modes)
	IsRange bool

	// IsGreaterThan => >
	IsGreaterThan bool
	// IsLessThan => <
	IsLessThan bool
	// IsGreaterOrEqualThan => >=
	IsGreaterOrEqualThan bool
	// IsLessOrEqualThan => <=
	IsLessOrEqualThan bool

	// IsFullTextSearch => ILike (field1) OR ILike (field2) OR ...
	IsFullTextSearch     bool
	FullTextSearchFields []string
	// contains filtered or unexported fields
}

WhereOne is the where one.

Directories

Path Synopsis
examples
aggregate command
chain command
where_generic command
where_range command

Jump to

Keyboard shortcuts

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