Documentation
¶
Overview ¶
enhanced, tracing enabled database query builder.
Index ¶
- Constants
- Variables
- func AddCreateHooks(f func(table string, q *Query, v []map[string]any))
- func AddUpdateHooks(f func(table string, q *Query))
- func EscapeString(s string) string
- func ExecSQL(rail miso.Rail, db *gorm.DB, sql string, args ...any) error
- func GetDB() *gorm.DB
- func ImplGetPrimaryDBFunc(impl func() *gorm.DB) (implSet bool)
- func InitSchema(rail miso.Rail, initSchemaSegments []string, getDB func() *gorm.DB) error
- func InitSchemaConditionally(rail miso.Rail, conditionalSegments []ConditionalSchemaSegment, ...) error
- func IterateAll[V any](rail miso.Rail, db *gorm.DB, p IterateAllParam[V]) error
- func IterateAllByOffset[V any, Offset any](rail miso.Rail, db *gorm.DB, p IterateByOffsetParam[V, Offset]) errordeprecated
- func IterateAllByOffset1[V any, Offset any](rail miso.Rail, db *gorm.DB, p IterateByOffset1Param[V, Offset]) error
- func IterateAllByOffset2[V any, Offset1, Offset2 any](rail miso.Rail, db *gorm.DB, p IterateByOffset2Param[V, Offset1, Offset2]) error
- func NewGormLogger(config lg.Config) *gormLogger
- func NewQueryFunc(table string, ops ...func(q *Query) *Query) func(r miso.Rail, db *gorm.DB) *Query
- func PrepareCreateModelHook(optionalFn ...func(table string) (ok bool))
- func PrepareUpdateModelHook(optionalFn ...func(table string) (ok bool))
- func RunTransaction(rail miso.Rail, db *gorm.DB, callback func(qry func() *Query) error) error
- type ChainedPageQuery
- type ConditionalSchemaSegment
- type CreateModel
- type IterateAllParam
- type IterateByOffset1Param
- type IterateByOffset2Param
- type IterateByOffsetParam
- type IteratePageParam
- type MisoJSONSerializer
- type Nilable
- type NilableValue
- type PageQuery
- func (pq *PageQuery[V]) IterateAll(rail miso.Rail, param IteratePageParam, ...) error
- func (pq *PageQuery[V]) IterateAllPages(rail miso.Rail, param IteratePageParam, ...) error
- func (pq *PageQuery[V]) Scan(rail miso.Rail, reqPage miso.Paging) (miso.PageRes[V], error)
- func (pq *PageQuery[V]) Transform(t func(t V) V) *PageQuery[V]
- func (pq *PageQuery[V]) TransformAsync(t func(t V) async.Future[V]) *PageQuery[V]
- func (pq *PageQuery[V]) WithBaseQuery(qry ChainedPageQuery) *PageQuery[V]
- func (pq *PageQuery[V]) WithSelectQuery(qry ChainedPageQuery) *PageQuery[V]
- type Query
- func (q *Query) And(f func(*Query) *Query) *Query
- func (q *Query) AtPage(p miso.Paging) *Query
- func (q *Query) Between(col string, a any, b any) *Query
- func (q *Query) Clauses(c ...clause.Expression) *Query
- func (q *Query) ColumnName(s string) string
- func (q *Query) Count() (int64, error)
- func (q *Query) Create(v any) (rowsAffected int64, err error)
- func (q *Query) CreateAny(v any) error
- func (q *Query) CreateIgnore(v any) (rowsAffected int64, err error)
- func (q *Query) CreateIgnoreAny(v any) error
- func (q *Query) CreateInsertRowMaps(v any) []map[string]any
- func (q *Query) DB() *gorm.DB
- func (q *Query) Delete() (rowsAffected int64, err error)
- func (q *Query) DeleteAny() error
- func (q *Query) Eq(col string, args ...any) *Query
- func (q *Query) EqIf(cond bool, col string, args ...any) *Query
- func (q *Query) EqNotEmpty(col string, v any) *Query
- func (q *Query) Exec(sql string, args ...any) (rowsAffected int64, err error)
- func (q *Query) ExecAny(sql string, args ...any) error
- func (q *Query) From(table string) *Query
- func (q *Query) Ge(col string, args ...any) *Query
- func (q *Query) GeIf(cond bool, col string, args ...any) *Query
- func (q *Query) Group(name string) *Query
- func (q *Query) Gt(col string, args ...any) *Query
- func (q *Query) GtIf(cond bool, col string, args ...any) *Query
- func (q *Query) HasAny() (bool, error)
- func (q *Query) If(cond bool, f func(*Query) *Query) *Query
- func (q *Query) In(col string, args ...any) *Query
- func (q *Query) IsNotNull(col string) *Query
- func (q *Query) IsNull(col string) *Query
- func (q *Query) Join(query string, args ...any) *Query
- func (q *Query) JoinIf(addJoin bool, query string, args ...any) *Query
- func (q *Query) Joins(query string, args ...any) *Query
- func (q *Query) Le(col string, args ...any) *Query
- func (q *Query) LeIf(cond bool, col string, args ...any) *Query
- func (q *Query) Like(col string, val string) *Query
- func (q *Query) LikeIf(cond bool, col string, val string) *Query
- func (q *Query) LikeLeft(col string, val string) *Query
- func (q *Query) LikeLeftIf(cond bool, col string, val string) *Query
- func (q *Query) LikeRight(col string, val string) *Query
- func (q *Query) LikeRightIf(cond bool, col string, val string) *Query
- func (q *Query) Limit(n int) *Query
- func (q *Query) LogSQL() *Query
- func (q *Query) Lt(col string, args ...any) *Query
- func (q *Query) LtIf(cond bool, col string, args ...any) *Query
- func (q *Query) Ne(col string, args ...any) *Query
- func (q *Query) NeIf(cond bool, col string, args ...any) *Query
- func (q *Query) NotIn(col string, args ...any) *Query
- func (q *Query) NotInsertModelFields() *Query
- func (q *Query) NotLogSQL() *Query
- func (q *Query) Offset(n int) *Query
- func (q *Query) Omit(col ...string) *Query
- func (q *Query) Or(query string, args ...any) *Query
- func (q *Query) OrFunc(f func(*Query) *Query) *Query
- func (q *Query) OrIf(cond bool, query string, args ...any) *Query
- func (q *Query) Order(order string) *Query
- func (q *Query) OrderAsc(col string) *Query
- func (q *Query) OrderDesc(col string) *Query
- func (q *Query) Rail() (miso.Rail, bool)
- func (q *Query) Raw(sql string, args ...any) *Query
- func (q *Query) Scan(ptr any) (rowsAffected int64, err error)
- func (q *Query) ScanAny(ptr any) (ok bool, err error)
- func (q *Query) ScanVal(ptr any) (err error)
- func (q *Query) Select(cols string, args ...any) *Query
- func (q *Query) SelectCols(v any) *Query
- func (q *Query) Set(col string, arg any) *Query
- func (q *Query) SetCols(arg any, cols ...string) *Query
- func (q *Query) SetColsIgnoreEmpty(arg any, cols ...string) *Query
- func (q *Query) SetIf(cond bool, col string, arg any) *Query
- func (q *Query) Table(table string) *Query
- func (q *Query) Update() (rowsAffected int64, err error)
- func (q *Query) UpdateAny() error
- func (q *Query) Where(query string, args ...any) *Query
- func (q *Query) WhereFunc(f func(*Query) *Query) *Query
- func (q *Query) WhereIf(addWhere bool, query string, args ...any) *Query
- func (q *Query) WhereNotNil(query string, v any) *Query
- type UpdateModel
Constants ¶
const ( ColUpdatedBy = "updated_by" ColCreatedBy = "created_by" ColTraceId = "trace_id" )
const (
ErrCodeRecordNotFound = "RECORD_NOT_FOUND"
)
Variables ¶
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() } )
var (
ErrRecordNotFound = errs.NewErrfCode(ErrCodeRecordNotFound, "Record Not Found")
)
Functions ¶
func AddCreateHooks ¶ added in v0.3.1
Register hooks for Query.Create, Query.CreateAny and Query.CreateIgnore.
func AddUpdateHooks ¶ added in v0.3.1
Register hooks for Query.Update and Query.UpdateAny.
func EscapeString ¶ added in v0.4.0
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 ImplGetPrimaryDBFunc ¶ added in v0.1.18
func InitSchema ¶
func InitSchemaConditionally ¶ added in v0.1.17
func IterateAll ¶ added in v0.4.6
Iterate all records until none left.
Records should not be matched again in the next iteration once they are processed.
Before looping pages, total count of records matched is checked to prevent infinite loop (just in case some records are never processed properly).
func IterateAllByOffset
deprecated
added in
v0.2.6
func IterateAllByOffset[V any, Offset any](rail miso.Rail, db *gorm.DB, p IterateByOffsetParam[V, Offset]) error
Deprecated: Use IterateAllByOffset1 or IterateAllByOffset2 instead.
func IterateAllByOffset1 ¶ added in v0.4.6
func IterateAllByOffset1[V any, Offset any](rail miso.Rail, db *gorm.DB, p IterateByOffset1Param[V, Offset]) error
Iterate all matched records ordered by column (OffsetCol).
E.g.,
func ListRecords(rail miso.Rail, forEachPage func(v []Record) (err error)) error {
return dbquery.IterateAllByOffset1(rail, GetBI(), dbquery.IterateByOffset2Param[Record, atom.Time]{
OffsetCol: "rec_time",
Limit: 100,
BuildQuery: func(rail miso.Rail, q *dbquery.Query) *dbquery.Query {
return q.Table("my_table").
Eq("my_col", "").
SelectCols(Record{})
},
ForEachPage: func(p []Record) (stop bool, err error) {
return false, forEachPage(p)
},
GetOffset: func(v Record) (atom.Time) {
return v.RecTime
},
})
}
func IterateAllByOffset2 ¶ added in v0.4.6
func IterateAllByOffset2[V any, Offset1, Offset2 any](rail miso.Rail, db *gorm.DB, p IterateByOffset2Param[V, Offset1, Offset2]) error
Iterate all matched records ordered by columns (OffsetCol1, OffsetCol2).
E.g.,
func ListRecords(rail miso.Rail, forEachPage func(v []Record) (err error)) error {
return dbquery.IterateAllByOffset2(rail, GetBI(), dbquery.IterateByOffset2Param[Record, atom.Time, string]{
OffsetCol1: "rec_time",
OffsetCol2: "rec_id",
Limit: 100,
BuildQuery: func(rail miso.Rail, q *dbquery.Query) *dbquery.Query {
return q.Table("my_table").
Eq("my_col", "").
SelectCols(Record{})
},
ForEachPage: func(p []Record) (stop bool, err error) {
return false, forEachPage(p)
},
GetOffset: func(v Record) (atom.Time, string) {
return v.RecTime, v.RecId
},
})
}
func NewGormLogger ¶ added in v0.2.0
func NewQueryFunc ¶ added in v0.2.0
func PrepareCreateModelHook ¶ added in v0.3.1
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
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.
Types ¶
type ChainedPageQuery ¶
type ConditionalSchemaSegment ¶ added in v0.1.17
type CreateModel ¶ added in v0.3.1
CreateModel.
This is for reference only, it's not needed for PrepareCreateModelHook.
type IterateAllParam ¶ added in v0.4.6
type IterateByOffset1Param ¶ added in v0.4.6
type IterateByOffset2Param ¶ added in v0.4.6
type IterateByOffset2Param[V, Offset1, Offset2 any] struct { Limit int // limit, by default 100 OffsetCol1 string // col1 name in ORDER BY (col1, col2) OffsetCol2 string // col2 name in ORDER BY (col1, col2) BuildQuery func(rail miso.Rail, q *Query) *Query GetOffset func(v V) (Offset1, Offset2) ForEachPage func(p []V) (stop bool, err error) }
type IterateByOffsetParam ¶ added in v0.2.6
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
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 (*PageQuery[V]) IterateAll ¶ added in v0.1.22
func (*PageQuery[V]) IterateAllPages ¶ added in v0.2.12
func (*PageQuery[V]) TransformAsync ¶
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 ¶
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) 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
Get column name for given golang field name.
func (*Query) CreateIgnore ¶ added in v0.2.0
Run CREATE IGNORE to insert given value.
func (*Query) CreateIgnoreAny ¶ added in v0.2.15
Run CREATE IGNORE to insert given value.
func (*Query) CreateInsertRowMaps ¶ added in v0.3.1
func (*Query) EqNotEmpty ¶ added in v0.1.22
Equal to if v is not empty string.
func (*Query) HasAny ¶ added in v0.2.6
Scan and check if there is any record that matches the specified conditions.
func (*Query) LikeLeftIf ¶
LIKE '%?'
func (*Query) LikeRightIf ¶
LIKE '?%'
func (*Query) LogSQL ¶ added in v0.4.3
Log current SQL statement.
Query.LogSQL has higher precedence over Query.NotLogSQL.
func (*Query) NotInsertModelFields ¶ added in v0.4.3
Do not automatically insert model fields.
func (*Query) Scan ¶
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
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
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) SelectCols ¶ added in v0.2.0
Add SELECT statements based on the given struct value.
func (*Query) Set ¶
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
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
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 ¶
Add SET ? statements if true.
UPDATE is not exected until one of Query.Update or Query.UpdateAny is called.
type UpdateModel ¶ added in v0.3.1
UpdateModel.
This is for reference only, it's not needed for PrepareUpdateModelHook.