squery

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2021 License: MIT Imports: 11 Imported by: 0

README

squery Go Reference

Simple SQL query builder in golang.

Documentation

Index

Constants

View Source
const (
	AscendingOrder  = "ASC"
	DescendingOrder = "DESC"
)

Sorting order

Variables

View Source
var (
	MaxLimitPerPage     = int64(500)
	DefaultLimitPerPage = int64(25)
	AllMatchers         = []string{
		sqlLike,
		sqlNotLike,
		sqlILike,
		sqlNotILike,
		sqlSimilarTo,
		sqlNotSimilarTo,
		sqlRegexMatch,
		sqlIRegexMatch,
		sqlNotRegexMatch,
		sqlNotIRegexMatch,
	}
)

filter limit

Functions

func JoinSelectColumns

func JoinSelectColumns(cols []*SelectColumn) string

JoinSelectColumns for SQL building

func MapQuoteField

func MapQuoteField(jsToDbMap map[string]string) func(string) (string, error)

MapQuoteField return quoted DB field

func QuoteSelectField

func QuoteSelectField(jsFields []string, jsToDbMap map[string]string) (string, []string)

QuoteSelectField return quoted DB field

Types

type Builder

type Builder interface {
	Build(sb StringBuilder, ph Placeholder) ([]interface{}, error)
}

type DataList

type DataList struct {
	Success    bool        `json:"success"`
	Total      int64       `json:"total"`
	DataCount  int         `json:"dataCount"`
	Pagination *Pagination `json:"pagination,omitempty"`
	Data       interface{} `json:"data"`
}

DataList for storing many/list query result

type DbColumn added in v0.4.2

type DbColumn struct {
	ColumnExpr string  `json:"columnExpr"`
	Label      string  `json:"label"`
	DataType   *string `json:"dataType"`
}

DbColumn stores DB aliases

type EqFilter

type EqFilter struct {
	Field string      `json:"field"`
	Value interface{} `json:"value"`
}

EqFilter stores query term of "field=$value"

type Error added in v0.3.0

type Error interface {
	Err() error
}

type Expression

type Expression interface {
	Builder
	IsEmpty() bool
}

Expression builder

func NewQueryTermExpression

func NewQueryTermExpression(q *QueryTerm, fulltextCols []string, fm FnMapField) Expression

NewQueryTermExpression convert query term to expression

type ExpressionBuilder

type ExpressionBuilder interface {
	Or(expr1, expr2 Expression, exprs ...Expression) Expression
	And(expr1, expr2 Expression, exprs ...Expression) Expression
	Null(term Term) Expression
	NotNull(term Term) Expression
	Not(expr Expression) Expression
	Eq(term Term, arg interface{}) Expression
	Neq(term Term, arg interface{}) Expression
	Gt(term Term, arg interface{}) Expression
	Gte(term Term, arg interface{}) Expression
	Lt(term Term, arg interface{}) Expression
	Lte(term Term, arg interface{}) Expression
	Like(term Term, arg interface{}) Expression
	ILike(term Term, arg interface{}) Expression
	SimilarTo(term Term, arg interface{}) Expression
	NotLike(term Term, arg interface{}) Expression
	NotILike(term Term, arg interface{}) Expression
	NotSimilarTo(term Term, arg interface{}) Expression
	Between(term Term, arg1, arg2 interface{}) Expression
	In(term Term, args ...interface{}) Expression
	NotIn(term Term, args ...interface{}) Expression
	Raw(query string, args ...interface{}) Expression
}

ExpressionBuilder

var Expr ExpressionBuilder = exprBuilder{}

------------------------------------------------------------------------------------------------

func NewExpressionBuilder

func NewExpressionBuilder() ExpressionBuilder

type Expressions

type Expressions interface {
	Builder
	Expression() Expression
	Set(expr Expression) Expressions
	Or(expr Expression, exprs ...Expression) Expressions
	And(expr Expression, exprs ...Expression) Expressions
}
var FE Expressions = &chainableExpression{}

FE for fluent expression constructor

func NewExpressions

func NewExpressions() Expressions

NewExpressions construct new fluent expression

type F

type F string

F type for sql field

func (F) String

func (f F) String() string

String representation of the field

type FieldMapSelector added in v0.3.0

type FieldMapSelector func(field string, val interface{}) (string, interface{}, bool)

FieldMapSelector to convert map field's to other field, e.g. JSON

type FieldValues added in v0.4.0

type FieldValues map[string]interface{}

FieldValues stores filed: value for db

type FnMapField

type FnMapField func(string) (string, error)

FnMapField functions maps field from one to another

type Functor

type Functor interface {
	Builder
	Func(name string, args ...interface{}) Functor
	Name() string
	Fields() []F
}

type ListSearchArg

type ListSearchArg struct {
	Sorts      SortConditions  `json:"sorts,omitempty"`
	Pagination *Pagination     `json:"pagination,omitempty"`
	Filter     json.RawMessage `json:"filter"`
	Query      *QueryTerm      `json:"query,omitempty"`
	Fields     []string        `json:"fields,omitempty"`
}

ListSearchArg stores params for list searching

func (*ListSearchArg) DefaultPerPage

func (l *ListSearchArg) DefaultPerPage(perPage int64) *ListSearchArg

Default value for pagination

func (*ListSearchArg) IsFilterEmpty

func (l *ListSearchArg) IsFilterEmpty() bool

IsFilterEmpty return true if filter is not set

func (*ListSearchArg) IsFilterSpecified

func (l *ListSearchArg) IsFilterSpecified() bool

IsFilterSpecified return true if Filte has valid json

func (*ListSearchArg) IsZero

func (l *ListSearchArg) IsZero() bool

IsZero return true if object not set

type M

type M string

M mysql escaper

func (M) String added in v0.2.0

func (m M) String() string

type MapSlice added in v0.3.0

type MapSlice []map[string]interface{}

Aiias to slice of map[string]interface{}

type Pagination

type Pagination struct {
	Page        int64   `json:"page"`    // starts from 0
	PerPage     int64   `json:"perPage"` // number of record in one page
	NextPageKey *string `json:"nextPageKey"`
	// contains filtered or unexported fields
}

Pagination of the result

func (*Pagination) Calculate

func (p *Pagination) Calculate(maxPerPage int64)

func (*Pagination) Limit

func (p *Pagination) Limit() int64

Limit return valid number per page

func (*Pagination) Offset

func (p *Pagination) Offset() int64

Offset calculate sql offset (psql)

type Placeholder

type Placeholder interface {
	Next() string
	Position() int
}

Placeholder in sql query, e.g. $1, $2, ?

func NewPsqlPlaceholder

func NewPsqlPlaceholder(initVal ...int) Placeholder

NewPsqlPlaceholder create Postgresql place holder with $ prefix.

func NewQmPlaceholder

func NewQmPlaceholder() Placeholder

NeqQmPlaceholder return placeholder with question mark

type Property added in v0.4.5

type Property struct {
	DefaultLabel    string            `json:"defaultLabel"`
	TranslatedLabel map[string]string `json:"translatedLabel"`
	Value           interface{}       `json:"value"`
	DataType        *string           `json:"dataType"`
}

Property stores meta information for dynamic Json fields.

type Querier added in v0.3.0

type Querier interface {
	Error
	One(ctx context.Context, dest interface{}) error
	OneMap(ctx context.Context, fm FieldMapSelector) (map[string]interface{}, error)
	Many(ctx context.Context, dest interface{}) error
	ManyMap(ctx context.Context, fm FieldMapSelector) (MapSlice, error)
	Count(ctx context.Context) (int64, error)
}

Querier execute query

type QuerierConstructor added in v0.3.0

type QuerierConstructor interface {
	NamedQuery(query string, arg interface{}, hasIn bool, logFields ...interface{}) Querier
	Query(query string, args []interface{}, logFields ...interface{}) Querier
	InQuery(query string, args []interface{}, logFields ...interface{}) Querier
	RebindQuery(query string, args []interface{}, logFields ...interface{}) Querier
	WithSelector(s Selector, logFields ...interface{}) Querier
}

QuerierConstructor is interface for building various querier

func NewQuerierConstructor added in v0.3.0

func NewQuerierConstructor(db *sqlx.DB, log logger.Logger) QuerierConstructor

type Query

type Query interface {
	Selector
	From(name Stringer) Query
	Where(expr Expression) Query
	Having(expr Expression) Query
	Columns(cols ...Stringer) Query
	RawColumns(cols ...string) Query
	Limit(n int64) Query
	Offset(n int64) Query
	One() Query
	OrderBy(clause Stringer) Query
	GroupBy(clause Stringer) Query
}

Query builder

func NewQuery

func NewQuery() Query

NewQuery create query builder

func NewTemplateQuery added in v0.4.0

func NewTemplateQuery(selTpl, cntTpl string, fm FnMapField, fv FieldValues) Query

NewTemplateQuery create query builder

type QueryTerm

type QueryTerm struct {
	Fields  []string `json:"fields,omitempty"`
	Matcher string   `json:"matcher"`
	Term    string   `json:"term"`
}

QueryTErm stores query term with specific operator

func (*QueryTerm) IsEmpty

func (q *QueryTerm) IsEmpty() bool

type R

type R string

R type for Raw query

func (R) Build

func (r R) Build(sb StringBuilder, ph Placeholder) ([]interface{}, error)

func (R) IsEmpty

func (r R) IsEmpty() bool

func (R) String

func (r R) String() string

type Raw

type Raw interface {
	Builder
}

type RefSearchArg

type RefSearchArg struct {
	Target     EqFilter       `json:"target"`
	Sorts      SortConditions `json:"sorts,omitempty"`
	Pagination *Pagination    `json:"pagination,omitempty"`
}

RefSearchArg stores params for ref many

func (*RefSearchArg) IsZero

func (r *RefSearchArg) IsZero() bool

IsZeror return true if object is not initialized yet

type S added in v0.2.0

type S string

S type for string

func (S) String added in v0.2.0

func (s S) String() string

simply cast to string

type SelectColumn

type SelectColumn struct {
	JsonField   string
	SelectField string
	ResultField string
}

SelectColumn definition for column mapping map between json->db->resultfield

func FindResultField

func FindResultField(cols []*SelectColumn, resField string) *SelectColumn

FindResultField in select column array

type Selector added in v0.3.0

type Selector interface {
	Builder
	Select(cols ...Stringer) (string, []interface{}, error)
	RawSelect(cols ...string) (string, []interface{}, error)
	Count() (string, []interface{}, error)
}

type Sort

type Sort struct {
	Fields []string `json:"fields"`
	Order  string   `json:"order"`
}

Sort stores sort information

func (*Sort) Clause

func (s *Sort) Clause(jsToField map[string]string) string

Clause return sorting clause, e.g. created_at ASC

func (*Sort) IsAscending

func (s *Sort) IsAscending() bool

IsAscending return true if the data is sorted in ASCENDING order

func (*Sort) OrderString

func (s *Sort) OrderString() string

OrderString from sort arg

type SortConditions

type SortConditions []*Sort

SortConditions stores list of sort items

func (SortConditions) Clause

func (sc SortConditions) Clause(jsToField map[string]string) string

Convert to order by clause

type SqlExpression

type SqlExpression struct {
	Clause    string        `json:"clause"`
	Args      []interface{} `json:"args"`
	Fields    []string      `json:"fields"`
	SqlFields []string      `json:"sqlFields"`
	// contains filtered or unexported fields
}

SqlExpression includes clause, and args

func (*SqlExpression) Build

func (se *SqlExpression) Build(sb StringBuilder, ph Placeholder) ([]interface{}, error)

Builder interface, so that it can be passed to query

func (*SqlExpression) IsEmpty

func (se *SqlExpression) IsEmpty() bool

type StringBuilder

type StringBuilder interface {
	Stringer
	io.Writer
	Len() int
	WriteByte(c byte) error
	WriteRune(r rune) (int, error)
	WriteString(s string) (int, error)
}

type Stringer

type Stringer interface {
	String() string
}

Stringer interface for given value

func SSliceFrom added in v0.2.0

func SSliceFrom(strSlice []string) []Stringer

SSliceFrom converts string slice to S

type TemplateListSearchArg added in v0.4.0

type TemplateListSearchArg struct {
	ListSearchArg
	FieldValues    FieldValues          `json:"fieldValues"`
	SelectTemplate string               `json:"-"`
	CountTemplate  string               `json:"-"`
	FieldsMap      map[string]string    `json:"-"`
	SelectColsMap  map[string]*DbColumn `json:"-"`
}

func (*TemplateListSearchArg) FieldLabel added in v0.4.2

func (t *TemplateListSearchArg) FieldLabel(jsField string) string

FieldLabel convert JSON Field to label

func (*TemplateListSearchArg) FieldMapper added in v0.4.0

func (t *TemplateListSearchArg) FieldMapper(jsField string) (string, error)

FieldMapper map between JSON field to valid DB fields or snake_cased version

func (*TemplateListSearchArg) FieldsLabels added in v0.4.2

func (t *TemplateListSearchArg) FieldsLabels(fields []string) []string

FieldsLabels convert from fields to label

func (*TemplateListSearchArg) FieldsToColumns added in v0.4.0

func (t *TemplateListSearchArg) FieldsToColumns() []Stringer

func (*TemplateListSearchArg) QueryableFields added in v0.4.2

func (t *TemplateListSearchArg) QueryableFields() []string

QueryableFields return list of

func (*TemplateListSearchArg) SelectColumnsMapper added in v0.4.0

func (t *TemplateListSearchArg) SelectColumnsMapper(jsField string) (Stringer, error)

SelectColumnsMapper map between JSON field to valid DB columns or snake_cased version

type Term

type Term interface {
	Stringer
}

Term in expression

type Tree

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

Tree stores tree structure of expression

func NewExpressionTree

func NewExpressionTree(data []byte, fm FnMapField) (*Tree, error)

NewExpressionTree create filter tree representation from JSON with default key, i.e. "filter"

func (*Tree) Build

func (t *Tree) Build(sb StringBuilder, ph Placeholder) ([]interface{}, error)

Build implement builder interface

func (*Tree) FieldMapper

func (t *Tree) FieldMapper(fm FnMapField) *Tree

Option set generator option

func (*Tree) IsEmpty

func (t *Tree) IsEmpty() bool

IsEmpty return true if the expression tree don't has data

func (*Tree) SqlExpression

func (t *Tree) SqlExpression() *SqlExpression

SqlExpression return sql expression. If this method is called before Build, it will return NULL.

Jump to

Keyboard shortcuts

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