db_utils

package
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2025 License: MIT Imports: 11 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetDBFieldMap

func GetDBFieldMap(input any) map[string]string

func GetGormTableName added in v0.4.4

func GetGormTableName(db *gorm.DB, model interface{}) (string, error)

GetGormTableName возвращает имя таблицы для модели: если TableName() реализован — используется он, иначе — имя, сгенерированное GORM.

func ReleaseConditionsMap added in v0.3.5

func ReleaseConditionsMap(cm ConditionsMap)

Вернуть ConditionsMap в пул

func ReleaseQueryCondition added in v0.3.5

func ReleaseQueryCondition(qc *QueryCondition)

Вернуть QueryCondition в пул

Types

type ConditionsMap

type ConditionsMap map[string]*QueryCondition

Основные типы остаются прежними

func AcquireConditionsMap added in v0.3.5

func AcquireConditionsMap() ConditionsMap

Получить ConditionsMap из пула

func MergeConditions added in v0.3.3

func MergeConditions(m1, m2 ConditionsMap, keyForM1 string) ConditionsMap

Остальные методы остаются прежними но с небольшими оптимизациями

func NewConditionsMap

func NewConditionsMap() ConditionsMap

func (ConditionsMap) AddCondition

func (cm ConditionsMap) AddCondition(key string, condition *QueryCondition) ConditionsMap

func (ConditionsMap) Clone added in v0.3.5

func (cm ConditionsMap) Clone() ConditionsMap

Оптимизированное клонирование с использованием пулов

func (ConditionsMap) Release added in v0.3.5

func (cm ConditionsMap) Release()

Метод для освобождения всех ресурсов

func (ConditionsMap) Remove

func (cm ConditionsMap) Remove(key string) (*QueryCondition, bool)

func (ConditionsMap) Update

func (cm ConditionsMap) Update(key string, operator sql_enum.QueryOperator, value ...interface{}) ConditionsMap

func (ConditionsMap) UpdateRequired

func (cm ConditionsMap) UpdateRequired(key string, required bool) (ConditionsMap, bool)

func (ConditionsMap) UpdateRequiredWithPanic

func (cm ConditionsMap) UpdateRequiredWithPanic(key string, required bool) ConditionsMap

type DefaultSortStrategy added in v0.4.4

type DefaultSortStrategy struct{}

func (*DefaultSortStrategy) ApplySort added in v0.4.4

func (s *DefaultSortStrategy) ApplySort(db *gorm.DB, field, direction string) *gorm.DB

func (*DefaultSortStrategy) Supports added in v0.4.4

func (s *DefaultSortStrategy) Supports(field string) bool

type EntityInfo added in v0.4.4

type EntityInfo struct {
	TableName      string
	FieldInfoMap   map[string]*FieldInfo
	Conditions     ConditionsMap
	SortableFields []string
}

func GenerateConditionsFor

func GenerateConditionsFor[T any](db *gorm.DB) *EntityInfo

func GenerateConditionsFromEntity

func GenerateConditionsFromEntity(entity interface{}, db *gorm.DB) *EntityInfo

func NewEntityInfo added in v0.4.4

func NewEntityInfo(tableName string) *EntityInfo

type FieldInfo added in v0.4.4

type FieldInfo struct {
	ExTableName string
	In          string
	Ex          string
	Paths       []string
}

type PaginatedResult

type PaginatedResult[T any] struct {
	Items      []*T  `json:"items"`
	Total      int64 `json:"total"`
	Page       int   `json:"page"`
	Size       int   `json:"size"`
	TotalPages int   `json:"totalPages"`
}

type Pagination

type Pagination struct {
	Page   int
	Limit  int
	Offset int
}

func NewPagination

func NewPagination(page, size int) *Pagination

type PreloadCondition

type PreloadCondition struct {
	QueryParam   string // Название параметра в запросе (например "no_child")
	PreloadName  string // Название прелоада (например "Children")
	DefaultValue bool   // Значение по умолчанию, если параметр не указан
	Invert       bool   // Если true, то прелоад включается когда false
}

type QueryCondition

type QueryCondition struct {
	Field            string
	Operator         sql_enum.QueryOperator
	Value            interface{}
	Required         bool
	Transformer      utils.ValueTransformer
	UniqueIdentifier bool
}

func AcquireQueryCondition added in v0.3.5

func AcquireQueryCondition() *QueryCondition

Получить QueryCondition из пула

func (*QueryCondition) Clone added in v0.3.5

func (q *QueryCondition) Clone() *QueryCondition

Копирование QueryCondition из пула

func (*QueryCondition) SetValue

func (q *QueryCondition) SetValue(stringValues ...string) error

type QueryOptions

type QueryOptions struct {
	Conditions     ConditionsMap
	Preloads       []string
	Sort           *SortOption
	Pagination     *Pagination // Используем указатель для optional параметра
	SortStrategies []SortStrategy
}

func DefaultQueryOptions

func DefaultQueryOptions() *QueryOptions

func (*QueryOptions) AddNewStrategy added in v0.4.4

func (opts *QueryOptions) AddNewStrategy(info *EntityInfo)

func (*QueryOptions) AddSortStrategy added in v0.4.4

func (opts *QueryOptions) AddSortStrategy(strategy SortStrategy)

func (*QueryOptions) ApplyDefaults

func (opts *QueryOptions) ApplyDefaults() *QueryOptions

func (*QueryOptions) SetSort

func (o *QueryOptions) SetSort(field string, direction string) *QueryOptions

type QueryTag

type QueryTag struct {
	Operators         []sql_enum.QueryOperator // Поддерживаемые операторы
	ParamName         string                   // Имя параметра в запросе
	Consider          bool                     // Учитывать или нет
	UniqueIdentifier  bool                     // Использовать как уникальный идентификатор запроса
	NoSortable        bool
	Path              []string
	ExternalTableName string
	InternalColumn    string
	ExternalColumn    string
	FieldPattern      string
}

type RelatedFieldSortStrategy added in v0.4.4

type RelatedFieldSortStrategy struct {
	FieldPattern string
	JoinClause   string
	OrderClause  string
}

func (*RelatedFieldSortStrategy) ApplySort added in v0.4.4

func (s *RelatedFieldSortStrategy) ApplySort(db *gorm.DB, field, direction string) *gorm.DB

func (*RelatedFieldSortStrategy) Supports added in v0.4.4

func (s *RelatedFieldSortStrategy) Supports(field string) bool

type SortOption

type SortOption struct {
	Field     string
	Direction string // "ASC" или "DESC"
}

func NewSortOption

func NewSortOption(field, direction string) *SortOption

func NewSortOptionWithDefaults

func NewSortOptionWithDefaults() *SortOption

func ParseSortString

func ParseSortString(sortStr string, validFields []string) *SortOption

ParseSortString парсит строку сортировки и валидирует поля

func (*SortOption) GetOrderClause added in v0.4.4

func (o *SortOption) GetOrderClause() string

func (*SortOption) ReplaceFieldIfExists added in v0.4.4

func (s *SortOption) ReplaceFieldIfExists(oldPart, newPart string) *SortOption

ReplaceFieldIfExists заменяет часть поля сортировки, если она присутствует

type SortStrategy added in v0.4.4

type SortStrategy interface {
	ApplySort(db *gorm.DB, field, direction string) *gorm.DB
	Supports(field string) bool
}

func NewSortStrategy added in v0.4.4

func NewSortStrategy(field, tableName string, fi FieldInfo) SortStrategy

Jump to

Keyboard shortcuts

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