dbquery

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

enhanced, tracing enabled database query builder.

Index

Constants

View Source
const (
	ColUpdatedBy = "updated_by"
	ColCreatedBy = "created_by"
	ColTraceId   = "trace_id"
)
View Source
const (
	ErrCodeRecordNotFound = "RECORD_NOT_FOUND"
)

Variables

View Source
var (
	CreatedByExtractor func(rail miso.Rail) string = func(rail miso.Rail) string {
		return rail.Username()
	}

	UpdatedByExtractor func(rail miso.Rail) string = func(rail miso.Rail) string {
		return rail.Username()
	}
)
View Source
var (
	ErrRecordNotFound = errs.NewErrfCode(ErrCodeRecordNotFound, "Record Not Found")
)

Functions

func AddCreateHooks added in v0.3.1

func AddCreateHooks(f func(table string, q *Query, v []map[string]any))

Register hooks for Query.Create, Query.CreateAny and Query.CreateIgnore.

func AddUpdateHooks added in v0.3.1

func AddUpdateHooks(f func(table string, q *Query))

Register hooks for Query.Update and Query.UpdateAny.

func EscapeString added in v0.4.0

func EscapeString(s string) string

Escape String

Acknowledgement: following code is copied from https://github.com/pingcap/tidb/blob/master/pkg/util/sqlescape/utils.go (Copyright 2021 PingCAP, Inc. Apache License)

func ExecSQL added in v0.2.15

func ExecSQL(rail miso.Rail, db *gorm.DB, sql string, args ...any) error

func GetDB added in v0.1.18

func GetDB() *gorm.DB

func ImplGetPrimaryDBFunc added in v0.1.18

func ImplGetPrimaryDBFunc(impl func() *gorm.DB) (implSet bool)

func InitSchema

func InitSchema(rail miso.Rail, initSchemaSegments []string, getDB func() *gorm.DB) error

func InitSchemaConditionally added in v0.1.17

func InitSchemaConditionally(rail miso.Rail, conditionalSegments []ConditionalSchemaSegment, getDB func() *gorm.DB) error

func IterateAllByOffset added in v0.2.6

func IterateAllByOffset[V any, T any](rail miso.Rail, db *gorm.DB, p IterateByOffsetParam[V, T]) error

func NewGormLogger added in v0.2.0

func NewGormLogger(config lg.Config) *gormLogger

func NewQueryFunc added in v0.2.0

func NewQueryFunc(table string, ops ...func(q *Query) *Query) func(r miso.Rail, db *gorm.DB) *Query

func PrepareCreateModelHook added in v0.3.1

func PrepareCreateModelHook(optionalFn ...func(table string) (ok bool))

Prepare Hook that will run when Query call INSERT related methods, see AddCreateHooks and CreateModel.

The created_by and trace_id fields are extracted from trace and CreatedByExtractor, and are automatically set as part of INSERT SQL when you call Query INSERT releated methods.

Arg optionalFn should return whether the hook should run for current table, e.g., some tables may not have the trace_id and created_by fields.

Call this func before miso bootstraps.

func PrepareUpdateModelHook added in v0.3.1

func PrepareUpdateModelHook(optionalFn ...func(table string) (ok bool))

Prepare UpdateModel Hook that will run when Query call UPDATE related methods, see AddUpdateHooks and UpdateModel.

This hook will attempt to extract trace_id and updated_by field from trace (miso.Rail) and UpdatedByExtractor, these fields are then updated to database along with other fields.

Arg optionalFn should return whether the hook should run for current table, e.g., some tables may not have the trace_id and updated_by fields.

By default, hooks are executed for all tables unless optionalFn is provided.

Call this func before miso bootstraps.

func RunTransaction added in v0.2.11

func RunTransaction(rail miso.Rail, db *gorm.DB, callback func(qry func() *Query) error) error

Types

type ChainedPageQuery

type ChainedPageQuery func(q *Query) *Query

type ConditionalSchemaSegment added in v0.1.17

type ConditionalSchemaSegment struct {
	Script    string
	Condition func(*gorm.DB) (ok bool, err error) // considered true if Condition is nil
	AfterExec func(*gorm.DB) error                // can be nil, called when script is executed without error
}

type CreateModel added in v0.3.1

type CreateModel struct {
	CreatedBy string
	TraceId   string
}

CreateModel.

This is for reference only, it's not needed for PrepareCreateModelHook.

type IterateByOffsetParam added in v0.2.6

type IterateByOffsetParam[V, T any] struct {
	Limit         int
	InitialOffset T
	FetchPage     func(rail miso.Rail, db *gorm.DB, offset T) ([]V, error)
	GetOffset     func(v V) T
	ForEach       func(v V) (stop bool, err error)
}

type IteratePageParam added in v0.1.22

type IteratePageParam struct {
	Limit int `json:"limit" desc:"page limit"`
}

type MisoJSONSerializer added in v0.2.10

type MisoJSONSerializer struct {
}

MisoJSONSerializer json serializer

func (MisoJSONSerializer) Scan added in v0.2.10

func (MisoJSONSerializer) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) (err error)

Scan implements serializer interface

func (MisoJSONSerializer) Value added in v0.2.10

func (MisoJSONSerializer) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

Value implements serializer interface

type Nilable

type Nilable interface {
	IsZero() bool
	MarkZero(isZero bool)
}

type NilableValue

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

func (*NilableValue) IsZero

func (n *NilableValue) IsZero() bool

func (*NilableValue) MarkZero

func (n *NilableValue) MarkZero(isZero bool)

type PageQuery

type PageQuery[V any] struct {
	// contains filtered or unexported fields
}

Create param for page query.

func NewPagedQuery

func NewPagedQuery[V any](db *gorm.DB) *PageQuery[V]

func (*PageQuery[V]) IterateAll added in v0.1.22

func (pq *PageQuery[V]) IterateAll(rail miso.Rail, param IteratePageParam, forEach func(v V) (stop bool, err error)) error

func (*PageQuery[V]) IterateAllPages added in v0.2.12

func (pq *PageQuery[V]) IterateAllPages(rail miso.Rail, param IteratePageParam, forEachPage func(v []V) (stop bool, err error)) error

func (*PageQuery[V]) Scan

func (pq *PageQuery[V]) Scan(rail miso.Rail, reqPage miso.Paging) (miso.PageRes[V], error)

func (*PageQuery[V]) Transform

func (pq *PageQuery[V]) Transform(t func(t V) V) *PageQuery[V]

func (*PageQuery[V]) TransformAsync

func (pq *PageQuery[V]) TransformAsync(t func(t V) async.Future[V]) *PageQuery[V]

func (*PageQuery[V]) WithBaseQuery

func (pq *PageQuery[V]) WithBaseQuery(qry ChainedPageQuery) *PageQuery[V]

func (*PageQuery[V]) WithSelectQuery

func (pq *PageQuery[V]) WithSelectQuery(qry ChainedPageQuery) *PageQuery[V]

type Query

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

func NewQuery

func NewQuery(opts ...any) *Query

Create New *Query.

Param opts can be *gorm.DB, miso.Rail or context.Context.

If *gorm.DB is missing, GetDB is called to obtain the primary one.

If miso.Rail or context.Context is provided, tracing baggages (e.g., trace_id, span_id) are automatically propagated to the SQL logger registered in gorm.

func (*Query) And

func (q *Query) And(f func(*Query) *Query) *Query

Add AND (...) condition.

func (*Query) AtPage added in v0.3.2

func (q *Query) AtPage(p miso.Paging) *Query

Add OFFSET and LIMIT for given page.

func (*Query) Between

func (q *Query) Between(col string, a any, b any) *Query

Add BETWEEN ? AND ? condition.

func (*Query) Clauses added in v0.3.1

func (q *Query) Clauses(c ...clause.Expression) *Query

Add gorm clauses.

func (*Query) ColumnName added in v0.2.0

func (q *Query) ColumnName(s string) string

Get column name for given golang field name.

func (*Query) Count added in v0.2.0

func (q *Query) Count() (int64, error)

Run SQL and get COUNT(?) or COUNT(*) result.

func (*Query) Create

func (q *Query) Create(v any) (rowsAffected int64, err error)

Insert given value.

func (*Query) CreateAny added in v0.2.15

func (q *Query) CreateAny(v any) error

Insert given value.

func (*Query) CreateIgnore added in v0.2.0

func (q *Query) CreateIgnore(v any) (rowsAffected int64, err error)

Run CREATE IGNORE to insert given value.

func (*Query) CreateIgnoreAny added in v0.2.15

func (q *Query) CreateIgnoreAny(v any) error

Run CREATE IGNORE to insert given value.

func (*Query) CreateInsertRowMaps added in v0.3.1

func (q *Query) CreateInsertRowMaps(v any) []map[string]any

func (*Query) DB

func (q *Query) DB() *gorm.DB

Get underlying *gorm.DB .

func (*Query) Delete added in v0.2.15

func (q *Query) Delete() (rowsAffected int64, err error)

Exec DELETE.

func (*Query) DeleteAny added in v0.2.15

func (q *Query) DeleteAny() error

Exec DELETE.

func (*Query) Eq

func (q *Query) Eq(col string, args ...any) *Query

=

func (*Query) EqIf

func (q *Query) EqIf(cond bool, col string, args ...any) *Query

=

func (*Query) EqNotEmpty added in v0.1.22

func (q *Query) EqNotEmpty(col string, v any) *Query

=

func (*Query) Exec

func (q *Query) Exec(sql string, args ...any) (rowsAffected int64, err error)

Exec SQL.

func (*Query) ExecAny added in v0.2.15

func (q *Query) ExecAny(sql string, args ...any) error

Exec SQL.

func (*Query) From

func (q *Query) From(table string) *Query

Table.

func (*Query) Ge

func (q *Query) Ge(col string, args ...any) *Query

>=

func (*Query) GeIf

func (q *Query) GeIf(cond bool, col string, args ...any) *Query

>=

func (*Query) Group

func (q *Query) Group(name string) *Query

Add GROUP statement.

func (*Query) Gt

func (q *Query) Gt(col string, args ...any) *Query

>

func (*Query) GtIf

func (q *Query) GtIf(cond bool, col string, args ...any) *Query

>

func (*Query) HasAny added in v0.2.6

func (q *Query) HasAny() (bool, error)

Scan and check if there is any record that matches the specified conditions.

func (*Query) If

func (q *Query) If(cond bool, f func(*Query) *Query) *Query

Run f if cond is true.

func (*Query) In added in v0.2.6

func (q *Query) In(col string, args ...any) *Query

Add IN (...) condition.

func (*Query) IsNotNull

func (q *Query) IsNotNull(col string) *Query

Add IS NOT NULL condition.

func (*Query) IsNull

func (q *Query) IsNull(col string) *Query

Add IS NULL condition.

func (*Query) Join

func (q *Query) Join(query string, args ...any) *Query

Same as Query.Joins.

func (*Query) JoinIf

func (q *Query) JoinIf(addJoin bool, query string, args ...any) *Query

Add JOIN if true.

func (*Query) Joins added in v0.1.22

func (q *Query) Joins(query string, args ...any) *Query

Add JOIN statements.

func (*Query) Le

func (q *Query) Le(col string, args ...any) *Query

<=

func (*Query) LeIf

func (q *Query) LeIf(cond bool, col string, args ...any) *Query

<=

func (*Query) Like

func (q *Query) Like(col string, val string) *Query

LIKE '%?%'

func (*Query) LikeIf

func (q *Query) LikeIf(cond bool, col string, val string) *Query

LIKE '%?%'

func (*Query) LikeLeft

func (q *Query) LikeLeft(col string, val string) *Query

LIKE '%?'

func (*Query) LikeLeftIf

func (q *Query) LikeLeftIf(cond bool, col string, val string) *Query

LIKE '%?'

func (*Query) LikeRight

func (q *Query) LikeRight(col string, val string) *Query

LIKE '?%'

func (*Query) LikeRightIf

func (q *Query) LikeRightIf(cond bool, col string, val string) *Query

LIKE '?%'

func (*Query) Limit

func (q *Query) Limit(n int) *Query

Add LIMIT.

func (*Query) Lt

func (q *Query) Lt(col string, args ...any) *Query

<

func (*Query) LtIf

func (q *Query) LtIf(cond bool, col string, args ...any) *Query

<

func (*Query) Ne

func (q *Query) Ne(col string, args ...any) *Query

!=

func (*Query) NeIf

func (q *Query) NeIf(cond bool, col string, args ...any) *Query

!=

func (*Query) NotIn added in v0.2.6

func (q *Query) NotIn(col string, args ...any) *Query

Add NOT IN (...) condition.

func (*Query) NotLogSQL added in v0.3.3

func (q *Query) NotLogSQL() *Query

Do not log current SQL statement.

func (*Query) Offset

func (q *Query) Offset(n int) *Query

Add OFFSET.

func (*Query) Omit added in v0.2.0

func (q *Query) Omit(col ...string) *Query

Omit columns.

func (*Query) Or

func (q *Query) Or(query string, args ...any) *Query

Add OR (...) condition.

func (*Query) OrFunc

func (q *Query) OrFunc(f func(*Query) *Query) *Query

Add OR (...) condition.

func (*Query) OrIf

func (q *Query) OrIf(cond bool, query string, args ...any) *Query

Add OR (...) condition if true.

func (*Query) Order

func (q *Query) Order(order string) *Query

Add ORDER statement.

func (*Query) OrderAsc added in v0.2.1

func (q *Query) OrderAsc(col string) *Query

Add ORDER BY ? ASC.

func (*Query) OrderDesc added in v0.2.1

func (q *Query) OrderDesc(col string) *Query

Add ORDER BY ? DESC.

func (*Query) Rail added in v0.3.1

func (q *Query) Rail() (miso.Rail, bool)

Obtain Rail in this Query if there is any.

func (*Query) Raw

func (q *Query) Raw(sql string, args ...any) *Query

Add raw SQL.

func (*Query) Scan

func (q *Query) Scan(ptr any) (rowsAffected int64, err error)

Run SQL and scan result.

If ptr is of type Nilable (e.g., by embedding NilableValue), [Nilable.MarkZero] is automatically called based on rowsAffected.

func (*Query) ScanAny added in v0.2.15

func (q *Query) ScanAny(ptr any) (ok bool, err error)

Run SQL and scan result.

If ptr is of type Nilable (e.g., by embedding NilableValue), [Nilable.MarkZero] is automatically called based on rowsAffected.

func (*Query) ScanVal added in v0.2.15

func (q *Query) ScanVal(ptr any) (err error)

Run SQL and scan result.

If ptr is of type Nilable (e.g., by embedding NilableValue), [Nilable.MarkZero] is automatically called based on rowsAffected.

func (*Query) Select

func (q *Query) Select(cols string, args ...any) *Query

Add SELECT statements.

func (*Query) SelectCols added in v0.2.0

func (q *Query) SelectCols(v any) *Query

Add SELECT statements based on the given struct value.

func (*Query) Set

func (q *Query) Set(col string, arg any) *Query

Add SET ? statements.

UPDATE is not exected until one of Query.Update or Query.UpdateAny is called.

func (*Query) SetCols added in v0.2.0

func (q *Query) SetCols(arg any, cols ...string) *Query

Add multiple SET ? statements based on given struct / map value.

UPDATE is not exected until one of Query.Update or Query.UpdateAny is called.

func (*Query) SetColsIgnoreEmpty added in v0.2.12

func (q *Query) SetColsIgnoreEmpty(arg any, cols ...string) *Query

Add multiple SET ? statements based on given struct / map value, ignore empty field.

UPDATE is not exected until one of Query.Update or Query.UpdateAny is called.

func (*Query) SetIf

func (q *Query) SetIf(cond bool, col string, arg any) *Query

Add SET ? statements if true.

UPDATE is not exected until one of Query.Update or Query.UpdateAny is called.

func (*Query) Table

func (q *Query) Table(table string) *Query

Table.

func (*Query) Update

func (q *Query) Update() (rowsAffected int64, err error)

Exec UPDATE SQL.

func (*Query) UpdateAny added in v0.2.15

func (q *Query) UpdateAny() error

Exec UPDATE SQL.

func (*Query) Where

func (q *Query) Where(query string, args ...any) *Query

Add WHERE statement.

func (*Query) WhereFunc

func (q *Query) WhereFunc(f func(*Query) *Query) *Query

func (*Query) WhereIf

func (q *Query) WhereIf(addWhere bool, query string, args ...any) *Query

Add WHERE if true.

func (*Query) WhereNotNil added in v0.1.22

func (q *Query) WhereNotNil(query string, v any) *Query

Add WHERE if v is not nil.

type UpdateModel added in v0.3.1

type UpdateModel struct {
	UpdatedBy string
	TraceId   string
}

UpdateModel.

This is for reference only, it's not needed for PrepareUpdateModelHook.

Jump to

Keyboard shortcuts

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