Documentation ¶
Overview ¶
Package goq provides a type-safe and fluent query builder.
Query Construction ¶
You can construct various queries using Goq. All expression structs and interfaces are named as 'XxxExpr' and the Column struct implements basic operators like 'Add', 'Like', 'Between', etc. See the Expr interface for the documentation about these operators.
Collecting Data ¶
A collector collects *sql.Rows fetched from DB into a common data structure like a slice, map, etc.
Available collectors:
Table.ToElem Table.ToSlice Table.ToUniqSlice Table.ToMap Table.ToSliceMap Table.ToUniqSliceMap ToElem ToSlice ToMap ToSliceMap ToRowMap ToRowMapSlice
These collector methods can be used from the query builder. 'Table' in the above list means a table helper (see [TODO: link] for custom query builder).
For example, the following code collects users table records into a 'users' slice and other values into another slice.
b := NewBuilder(db.Dialect()) q := b.Select( b.Users.All(), b.Coalesce(b.Users.NickName, b.Users.Name).As("nick_name"), b.Func("MONTH", b.Users.BirthDay).As("month"), ).From(b.Users) db.Query(q).Collect( b.Users.ToSlice(&users), b.ToSlice(&others), )
The collectors defined in a table helper are called model collector. They collect rows into a model or models. The model collector structs are named 'ModelXxxCollector'. For example, 'Table.ToSlice' returns a ModelSliceCollector.
The collectors defined in a query builder are called generic collector. They collect rows into a generic structure such as a slice of non-model struct. The generic collector structs are named 'XxxCollector'. For example, 'ToSlice' returns a SliceCollector.
Furthermore, collectors are classified into two types: list collector or single collector. A list collector collects rows into a slice or a map of slices. A single collector collects a first row only into a struct or map. You need to pass them to Collect and First methods, respectively.
db.Query(q).Collect(z.Users.ToSlice(&users)) db.Query(q).First(z.Users.ToElem(&user))
Note that we often use 'z' as a variable name of Goq query builder in example code. This name has no special meanings. We use it just because this character rarely duplicates with other common variable names and is easy to identify.
Index ¶
- Constants
- Variables
- func ExecCollectorsForTest(cllcts []Collector, rows [][]interface{}, selects []Selection, ...) error
- func NewInitConf(selects []Selection, colNames []string) *initConf
- type Aliased
- type AnonExpr
- type Builder
- type CaseElseExpr
- func (o *CaseElseExpr) Add(v interface{}) AnonExpr
- func (ce *CaseElseExpr) Apply(q *Query, ctx DBContext)
- func (o *CaseElseExpr) As(alias string) Aliased
- func (o *CaseElseExpr) Asc() Orderer
- func (o *CaseElseExpr) Between(start interface{}, end interface{}) PredExpr
- func (o *CaseElseExpr) Concat(v interface{}) AnonExpr
- func (o *CaseElseExpr) Desc() Orderer
- func (o *CaseElseExpr) Dvd(v interface{}) AnonExpr
- func (o *CaseElseExpr) Eq(v interface{}) PredExpr
- func (o *CaseElseExpr) Gt(v interface{}) PredExpr
- func (o *CaseElseExpr) Gte(v interface{}) PredExpr
- func (o *CaseElseExpr) In(vals interface{}) PredExpr
- func (o *CaseElseExpr) IsNotNull() PredExpr
- func (o *CaseElseExpr) IsNull() PredExpr
- func (o *CaseElseExpr) Like(s string) PredExpr
- func (o *CaseElseExpr) Lt(v interface{}) PredExpr
- func (o *CaseElseExpr) Lte(v interface{}) PredExpr
- func (o *CaseElseExpr) Mlt(v interface{}) AnonExpr
- func (o *CaseElseExpr) Neq(v interface{}) PredExpr
- func (o *CaseElseExpr) NotIn(vals interface{}) PredExpr
- func (o *CaseElseExpr) Ordering() Ordering
- func (o *CaseElseExpr) Sbt(v interface{}) AnonExpr
- func (ce *CaseElseExpr) Selection() Selection
- type CaseExpr
- func (o *CaseExpr) Add(v interface{}) AnonExpr
- func (c *CaseExpr) Apply(q *Query, ctx DBContext)
- func (o *CaseExpr) As(alias string) Aliased
- func (o *CaseExpr) Asc() Orderer
- func (o *CaseExpr) Between(start interface{}, end interface{}) PredExpr
- func (o *CaseExpr) Concat(v interface{}) AnonExpr
- func (o *CaseExpr) Desc() Orderer
- func (o *CaseExpr) Dvd(v interface{}) AnonExpr
- func (c *CaseExpr) Else(v interface{}) *CaseElseExpr
- func (o *CaseExpr) Eq(v interface{}) PredExpr
- func (o *CaseExpr) Gt(v interface{}) PredExpr
- func (o *CaseExpr) Gte(v interface{}) PredExpr
- func (o *CaseExpr) In(vals interface{}) PredExpr
- func (o *CaseExpr) IsNotNull() PredExpr
- func (o *CaseExpr) IsNull() PredExpr
- func (o *CaseExpr) Like(s string) PredExpr
- func (o *CaseExpr) Lt(v interface{}) PredExpr
- func (o *CaseExpr) Lte(v interface{}) PredExpr
- func (o *CaseExpr) Mlt(v interface{}) AnonExpr
- func (o *CaseExpr) Neq(v interface{}) PredExpr
- func (o *CaseExpr) NotIn(vals interface{}) PredExpr
- func (o *CaseExpr) Ordering() Ordering
- func (o *CaseExpr) Sbt(v interface{}) AnonExpr
- func (c *CaseExpr) Selection() Selection
- type Clauses
- type Collector
- type CollectorMaker
- func (cm *CollectorMaker) ToElem(ptr interface{}) *ElemCollector
- func (cm *CollectorMaker) ToMap(ptr interface{}) *MapCollectorMaker
- func (cm *CollectorMaker) ToRowMap(mp *map[string]interface{}) *RowMapCollector
- func (cm *CollectorMaker) ToRowMapSlice(slice *[]map[string]interface{}) *RowMapSliceCollector
- func (cm *CollectorMaker) ToSlice(ptr interface{}) *SliceCollector
- func (cm *CollectorMaker) ToSliceMap(ptr interface{}) *SliceMapCollectorMaker
- type Column
- func (o *Column) Add(v interface{}) AnonExpr
- func (c *Column) Apply(q *Query, ctx DBContext)
- func (o *Column) As(alias string) Aliased
- func (o *Column) Asc() Orderer
- func (o *Column) Between(start interface{}, end interface{}) PredExpr
- func (c *Column) ColumnName() string
- func (o *Column) Concat(v interface{}) AnonExpr
- func (o *Column) Desc() Orderer
- func (o *Column) Dvd(v interface{}) AnonExpr
- func (o *Column) Eq(v interface{}) PredExpr
- func (c *Column) FieldName() string
- func (o *Column) Gt(v interface{}) PredExpr
- func (o *Column) Gte(v interface{}) PredExpr
- func (o *Column) In(vals interface{}) PredExpr
- func (o *Column) IsNotNull() PredExpr
- func (o *Column) IsNull() PredExpr
- func (o *Column) Like(s string) PredExpr
- func (o *Column) Lt(v interface{}) PredExpr
- func (o *Column) Lte(v interface{}) PredExpr
- func (c *Column) Meta() *ColumnMeta
- func (o *Column) Mlt(v interface{}) AnonExpr
- func (o *Column) Neq(v interface{}) PredExpr
- func (o *Column) NotIn(vals interface{}) PredExpr
- func (o *Column) Ordering() Ordering
- func (o *Column) Sbt(v interface{}) AnonExpr
- func (c *Column) Selection() Selection
- func (c *Column) StructName() string
- func (c *Column) TableAlias() string
- func (c *Column) TableName() string
- type ColumnBuilder
- type ColumnList
- type ColumnMaker
- type ColumnMeta
- type DB
- func (d *DB) Begin() (*Tx, error)
- func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
- func (d *DB) Close() error
- func (d *DB) Dialect() dialect.Dialect
- func (d *DB) Exec(query QueryRoot) (sql.Result, error)
- func (d *DB) ExecContext(ctx context.Context, query QueryRoot) (sql.Result, error)
- func (d *DB) Query(query QueryExpr) *Runner
- func (d *DB) QueryContext(ctx context.Context, query QueryExpr) *Runner
- type DBContext
- type Delete
- type DynmTable
- type ElemCollector
- type Expr
- type GroupByClause
- type Insert
- type InsertMaker
- type JoinClause
- type JoinDef
- type JoinDefiner
- type JoinOn
- type JoinType
- type ListCollector
- type MapCollector
- type MapCollectorMaker
- type ModelCollectorMaker
- func (cm *ModelCollectorMaker) ToElem(ptr interface{}) *ModelElemCollector
- func (cm *ModelCollectorMaker) ToMap(ptr interface{}) *ModelMapCollector
- func (cm *ModelCollectorMaker) ToSlice(ptr interface{}) *ModelSliceCollector
- func (cm *ModelCollectorMaker) ToSliceMap(ptr interface{}) *ModelSliceMapCollectorMaker
- func (cm *ModelCollectorMaker) ToUniqSlice(ptr interface{}) *ModelUniqSliceCollector
- func (cm *ModelCollectorMaker) ToUniqSliceMap(ptr interface{}) *ModelUniqSliceMapCollectorMaker
- type ModelElemCollector
- type ModelMapCollector
- type ModelSliceCollector
- type ModelSliceMapCollector
- type ModelSliceMapCollectorMaker
- type ModelUniqSliceCollector
- type ModelUniqSliceMapCollector
- type ModelUniqSliceMapCollectorMaker
- type Order
- type Orderer
- type Ordering
- type PredExpr
- type Query
- type QueryApplier
- type QueryBuilder
- func (b *QueryBuilder) And(preds ...PredExpr) PredExpr
- func (b *QueryBuilder) Avg(exp Expr) AnonExpr
- func (b *QueryBuilder) Case(cases ...*WhenClause) *CaseExpr
- func (b *QueryBuilder) CaseOf(val Expr, cases ...*WhenClause) *CaseExpr
- func (b *QueryBuilder) Coalesce(exp Expr, alt interface{}) AnonExpr
- func (b *QueryBuilder) Col(table, col string) *Column
- func (b *QueryBuilder) Concat(exps ...interface{}) AnonExpr
- func (b *QueryBuilder) Count(exp Expr) AnonExpr
- func (b *QueryBuilder) DeleteFrom(table SchemaTable) *Delete
- func (b *QueryBuilder) Exists(query QueryExpr) PredExpr
- func (b *QueryBuilder) FullJoin(table TableLike) *JoinClause
- func (b *QueryBuilder) Func(name string, args ...interface{}) AnonExpr
- func (b *QueryBuilder) InnerJoin(table TableLike) *JoinClause
- func (b *QueryBuilder) InsertInto(table SchemaTable, cols ...*Column) *InsertMaker
- func (b *QueryBuilder) LeftJoin(table TableLike) *JoinClause
- func (b *QueryBuilder) Max(exp Expr) AnonExpr
- func (b *QueryBuilder) Min(exp Expr) AnonExpr
- func (b *QueryBuilder) Name(name string) *nameExpr
- func (b *QueryBuilder) NotExists(query QueryExpr) PredExpr
- func (b *QueryBuilder) Null() AnonExpr
- func (b *QueryBuilder) Or(preds ...PredExpr) PredExpr
- func (b *QueryBuilder) Parens(exp Expr) AnonExpr
- func (b *QueryBuilder) Query(exp QueryApplier) Query
- func (b *QueryBuilder) Raw(sql string) *RawExpr
- func (b *QueryBuilder) RightJoin(table TableLike) *JoinClause
- func (b *QueryBuilder) Select(exps ...Selectable) SelectClause
- func (b *QueryBuilder) SelectDistinct(exps ...Selectable) SelectClause
- func (b *QueryBuilder) Sum(exp Expr) AnonExpr
- func (b *QueryBuilder) Table(name string) *DynmTable
- func (b *QueryBuilder) Update(table SchemaTable) *UpdateMaker
- func (b *QueryBuilder) Var(v interface{}) AnonExpr
- func (b *QueryBuilder) VarT(v interface{}, typ string) AnonExpr
- func (b *QueryBuilder) When(when interface{}) *WhenClause
- type QueryExpr
- type QueryRoot
- type QueryTable
- type Queryable
- type RawExpr
- func (o *RawExpr) Add(v interface{}) AnonExpr
- func (r *RawExpr) Apply(q *Query, ctx DBContext)
- func (o *RawExpr) As(alias string) Aliased
- func (o *RawExpr) Asc() Orderer
- func (o *RawExpr) Between(start interface{}, end interface{}) PredExpr
- func (o *RawExpr) Concat(v interface{}) AnonExpr
- func (o *RawExpr) Desc() Orderer
- func (o *RawExpr) Dvd(v interface{}) AnonExpr
- func (o *RawExpr) Eq(v interface{}) PredExpr
- func (o *RawExpr) Gt(v interface{}) PredExpr
- func (o *RawExpr) Gte(v interface{}) PredExpr
- func (r *RawExpr) ImplPredExpr()
- func (o *RawExpr) In(vals interface{}) PredExpr
- func (o *RawExpr) IsNotNull() PredExpr
- func (o *RawExpr) IsNull() PredExpr
- func (o *RawExpr) Like(s string) PredExpr
- func (o *RawExpr) Lt(v interface{}) PredExpr
- func (o *RawExpr) Lte(v interface{}) PredExpr
- func (o *RawExpr) Mlt(v interface{}) AnonExpr
- func (o *RawExpr) Neq(v interface{}) PredExpr
- func (o *RawExpr) NotIn(vals interface{}) PredExpr
- func (o *RawExpr) Ordering() Ordering
- func (o *RawExpr) Sbt(v interface{}) AnonExpr
- func (r *RawExpr) Selection() Selection
- type RowMapCollector
- type RowMapSliceCollector
- type Runner
- type SchemaTable
- type SelectClause
- type Selectable
- type Selection
- type SingleCollector
- type SliceCollector
- type SliceMapCollector
- type SliceMapCollectorMaker
- type Table
- type TableLike
- type Tx
- type Update
- type UpdateMaker
- type Values
- type WhenClause
- type Where
Constants ¶
const ( JOIN_INNER = "INNER" JOIN_LEFT = "LEFT OUTER" JOIN_RIGHT = "RIGHT OUTER" JOIN_FULL = "FULL OUTER" )
Join types.
const ( ORDER_ASC = "ASC" ORDER_DESC = "DESC" )
Orders.
Variables ¶
var (
ErrNoRows = errors.New("goq: no rows in result set")
)
Functions ¶
func ExecCollectorsForTest ¶
func ExecCollectorsForTest( cllcts []Collector, rows [][]interface{}, selects []Selection, colNames []string, ) error
ExecCollectorsForTest executes given collectors for given rows and selects. This is used for internal tests and not intended to be used for other purposes.
func NewInitConf ¶
NewInitConf creates a initConf for collectors. This is used internally.
Types ¶
type Aliased ¶
type Aliased interface { Selectable Alias() string }
Aliased is an aliased expression. You cannot operate an aliased expression. For example 'A.Add(B.As("b"))' fails to compile.
type Builder ¶
type Builder struct { *QueryBuilder *CollectorMaker }
Builder provides query builder methods and result collector methods.
func NewBuilder ¶
type CaseElseExpr ¶
type CaseElseExpr struct {
// contains filtered or unexported fields
}
CaseEelseExpr represents a 'CASE' expression with 'ELSE' clause.
func (*CaseElseExpr) Apply ¶
func (ce *CaseElseExpr) Apply(q *Query, ctx DBContext)
func (*CaseElseExpr) Between ¶
func (o *CaseElseExpr) Between(start interface{}, end interface{}) PredExpr
func (*CaseElseExpr) Selection ¶
func (ce *CaseElseExpr) Selection() Selection
type CaseExpr ¶
type CaseExpr struct {
// contains filtered or unexported fields
}
CaseExpr represents a 'CASE' expression without 'ELSE' clause.
func (*CaseExpr) Else ¶
func (c *CaseExpr) Else(v interface{}) *CaseElseExpr
type Clauses ¶
type Clauses interface { QueryExpr // Joins constructs a 'JOIN' clauses. Joins(joins ...JoinDefiner) Clauses // Where constructs a 'WHERE' clause. Where(preds ...PredExpr) Clauses // GroupBy constructs a 'GROUP BY' clasue. GroupBy(exps ...Expr) GroupByClause }
Clauses has 'JOIN', 'WHERE', and 'GROUP BY' clauses. You can call 'WHERE' and 'JOIN' multiple times. All given expressions are appended to the query.
type Collector ¶
type Collector interface {
// contains filtered or unexported methods
}
Collector defines methods to collect query results.
func InitCollectors ¶
InitCollectors initializes collectors. This is used internally.
type CollectorMaker ¶
type CollectorMaker struct{}
CollectorMaker provides methods to create generic collectors.
func NewMaker ¶
func NewMaker() *CollectorMaker
func (*CollectorMaker) ToElem ¶
func (cm *CollectorMaker) ToElem(ptr interface{}) *ElemCollector
ToElem creates an ElemCollector. It scans values into a given struct pointer.
func (*CollectorMaker) ToMap ¶
func (cm *CollectorMaker) ToMap(ptr interface{}) *MapCollectorMaker
ToMap creates a MapCollector maker. To obtain a MapCollector, you need to specify a key using 'By' or 'ByWith'.
db.Query(q).Collect(z.ToMap(&mapOfStruct).By(z.Users.ID))
See https://godoc.org/github.com/ryym/goq#MapCollectorMaker for details.
func (*CollectorMaker) ToRowMap ¶
func (cm *CollectorMaker) ToRowMap(mp *map[string]interface{}) *RowMapCollector
ToRowMap creates a RowMapCollector.
var row map[string]interface{} db.Query(q).Collect(z.ToRowMap(&row))
func (*CollectorMaker) ToRowMapSlice ¶
func (cm *CollectorMaker) ToRowMapSlice(slice *[]map[string]interface{}) *RowMapSliceCollector
ToRowMapSlice creates a RowMapSliceCollector.
var results []map[string]interface{} db.Query(q).Collect(z.ToRowMapSlice(&results))
func (*CollectorMaker) ToSlice ¶
func (cm *CollectorMaker) ToSlice(ptr interface{}) *SliceCollector
ToSlice creates a SliceCollector. It collects rows into a slice of structs.
db.Query(q).Collect(z.ToSlice(&items))
func (*CollectorMaker) ToSliceMap ¶
func (cm *CollectorMaker) ToSliceMap(ptr interface{}) *SliceMapCollectorMaker
ToSliceMap creates a SliceMapCollectorMaker. To obtain a SliceMapCollector, you need to specify a key using 'By' or 'ByWith'.
db.Query(q).Collect(z.ToSliceMap(&mapOfSlicesOfStruct).By(z.Users.ID))
See https://godoc.org/github.com/ryym/goq#SliceMapCollectorMaker for details.
type Column ¶
type Column struct {
// contains filtered or unexported fields
}
Column has data about the column and its table.
func (*Column) ColumnName ¶
func (*Column) Meta ¶
func (c *Column) Meta() *ColumnMeta
func (*Column) StructName ¶
func (*Column) TableAlias ¶
type ColumnBuilder ¶
type ColumnBuilder struct {
// contains filtered or unexported fields
}
func (*ColumnBuilder) Bld ¶
func (cb *ColumnBuilder) Bld() *Column
func (*ColumnBuilder) PK ¶
func (cb *ColumnBuilder) PK() *ColumnBuilder
PK specifies the column is a primary key.
type ColumnList ¶
type ColumnList struct {
// contains filtered or unexported fields
}
ColumnList is a special expression that holds multiple columns. You can pass this to QueryBuilder.Select method. All columns held by this struct will be selected.
func NewColumnList ¶
func NewColumnList(cols []*Column) *ColumnList
func (*ColumnList) Apply ¶
func (el *ColumnList) Apply(q *Query, ctx DBContext)
func (*ColumnList) Columns ¶
func (el *ColumnList) Columns() []*Column
Columns returns the columns as a slice.
func (*ColumnList) Selection ¶
func (el *ColumnList) Selection() Selection
type ColumnMaker ¶
type ColumnMaker struct {
// contains filtered or unexported fields
}
ColumnMaker is a utility to make several columns of the same table easily.
func NewColumnMaker ¶
func NewColumnMaker(structName, tableName string) *ColumnMaker
func (*ColumnMaker) As ¶
func (m *ColumnMaker) As(alias string) *ColumnMaker
func (*ColumnMaker) Col ¶
func (m *ColumnMaker) Col(fieldName, name string) *ColumnBuilder
type ColumnMeta ¶
type ColumnMeta struct { // PK indicates this column is a primary key or not. PK bool }
ColumnMeta is a meta information about a column.
type DB ¶
DB is a database handle which wraps *sql.DB. You can use Goq's query to access a DB instead of raw string SQL.
func Open ¶
Open opens a database. The arguments are passed to the Open method of *sql.DB. See https://golang.org/pkg/database/sql/#Open for details.
func (*DB) Dialect ¶
Dialect returns a dialect.Dialect for this DB. If this DB is not supported primarily, the dialect will be the generic one.
func (*DB) ExecContext ¶
type DBContext ¶
type DBContext interface { Placeholder(typ string, prevArgs []interface{}) string QuoteIdent(v string) string }
DBContext abstructs query syntax differences among RDBs.
type Delete ¶
type Delete struct {
// contains filtered or unexported fields
}
Delete constructs a 'DELETE' statement.
type DynmTable ¶
type DynmTable struct {
// contains filtered or unexported fields
}
func (*DynmTable) ApplyTable ¶
type ElemCollector ¶
type ElemCollector struct {
// contains filtered or unexported fields
}
ElemCollector scans a first row into an arbitrary struct.
func (*ElemCollector) ImplSingleCollector ¶
func (cl *ElemCollector) ImplSingleCollector()
type Expr ¶
type Expr interface { Selectable // Eq does '=' comparison (equal to). Eq(v interface{}) PredExpr // Neq does '<>' comparison (not equal to). Neq(v interface{}) PredExpr // Gt does '>' comparison (greater than). Gt(v interface{}) PredExpr // Gte does '>=' comparison (greater than or equal to). Gte(v interface{}) PredExpr // Lt does '<' comparison (less than). Lt(v interface{}) PredExpr // Lte does '<=' comparison (less than or equal to). Lte(v interface{}) PredExpr // Add does '+' operation (addition). Add(v interface{}) AnonExpr // Sbt does '-' operation (subtraction). Sbt(v interface{}) AnonExpr // Mlt does '*' operation (multiplication). Mlt(v interface{}) AnonExpr // Dvd does '/' operation (division). Dvd(v interface{}) AnonExpr // Concat concats a string by '||'. Concat(s interface{}) AnonExpr // Like does 'LIKE' comparison. // For example, 'Title.Like("I am%")' becomes true if // the 'Title' starts with 'I am'. Like(s string) PredExpr // Between does 'BETWEEN' comparison. Between(start interface{}, end interface{}) PredExpr // In constructs 'IN' comparison. // You must pass a slice or query. // Otherwise a query construction will result in an error. In(valsOrQuery interface{}) PredExpr // IsNull does 'IS NULL' comparison. IsNull() PredExpr // IsNotNull does 'IS NOT NULL' comparison. IsNotNull() PredExpr }
Expr is the interface of expressions that provide basic operators. All expression structs implement this interface.
type GroupByClause ¶
type GroupByClause interface { QueryExpr // Having constructs a 'HAVING' clause. Having(preds ...PredExpr) GroupByClause }
GroupByClause is a 'GROUP BY' clause.
type Insert ¶
type Insert struct {
// contains filtered or unexported fields
}
Insert constructs an 'INSERT' statement.
type InsertMaker ¶
type InsertMaker struct {
// contains filtered or unexported fields
}
InsertMaker constructs Insert struct.
func (*InsertMaker) Values ¶
func (m *InsertMaker) Values(elems ...interface{}) *Insert
Values accepts one or more model structs to be inserted.
func (*InsertMaker) ValuesMap ¶
func (m *InsertMaker) ValuesMap(valsList ...Values) *Insert
ValuesMap accepts one or more value maps to be inserted. If the target columns are specified by QueryBuilder.InsertInto, values of non-target columns are ignored.
type JoinClause ¶
type JoinClause struct {
// contains filtered or unexported fields
}
func (*JoinClause) On ¶
func (jc *JoinClause) On(pred PredExpr) *JoinOn
type JoinDef ¶
type JoinDef struct {
// contains filtered or unexported fields
}
JoinDef defines how to join a table. This uses 'INNER JOIN' by default.
type JoinDefiner ¶
type JoinDefiner interface {
// contains filtered or unexported methods
}
type ListCollector ¶
type ListCollector interface { Collector ImplListCollector() }
ListCollector interface represents a collector which collects rows into a collection data.
type MapCollector ¶
type MapCollector struct {
// contains filtered or unexported fields
}
MapCollector collects rows into a map of struct.
Example:
map[int]JapanName{ 6: JapanName{ Name: "Yamada", Kanji: "山田" }, 43: JapanName{ Name: "Kato", Kanji: "加藤" }, }
func (*MapCollector) ImplListCollector ¶
func (cl *MapCollector) ImplListCollector()
type MapCollectorMaker ¶
type MapCollectorMaker struct {
// contains filtered or unexported fields
}
MapCollectorMaker creates a MapCollector with the given key column.
db.Query(q).Collect(z.ToMap(&mapOfStruct).By(z.Users.ID))
Note that the key column specified by 'By' must be scanned into somewhere. If you do not collect the key column, use 'ByWith' instead. For example, consider this query and structs we will map results to.
query := z.Select(z.Users.ID, z.Users.GivenName, z.Users.FamilyName).From(z.Users)
structs:
type names struct { GivenName string FamilyName string } type idAndNames struct { ID int GivenName string FamilyName string }
Using 'idAndNames', you can collect results like this:
var mp map[int]idAndNames db.Query(query).Collect(z.ToMap(&mp).By(z.Users.ID))
But if you use 'names' struct instead, the code below will panic.
var mp map[int]names db.Query(query).Collect(z.ToMap(&mp).By(z.Users.ID))
This is because the 'z.Users.ID' does not be scanned to any field. To collect results without its key field, you must provide a pointer for the key by 'ByWith'.
var mp map[int]names var userIDStore int db.Query(query).Collect(z.ToMap(&mp).ByWith(&userIDStore, z.Users.ID))
func (*MapCollectorMaker) By ¶
func (m *MapCollectorMaker) By(key Selectable) *MapCollector
func (*MapCollectorMaker) ByWith ¶
func (m *MapCollectorMaker) ByWith(ptr interface{}, key Selectable) *MapCollector
type ModelCollectorMaker ¶
type ModelCollectorMaker struct {
// contains filtered or unexported fields
}
ModelCollectorMaker provides methods to create model collectors. All table helpers generated by Goq embeds this struct.
func NewModelCollectorMaker ¶
func NewModelCollectorMaker(cols []*Column, alias string) *ModelCollectorMaker
func (*ModelCollectorMaker) ToElem ¶
func (cm *ModelCollectorMaker) ToElem(ptr interface{}) *ModelElemCollector
ToElem creates an ModelElemCollector. It scans values into a given model pointer.
db.Query(q).First(z.Users.ToElem(&user))
func (*ModelCollectorMaker) ToMap ¶
func (cm *ModelCollectorMaker) ToMap(ptr interface{}) *ModelMapCollector
ToMap creates a ModelMapCollector. It collects rows into a map of models whose key is a primary key.
db.Query(q).Collect(z.Users.ToMap(&usersMap))
func (*ModelCollectorMaker) ToSlice ¶
func (cm *ModelCollectorMaker) ToSlice(ptr interface{}) *ModelSliceCollector
ToSlice creates a ModelSliceCollector. It collects rows into a slice of models.
db.Query(q).Collect(z.Users.ToSlice(&users))
func (*ModelCollectorMaker) ToSliceMap ¶
func (cm *ModelCollectorMaker) ToSliceMap(ptr interface{}) *ModelSliceMapCollectorMaker
ToSliceMap creates a ModelSliceMapCollectorMaker. To obtain a ModelSliceMapCollector, you need to specify a key using 'By' or 'ByWith'.
db.Query(q).Collect(z.Cties.ToSliceMap(&mapOfCities).By(z.Cities.CountryID))
See https://godoc.org/github.com/ryym/goq#ModelSliceMapCollectorMaker for details.
func (*ModelCollectorMaker) ToUniqSlice ¶
func (cm *ModelCollectorMaker) ToUniqSlice(ptr interface{}) *ModelUniqSliceCollector
ToUniqSlice creates a ModelUniqSliceCollector. It collects rows into a slice of models without duplication.
func (*ModelCollectorMaker) ToUniqSliceMap ¶
func (cm *ModelCollectorMaker) ToUniqSliceMap(ptr interface{}) *ModelUniqSliceMapCollectorMaker
ToUniqSliceMap creates a ModelUniqSliceMapCollectorMaker. To obtain a ModelUniqSliceMapCollector, you need to specify a key using 'By' or 'ByWith'.
db.Query(q).Collect(z.Cities.ToUniqSliceMap(&mapOfUniqCities).By(z.Country.Name))
See https://godoc.org/github.com/ryym/goq#ModelSliceMapCollectorMaker for details.
type ModelElemCollector ¶
type ModelElemCollector struct {
// contains filtered or unexported fields
}
ElemCollector scans a first row into a model struct.
func (*ModelElemCollector) ImplSingleCollector ¶
func (cl *ModelElemCollector) ImplSingleCollector()
type ModelMapCollector ¶
type ModelMapCollector struct {
// contains filtered or unexported fields
}
ModelMapCollector collects rows into a map of models whose key is a primary key.
func (*ModelMapCollector) ImplListCollector ¶
func (cl *ModelMapCollector) ImplListCollector()
type ModelSliceCollector ¶
type ModelSliceCollector struct {
// contains filtered or unexported fields
}
ModelSliceCollector collects rows into a slice of models.
Example:
[]City{ { ID: 8, Name: "Osaka" }, { ID: 12, Name: "Kyoto" }, }
func (*ModelSliceCollector) ImplListCollector ¶
func (cl *ModelSliceCollector) ImplListCollector()
type ModelSliceMapCollector ¶
type ModelSliceMapCollector struct {
// contains filtered or unexported fields
}
ModelSliceMapCollector collects rows into a map of slices.
Example:
map[string][]City{ "Japan": []City{ { ID: 12, Name: "Osaka" }, { ID: 29, Name: "Sapporo" }, }, "Somewhere": []City{ { ID: 242, Name: "Foo" }, { ID: 85, Name: "Bar" }, }, }
func (*ModelSliceMapCollector) ImplListCollector ¶
func (cl *ModelSliceMapCollector) ImplListCollector()
type ModelSliceMapCollectorMaker ¶
type ModelSliceMapCollectorMaker struct {
// contains filtered or unexported fields
}
ModelSliceMapCollectorMaker creates a ModelSliceMapCollector with the given key column. Note that the key column specified by 'By' must be scanned into somewhere. See https://godoc.org/github.com/ryym/goq#MapCollectorMaker for details.
func (*ModelSliceMapCollectorMaker) By ¶
func (m *ModelSliceMapCollectorMaker) By(key Selectable) *ModelSliceMapCollector
func (*ModelSliceMapCollectorMaker) ByWith ¶
func (m *ModelSliceMapCollectorMaker) ByWith(ptr interface{}, key Selectable) *ModelSliceMapCollector
type ModelUniqSliceCollector ¶
type ModelUniqSliceCollector struct {
// contains filtered or unexported fields
}
ModelUniqSliceCollector collects rows into a slice of models uniquely. The uniqueness of a model is determined by its primary key. If the result rows contains multiple rows which have a same primary key, ModelUniqSliceCollector scans the only first row.
Example:
[]City{ { ID: 8, Name: "Osaka" }, { ID: 12, Name: "Kyoto" }, }
func (*ModelUniqSliceCollector) ImplListCollector ¶
func (cl *ModelUniqSliceCollector) ImplListCollector()
type ModelUniqSliceMapCollector ¶
type ModelUniqSliceMapCollector struct {
// contains filtered or unexported fields
}
ModelUniqSliceMapCollector collects rows into a map of slices. Each slice has uniq model structs. The uniqueness of a model is determined by its primary key.
Example:
map[string][]City{ "Japan": []City{ { ID: 12, Name: "Osaka" }, { ID: 29, Name: "Sapporo" }, }, "Somewhere": []City{ { ID: 242, Name: "Foo" }, { ID: 85, Name: "Bar" }, }, }
func (*ModelUniqSliceMapCollector) ImplListCollector ¶
func (cl *ModelUniqSliceMapCollector) ImplListCollector()
type ModelUniqSliceMapCollectorMaker ¶
type ModelUniqSliceMapCollectorMaker struct {
// contains filtered or unexported fields
}
ModelUniqSliceMapCollectorMaker creates a ModelUniqSliceMapCollector with the given key column. Note that the key column specified by 'By' must be scanned into somewhere. See https://godoc.org/github.com/ryym/goq#MapCollectorMaker for details.
func (*ModelUniqSliceMapCollectorMaker) By ¶
func (m *ModelUniqSliceMapCollectorMaker) By(key Selectable) *ModelUniqSliceMapCollector
func (*ModelUniqSliceMapCollectorMaker) ByWith ¶
func (m *ModelUniqSliceMapCollectorMaker) ByWith(ptr interface{}, key Selectable) *ModelUniqSliceMapCollector
type Orderer ¶
type Orderer interface {
Ordering() Ordering
}
Orderer is the interface of expressions for 'ORDER BY'.
type Ordering ¶
type Ordering struct {
// contains filtered or unexported fields
}
Ordering is a combination of an expression and an order.
type PredExpr ¶
type PredExpr interface { AnonExpr ImplPredExpr() }
PredExpr represents a predicate expression. Some clauses like 'WHERE' or 'ON' accept predicate expressions only.
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query is a result query constructed by the query builder. You can use this to run a query using Go's sql.DB.
q, _ := query.Construct() db, _ := sql.Open("postgres", conn) db.Query(q.Query(), q.Args()...)
func (*Query) Err ¶
Err returns an error occurred during the query construction. The error contains one or more error messages joined by '|'.
type QueryApplier ¶
QueryApplier is the interface to append query parts. All query part structs implement this.
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder is a core query builder. It provides basic clauses and operators.
func NewQueryBuilder ¶
func NewQueryBuilder(dl dialect.Dialect) *QueryBuilder
func (*QueryBuilder) And ¶
func (b *QueryBuilder) And(preds ...PredExpr) PredExpr
And concatenates all the given predicates by 'AND'.
func (*QueryBuilder) Avg ¶
func (b *QueryBuilder) Avg(exp Expr) AnonExpr
Avg gets an average value of the expression by 'AVG'.
func (*QueryBuilder) Case ¶
func (b *QueryBuilder) Case(cases ...*WhenClause) *CaseExpr
Case constructs a 'CASE' expression.
z := goq.NewQueryBuilder(dialect.Generic()) age := z.Col("users", "age") q := z.Case( z.When(age.Lt(20)).Then("under20"), z.When(age.Lt(40)).Then("under40"), ).Else("above40")
SQL:
CASE WHEN users.age > 20 THEN 'under20' WHEN users.age > 40 THEN 'under40' ELSE 'above40' END
func (*QueryBuilder) CaseOf ¶
func (b *QueryBuilder) CaseOf(val Expr, cases ...*WhenClause) *CaseExpr
CaseOf constructs a 'CASE' expression for the value.
z := goq.NewQueryBuilder(dialect.Generic()) id := z.Col("users", "id") q := z.CaseOf(id, z.When(1).Then("one"), z.When(2).Then("two"), ).Else("other")
SQL:
CASE users.id WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'other' END
func (*QueryBuilder) Coalesce ¶
func (b *QueryBuilder) Coalesce(exp Expr, alt interface{}) AnonExpr
Coalesce sets an alternative value for 'NULL' by 'COALESCE'.
func (*QueryBuilder) Col ¶
func (b *QueryBuilder) Col(table, col string) *Column
Col creates a column expression dynamically.
func (*QueryBuilder) Concat ¶
func (b *QueryBuilder) Concat(exps ...interface{}) AnonExpr
Concat is a 'CONCAT' function.
func (*QueryBuilder) Count ¶
func (b *QueryBuilder) Count(exp Expr) AnonExpr
Count counts the expression by 'COUNT'.
func (*QueryBuilder) DeleteFrom ¶
func (b *QueryBuilder) DeleteFrom(table SchemaTable) *Delete
DeleteFrom constructs a 'DELETE' statement.
func (*QueryBuilder) Exists ¶
func (b *QueryBuilder) Exists(query QueryExpr) PredExpr
Exists constructs an 'EXISTS' predicate by the given query.
func (*QueryBuilder) FullJoin ¶
func (b *QueryBuilder) FullJoin(table TableLike) *JoinClause
FullJoin constructs an 'FULL OUTER JOIN' clause.
func (*QueryBuilder) Func ¶
func (b *QueryBuilder) Func(name string, args ...interface{}) AnonExpr
Func creates a function with its name and the arguments.
func (*QueryBuilder) InnerJoin ¶
func (b *QueryBuilder) InnerJoin(table TableLike) *JoinClause
InnerJoin constructs an 'INNER JOIN' clause.
func (*QueryBuilder) InsertInto ¶
func (b *QueryBuilder) InsertInto(table SchemaTable, cols ...*Column) *InsertMaker
InsertInto constructs an 'INSERT' statement. If the 'cols' are omitted, all columns of the table are set.
func (*QueryBuilder) LeftJoin ¶
func (b *QueryBuilder) LeftJoin(table TableLike) *JoinClause
LeftJoin constructs an 'LEFT OUTER JOIN' clause.
func (*QueryBuilder) Max ¶
func (b *QueryBuilder) Max(exp Expr) AnonExpr
Max gets a maximum value of the expression by 'MAX'.
func (*QueryBuilder) Min ¶
func (b *QueryBuilder) Min(exp Expr) AnonExpr
Min gets a minimum value of the expression by 'MIN'.
func (*QueryBuilder) Name ¶
func (b *QueryBuilder) Name(name string) *nameExpr
Name is used to an alias for some expression. You can use this in 'ORDER BY' to use the alias of expression in 'SELECT' clause.
func (*QueryBuilder) NotExists ¶
func (b *QueryBuilder) NotExists(query QueryExpr) PredExpr
NotExists constructs an 'NOT EXISTS' predicate by the given query.
func (*QueryBuilder) Null ¶
func (b *QueryBuilder) Null() AnonExpr
func (*QueryBuilder) Or ¶
func (b *QueryBuilder) Or(preds ...PredExpr) PredExpr
Or concatenates all the given predicates by 'OR'.
func (*QueryBuilder) Parens ¶
func (b *QueryBuilder) Parens(exp Expr) AnonExpr
Parens surrounds the given expression by parentheses.
func (*QueryBuilder) Query ¶
func (b *QueryBuilder) Query(exp QueryApplier) Query
Query constructs a Query from the given expression.
z := goq.NewQueryBuilder(dialect.Generic()) q := z.Query(z.Var(1).Add(z.Var(40))) fmt.Println(q.String())
func (*QueryBuilder) Raw ¶
func (b *QueryBuilder) Raw(sql string) *RawExpr
Raw constructs a raw expression. The given string will be embedded to the query without any filterings.
func (*QueryBuilder) RightJoin ¶
func (b *QueryBuilder) RightJoin(table TableLike) *JoinClause
RightJoin constructs an 'RIGHT OUTER JOIN' clause.
func (*QueryBuilder) Select ¶
func (b *QueryBuilder) Select(exps ...Selectable) SelectClause
Select constructs a 'SELECT' clause.
func (*QueryBuilder) SelectDistinct ¶
func (b *QueryBuilder) SelectDistinct(exps ...Selectable) SelectClause
SelectDistinct constructs a 'SELECT' clause with 'DISTINCT'.
func (*QueryBuilder) Sum ¶
func (b *QueryBuilder) Sum(exp Expr) AnonExpr
Sum gets a total sum of the expression by 'SUM'.
func (*QueryBuilder) Table ¶
func (b *QueryBuilder) Table(name string) *DynmTable
Table creates a table name dynamically.
func (*QueryBuilder) Update ¶
func (b *QueryBuilder) Update(table SchemaTable) *UpdateMaker
Update constructs an 'UPDATE' statement.
func (*QueryBuilder) Var ¶
func (b *QueryBuilder) Var(v interface{}) AnonExpr
Var is a variable for the query. This will be replaced by a placeholder and the value will be stored as an argument for the query.
func (*QueryBuilder) VarT ¶
func (b *QueryBuilder) VarT(v interface{}, typ string) AnonExpr
VarT is a variable with the type. PostgreSQL requires a type of placeholder in some situation.
func (*QueryBuilder) When ¶
func (b *QueryBuilder) When(when interface{}) *WhenClause
When is a 'WHEN' clause for a 'CASE' expression.
type QueryExpr ¶
type QueryExpr interface { Expr QueryRoot // Select overrides the selections. Select(exps ...Selectable) Clauses // As gives an alias to the query. As(alias string) QueryTable // Selections lists selected data. Selections() []Selection // OrderBy adds 'ORDER BY' clause. OrderBy(ords ...Orderer) QueryExpr // Limit adds 'LIMIT' clause. Limit(n int) QueryExpr // Offset adds 'OFFSET' clause. Offset(n int) QueryExpr // WithLimits copy this QueryExpr shallowly and set 'LIMIT' and 'OFFSET'. WithLimits(limit, offset int) QueryExpr }
QueryExpr is the interface of a query to select data.
type QueryRoot ¶
QueryRoot is the interface of query statements such as 'SELECT', 'CREATE', 'UPDATE', and so on.
type QueryTable ¶
type QueryTable interface { Selectable TableLike }
QueryTable represents a query as a table.
type Queryable ¶
type Queryable interface {
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
}
Queryable represents an interface to issue an query. Builtin *sql.DB implements this interface.
type RawExpr ¶
type RawExpr struct {
// contains filtered or unexported fields
}
RawExpr is a raw string expression.
type RowMapCollector ¶
type RowMapCollector struct {
// contains filtered or unexported fields
}
RowMapCollector scans a first row into a map.
map[string]interface{ "user_id": 30, "name": "alice" }
The keys of map are column name and values are row vlaues. So you can scan a row without defining a struct for it. But be careful, this scans values wihtout any conversions. Also result value types may be different by RDB. For example, if you scan an integer value '12' named 'id' from MySQL, the result map will be '{ "id": []uint8{49, 50} }', not '{ "id": 12 }'. This is because the MySQL driver returns '12' as bytes of UTF-8. However, the PostgreSQL driver returns '12' as an int64 value.
func (*RowMapCollector) ImplSingleCollector ¶
func (cl *RowMapCollector) ImplSingleCollector()
type RowMapSliceCollector ¶
type RowMapSliceCollector struct {
// contains filtered or unexported fields
}
RowMapSliceCollector collects rows into a slice of maps.
[]map[string]interface{}{ { "user_id": 30, "name": "alice" }, { "user_id": 31, "name": "bob" }, }
But be careful, this collector collects values without any conversions. See https://godoc.org/github.com/ryym/goq#RowMapCollector for details.
func (*RowMapSliceCollector) ImplListCollector ¶
func (cl *RowMapSliceCollector) ImplListCollector()
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner runs a query with given collectors to collect result rows.
func (*Runner) Collect ¶
func (r *Runner) Collect(collectors ...ListCollector) error
First executes given list collectors.
func (*Runner) First ¶
func (r *Runner) First(collectors ...SingleCollector) error
First executes given single collectors.
type SchemaTable ¶
type SchemaTable interface { TableLike // All constructs the column list expression that has all columns. All() *ColumnList // Except constructs the column list expression that has all columns except columns you specify. Except(cols ...*Column) *ColumnList }
SchemaTable represents a database table.
type SelectClause ¶
type SelectClause interface { QueryExpr // From constructs a 'FROM' clause. From(table TableLike, tables ...TableLike) Clauses }
SelectClause is a 'SELECT' clause.
type Selectable ¶
type Selectable interface { QueryApplier Selection() Selection }
Selectable represents a selectable expression. QueryBuilder.Select accepts values that implement this interface.
type Selection ¶
type Selection struct { Alias string ColumnName string TableName string TableAlias string StructName string FieldName string }
Selection provides information about a selected expression.
type SingleCollector ¶
type SingleCollector interface { Collector ImplSingleCollector() }
SingleCollector interface represents a collector which scans a first row.
type SliceCollector ¶
type SliceCollector struct {
// contains filtered or unexported fields
}
SliceCollector collects rows into a slice of structs.
Example:
[]IDs{ { CountryID: 1, CityID: 3, AddressID: 18 }, { CountryID: 1, CityID: 5, AddressID: 224 }, }
func (*SliceCollector) ImplListCollector ¶
func (cl *SliceCollector) ImplListCollector()
type SliceMapCollector ¶
type SliceMapCollector struct {
// contains filtered or unexported fields
}
SliceMapCollector collects rows into a map of slices.
Example:
map[string][]IDs{ "Japan": []IDs{ { CountryID: 1, CityID: 3 }, { CountryID: 1, CityID: 8 }, }, "Somewhere": []IDs{ { CountryID: 2, CityID: 55 }, }, }
func (*SliceMapCollector) ImplListCollector ¶
func (cl *SliceMapCollector) ImplListCollector()
type SliceMapCollectorMaker ¶
type SliceMapCollectorMaker struct {
// contains filtered or unexported fields
}
SliceMapCollectorMaker creates a SliceMapCollector with the given key column. Note that the key column specified by 'By' must be scanned into somewhere. See https://godoc.org/github.com/ryym/goq#MapCollectorMaker for details.
func (*SliceMapCollectorMaker) By ¶
func (m *SliceMapCollectorMaker) By(key Selectable) *SliceMapCollector
func (*SliceMapCollectorMaker) ByWith ¶
func (m *SliceMapCollectorMaker) ByWith(ptr interface{}, key Selectable) *SliceMapCollector
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
func (*Table) All ¶
func (t *Table) All() *ColumnList
func (*Table) ApplyTable ¶
func (*Table) Except ¶
func (t *Table) Except(excepts ...*Column) *ColumnList
type TableLike ¶
TableLike represents an expression that can be a table. Addition to database tables, aliased queries can also be used for 'FROM' or 'JOIN'. This means a query implements TableLike as well.
type Tx ¶
Tx is an in-progress database transaction which wraps *sql.Tx. You can use Goq's query to access a DB instead of raw string SQL.
type Update ¶
type Update struct {
// contains filtered or unexported fields
}
Update constructs an 'UPDATE' statement.
type UpdateMaker ¶
type UpdateMaker struct {
// contains filtered or unexported fields
}
UpdateMaker constructs Update struct.
func (*UpdateMaker) Elem ¶
func (m *UpdateMaker) Elem(elem interface{}, cols ...*Column) *Update
Elem accepts an model. If the 'cols' are specified, only the fields corresponding to these columns are updated.
type WhenClause ¶
type WhenClause struct {
// contains filtered or unexported fields
}
WhenClause constructs a 'WHEN' clause used for case expressions.
func (*WhenClause) Then ¶
func (w *WhenClause) Then(then interface{}) *WhenClause
Source Files ¶
- builder.go
- case.go
- clauses.go
- collector.go
- column.go
- db.go
- delete.go
- elem.go
- errors.go
- exprs.go
- goq.go
- insert.go
- joins.go
- maker.go
- map.go
- modelElem.go
- modelMap.go
- modelSlice.go
- modelSliceMap.go
- modelUniqSlice.go
- modelUniqSliceMap.go
- op_between.go
- op_logical.go
- op_xfix.go
- ops.go
- query.go
- querybuilder.go
- rowMap.go
- rowMapSlice.go
- runner.go
- slice.go
- sliceMap.go
- table.go
- types.go
- update.go
- util.go
- where.go
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
goq
Goq generate a custom query builder containing table helpers for your models.
|
Goq generate a custom query builder containing table helpers for your models. |
Package dialect defines some dialects per RDB.
|
Package dialect defines some dialects per RDB. |
Package gen provides a method to generate custom query builder.
|
Package gen provides a method to generate custom query builder. |
Package util is an internal utility.
|
Package util is an internal utility. |