qb

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package qb provides SQL query builder utilities for dynamic WHERE/ORDER/GROUP/LIMIT style queries and bulk insert/update/delete statements.

By default package-level helpers keep MySQL-compatible behavior. Use New(...) or *WithDialect helpers to generate SQL for sqlite and postgres. You can also use FromDB(...) with a datasource that exposes Dialect().

JSON helper functions (JsonContains/JsonSet/JsonArrayAppend/JsonArrayInsert/JsonRemove) generate MySQL JSON function syntax.

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrUnsupportedOperator reports there's unsupported operators in where-condition
	ErrUnsupportedOperator = errors.New("[builder] unsupported operator")
)
View Source
var IsZeroType = reflect.TypeOf((*IsZeroer)(nil)).Elem()

Functions

func AggregateAvg

func AggregateAvg(col string) agBuilder

AggregateAvg avg(col)

func AggregateCount

func AggregateCount(col string) agBuilder

AggregateCount count(col)

func AggregateMax

func AggregateMax(col string) agBuilder

AggregateMax max(col)

func AggregateMin

func AggregateMin(col string) agBuilder

AggregateMin min(col)

func AggregateSum

func AggregateSum(col string) agBuilder

AggregateSum sum(col)

func BuildDelete

func BuildDelete(table string, where map[string]interface{}) (string, []interface{}, error)

BuildDelete work as its name says and uses MySQL dialect for backward compatibility.

func BuildDeleteWithDialect

func BuildDeleteWithDialect(dialect, table string, where map[string]interface{}) (string, []interface{}, error)

BuildDeleteWithDialect builds a DELETE query for the given dialect.

func BuildInsert

func BuildInsert(table string, data []map[string]interface{}) (string, []interface{}, error)

BuildInsert work as its name says and uses MySQL dialect for backward compatibility.

func BuildInsertIgnore

func BuildInsertIgnore(table string, data []map[string]interface{}) (string, []interface{}, error)

BuildInsertIgnore work as its name says and uses MySQL dialect for backward compatibility.

func BuildInsertIgnoreWithDialect

func BuildInsertIgnoreWithDialect(dialect, table string, data []map[string]interface{}) (string, []interface{}, error)

BuildInsertIgnoreWithDialect builds an INSERT IGNORE-style query for the given dialect.

func BuildInsertOnDuplicate

func BuildInsertOnDuplicate(table string, data []map[string]interface{}, update map[string]interface{}) (string, []interface{}, error)

BuildInsertOnDuplicate builds an INSERT ... ON DUPLICATE KEY UPDATE clause. This function uses MySQL dialect for backward compatibility.

func BuildInsertOnDuplicateWithDialect

func BuildInsertOnDuplicateWithDialect(dialect, table string, data []map[string]interface{}, update map[string]interface{}) (string, []interface{}, error)

BuildInsertOnDuplicateWithDialect builds an INSERT ... ON DUPLICATE KEY UPDATE query for the given dialect.

func BuildInsertWithDialect

func BuildInsertWithDialect(dialect, table string, data []map[string]interface{}) (string, []interface{}, error)

BuildInsertWithDialect builds an INSERT query for the given dialect.

func BuildReplaceInsert

func BuildReplaceInsert(table string, data []map[string]interface{}) (string, []interface{}, error)

BuildReplaceInsert work as its name says and uses MySQL dialect for backward compatibility.

func BuildReplaceInsertWithDialect

func BuildReplaceInsertWithDialect(dialect, table string, data []map[string]interface{}) (string, []interface{}, error)

BuildReplaceInsertWithDialect builds a REPLACE-style query for the given dialect.

func BuildSelect

func BuildSelect(table string, where map[string]interface{}, selectField []string) (string, []interface{}, error)

BuildSelect works as its name says and uses MySQL dialect for backward compatibility.

func BuildSelectWithDialect

func BuildSelectWithDialect(dialect, table string, where map[string]interface{}, selectField []string) (string, []interface{}, error)

BuildSelectWithDialect builds a SELECT query for the given dialect.

func BuildUpdate

func BuildUpdate(table string, where map[string]interface{}, update map[string]interface{}) (string, []interface{}, error)

BuildUpdate work as its name says and uses MySQL dialect for backward compatibility.

func BuildUpdateWithDialect

func BuildUpdateWithDialect(dialect, table string, where map[string]interface{}, update map[string]interface{}) (string, []interface{}, error)

BuildUpdateWithDialect builds an UPDATE query for the given dialect.

func BuildUpsert

func BuildUpsert(table string, data []map[string]interface{}, conflictColumns []string, update map[string]interface{}) (string, []interface{}, error)

BuildUpsert builds an upsert query using MySQL dialect for backward-compatible defaults.

For MySQL, conflictColumns is ignored and ON DUPLICATE KEY semantics are used. For PostgreSQL and SQLite, conflictColumns is required when update is non-empty.

func BuildUpsertWithDialect

func BuildUpsertWithDialect(dialect, table string, data []map[string]interface{}, conflictColumns []string, update map[string]interface{}) (string, []interface{}, error)

BuildUpsertWithDialect builds an upsert query for the provided dialect.

func NamedQuery

func NamedQuery(sql string, data map[string]interface{}) (string, []interface{}, error)

NamedQuery is used for expressing complex query and uses MySQL placeholders for backward compatibility.

func NamedQueryWithDialect

func NamedQueryWithDialect(dialect, sql string, data map[string]interface{}) (string, []interface{}, error)

NamedQueryWithDialect expands named placeholders using the given dialect placeholder format.

func OmitEmpty

func OmitEmpty(where map[string]interface{}, omitKey []string) map[string]interface{}

OmitEmpty returns a copied map with zero-value keys removed.

Types

type AggregateSymbleBuilder

type AggregateSymbleBuilder interface {
	Symble() string
}

AggregateSymbleBuilder is deprecated, use AggregateSymbolBuilder instead.

type AggregateSymbolBuilder

type AggregateSymbolBuilder interface {
	Symbol() string
}

AggregateSymbolBuilder needs to be implemented so executor can get what should be put into `select Symbol() from xxx where yyy`.

type Between

type Between map[string][]interface{}

func (Between) Build

func (bt Between) Build() ([]string, []interface{})

type Builder

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

Builder builds SQL for a specific dialect.

func FromDB

func FromDB(db DialectProvider) (*Builder, error)

FromDB creates a Builder from a provider that exposes Dialect().

func New

func New(dialect string) (*Builder, error)

New returns a Builder for the provided dialect.

Supported values include:

  • mysql, mariadb
  • postgres, postgresql, supabase, cockroachdb
  • sqlite, sqlite3

func (Builder) AggregateQuery

func (b Builder) AggregateQuery(ctx context.Context, db *sql.DB, table string, where map[string]interface{}, aggregate interface{}) (ResultResolver, error)

AggregateQuery is a helper function to execute the aggregate query and return the result.

func (Builder) BuildDelete

func (b Builder) BuildDelete(table string, where map[string]interface{}) (string, []interface{}, error)

BuildDelete work as its name says.

func (Builder) BuildInsert

func (b Builder) BuildInsert(table string, data []map[string]interface{}) (string, []interface{}, error)

BuildInsert work as its name says.

func (Builder) BuildInsertIgnore

func (b Builder) BuildInsertIgnore(table string, data []map[string]interface{}) (string, []interface{}, error)

BuildInsertIgnore work as its name says.

func (Builder) BuildInsertOnDuplicate

func (b Builder) BuildInsertOnDuplicate(table string, data []map[string]interface{}, update map[string]interface{}) (string, []interface{}, error)

BuildInsertOnDuplicate builds an INSERT ... ON DUPLICATE KEY UPDATE clause.

func (Builder) BuildReplaceInsert

func (b Builder) BuildReplaceInsert(table string, data []map[string]interface{}) (string, []interface{}, error)

BuildReplaceInsert work as its name says.

func (Builder) BuildSelect

func (b Builder) BuildSelect(table string, where map[string]interface{}, selectField []string) (cond string, vals []interface{}, err error)

BuildSelect work as its name says. supported operators including: =,in,>,>=,<,<=,<>,!=. key without operator will be regarded as =. special key begin with _: _orderby,_groupby,_limit,_having. the value of _limit supports int/uint/int64/uint64 and integer slices with one or two elements (ie: []uint{0, 100}). the value of _having must be a map just like where but only support =,in,>,>=,<,<=,<>,!= for more examples,see README.md or open a issue.

func (Builder) BuildUpdate

func (b Builder) BuildUpdate(table string, where map[string]interface{}, update map[string]interface{}) (string, []interface{}, error)

BuildUpdate work as its name says.

func (Builder) BuildUpsert

func (b Builder) BuildUpsert(table string, data []map[string]interface{}, conflictColumns []string, update map[string]interface{}) (string, []interface{}, error)

BuildUpsert builds an upsert query for the current builder dialect.

func (Builder) NamedQuery

func (b Builder) NamedQuery(sql string, data map[string]interface{}) (string, []interface{}, error)

NamedQuery is used for expressing complex query.

type Comparable

type Comparable interface {
	Build() ([]string, []interface{})
}

Comparable requires type implements the Build method

func Custom

func Custom(query string, args ...interface{}) Comparable

func JsonArrayAppend

func JsonArrayAppend(field string, pathAndValuePair ...interface{}) Comparable

JsonArrayAppend generates JSON object args and calls JSON_ARRAY_APPEND.

MySQL only.

usage update := map[string]interface{}{"_custom_xxx": builder.JsonArrayAppend(field, "$", 1, "$[last]", []string{"2","3"}}

func JsonArrayInsert

func JsonArrayInsert(field string, pathAndValuePair ...interface{}) Comparable

JsonArrayInsert generates JSON object args and calls JSON_ARRAY_INSERT to insert at index.

MySQL only.

usage update := map[string]interface{}{"_custom_xxx": builder.JsonArrayInsert(field, "$[0]", 1, "$[0]", []string{"2","3"}}

func JsonContains

func JsonContains(fullJsonPath string, jsonLike interface{}) Comparable

JsonContains checks whether target JSON contains all items in jsonLike.

MySQL only.

notice: fullJsonPath should hard code, never from user input.

func JsonRemove

func JsonRemove(field string, path ...string) Comparable

JsonRemove call MySQL JSON_REMOVE function; remove element from Array or Map path removed in order, prev remove affect the later operation, maybe the array shrink

MySQL only.

remove last array element; update := map[string]interface{}{"_custom_xxx":builder.JsonRemove(field,'$.list[last]')} remove element; update := map[string]interface{}{"_custom_xxx":builder.JsonRemove(field,'$.key0')}

func JsonSet

func JsonSet(field string, pathAndValuePair ...interface{}) Comparable

JsonSet aims to set/update json field values.

MySQL only.

notice: jsonPath should hard code, never from user input;

usage update := map[string]interface{}{"_custom_xxx": builder.JsonSet(field, "$.code", 1, "$.user_info", map[string]any{"name": "", "age": 18})}

type Dialect

type Dialect string

Dialect represents a SQL dialect that qb can generate queries for.

const (
	DialectMySQL    Dialect = "mysql"
	DialectPostgres Dialect = "postgres"
	DialectSQLite   Dialect = "sqlite"
)

type DialectProvider

type DialectProvider interface {
	Dialect() string
}

DialectProvider describes a type that can expose SQL dialect.

type Eq

type Eq map[string]interface{}

Eq means equal(=)

func (Eq) Build

func (e Eq) Build() ([]string, []interface{})

Build implements the Comparable interface

type Gt

type Gt map[string]interface{}

Gt means greater than(>)

func (Gt) Build

func (g Gt) Build() ([]string, []interface{})

Build implements the Comparable interface

type Gte

type Gte map[string]interface{}

Gte means greater than or equal(>=)

func (Gte) Build

func (g Gte) Build() ([]string, []interface{})

Build implements the Comparable interface

type In

type In map[string][]interface{}

In means in

func (In) Build

func (i In) Build() ([]string, []interface{})

Build implements the Comparable interface

type IsZeroer

type IsZeroer interface {
	IsZero() bool
}

type Like

type Like map[string]interface{}

Like means like

func (Like) Build

func (l Like) Build() ([]string, []interface{})

Build implements the Comparable interface

type Lt

type Lt map[string]interface{}

Lt means less than(<)

func (Lt) Build

func (l Lt) Build() ([]string, []interface{})

Build implements the Comparable interface

type Lte

type Lte map[string]interface{}

Lte means less than or equal(<=)

func (Lte) Build

func (l Lte) Build() ([]string, []interface{})

Build implements the Comparable interface

type Ne

type Ne map[string]interface{}

Ne means Not Equal(!=)

func (Ne) Build

func (n Ne) Build() ([]string, []interface{})

Build implements the Comparable interface

type NestWhere

type NestWhere []Comparable

func (NestWhere) Build

func (nw NestWhere) Build() ([]string, []interface{})

type NotBetween

type NotBetween map[string][]interface{}

func (NotBetween) Build

func (nbt NotBetween) Build() ([]string, []interface{})

type NotIn

type NotIn map[string][]interface{}

NotIn means not in

func (NotIn) Build

func (i NotIn) Build() ([]string, []interface{})

Build implements the Comparable interface

type NotLike

type NotLike map[string]interface{}

func (NotLike) Build

func (l NotLike) Build() ([]string, []interface{})

Build implements the Comparable interface

type NullType

type NullType byte

NullType is the NULL type in mysql

const (

	// IsNull the same as `is null`
	IsNull NullType
	// IsNotNull the same as `is not null`
	IsNotNull
)

func (NullType) String

func (nt NullType) String() string

type OrWhere

type OrWhere []Comparable

func (OrWhere) Build

func (ow OrWhere) Build() ([]string, []interface{})

type Raw

type Raw string

type ResultResolver

type ResultResolver interface {
	Int64() int64
	Float64() float64
}

ResultResolver is a helper for retrieving data caller should know the type and call the responding method

func AggregateQuery

func AggregateQuery(ctx context.Context, db *sql.DB, table string, where map[string]interface{}, aggregate interface{}) (ResultResolver, error)

AggregateQuery is a helper function to execute the aggregate query and return the result

func AggregateQueryWithDialect

func AggregateQueryWithDialect(ctx context.Context, db *sql.DB, dialect, table string, where map[string]interface{}, aggregate interface{}) (ResultResolver, error)

AggregateQueryWithDialect executes aggregate query with the provided dialect.

Jump to

Keyboard shortcuts

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