Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples & docs: add examples and docs for Aggregate and Assign #50

Merged
merged 1 commit into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,7 @@
- [Force test and lint in pre-push](https://github.com/gotomicro/eql/pull/35)
- [Insert implementation ](https://github.com/gotomicro/eql/pull/38)
- [Delete implementation ](https://github.com/gotomicro/eql/pull/43)
- [having implementation ](https://github.com/gotomicro/eql/pull/45)
- [having implementation ](https://github.com/gotomicro/eql/pull/45)

### Docs, Lint issues and Examples
- [Add examples and docs for Aggregate and Assign](https://github.com/gotomicro/eql/pull/50)
4 changes: 4 additions & 0 deletions aggregate.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,27 +38,31 @@ func Avg(c string) Aggregate {
}
}

// Max represents MAX
func Max(c string) Aggregate {
return Aggregate{
fn: "MAX",
arg: c,
}
}

// Min represents MIN
func Min(c string) Aggregate {
return Aggregate{
fn: "MIN",
arg: c,
}
}

// Count represents COUNT
func Count(c string) Aggregate {
return Aggregate{
fn: "COUNT",
arg: c,
}
}

// Sum represents SUM
func Sum(c string) Aggregate {
return Aggregate{
fn: "SUM",
Expand Down
50 changes: 44 additions & 6 deletions aggregate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,36 @@
package eql

import (
"github.com/stretchr/testify/assert"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestAggregate(t *testing.T) {
testCases := []CommonTestCase{
{
name: "avg",
name: "avg",
builder: New().Select(Avg("Age")).From(&TestModel{}),
wantSql: "SELECT AVG(`age`) FROM `test_model`;",
},
{
name: "max",
name: "max",
builder: New().Select(Max("Age")).From(&TestModel{}),
wantSql: "SELECT MAX(`age`) FROM `test_model`;",
},
{
name: "min",
name: "min",
builder: New().Select(Min("Age").As("min_age")).From(&TestModel{}),
wantSql: "SELECT MIN(`age`) AS `min_age` FROM `test_model`;",
},
{
name: "sum",
name: "sum",
builder: New().Select(Sum("Age")).From(&TestModel{}),
wantSql: "SELECT SUM(`age`) FROM `test_model`;",
},
{
name: "count",
name: "count",
builder: New().Select(Count("Age")).From(&TestModel{}),
wantSql: "SELECT COUNT(`age`) FROM `test_model`;",
},
Expand All @@ -61,3 +63,39 @@ func TestAggregate(t *testing.T) {
})
}
}

func ExampleAggregate_As() {
query, _ := New().Select(Avg("Age").As("avg_age")).From(&TestModel{}).Build()
fmt.Println(query.SQL)
// Output: SELECT AVG(`age`) AS `avg_age` FROM `test_model`;
}

func ExampleAvg() {
query, _ := New().Select(Avg("Age").As("avg_age")).From(&TestModel{}).Build()
fmt.Println(query.SQL)
// Output: SELECT AVG(`age`) AS `avg_age` FROM `test_model`;
}

func ExampleCount() {
query, _ := New().Select(Count("Age")).From(&TestModel{}).Build()
fmt.Println(query.SQL)
// Output: SELECT COUNT(`age`) FROM `test_model`;
}

func ExampleMax() {
query, _ := New().Select(Max("Age")).From(&TestModel{}).Build()
fmt.Println(query.SQL)
// Output: SELECT MAX(`age`) FROM `test_model`;
}

func ExampleMin() {
query, _ := New().Select(Min("Age")).From(&TestModel{}).Build()
fmt.Println(query.SQL)
// Output: SELECT MIN(`age`) FROM `test_model`;
}

func ExampleSum() {
query, _ := New().Select(Sum("Age")).From(&TestModel{}).Build()
fmt.Println(query.SQL)
// Output: SELECT SUM(`age`) FROM `test_model`;
}
6 changes: 4 additions & 2 deletions assignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@

package eql

// Assignable represents that something could be used as "assignment" statement
type Assignable interface {
assign()
}

// Assignment represents assignment statement
type Assignment binaryExpr

func Assign(column string, value interface{}) Assignment {
Expand All @@ -39,6 +41,6 @@ type valueExpr struct {
val interface{}
}

func (valueExpr) expr() (string, error){
func (valueExpr) expr() (string, error) {
return "", nil
}
}
76 changes: 76 additions & 0 deletions assignment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright 2021 gotomicro
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package eql

import "fmt"

func ExampleAssign() {
db := New()
tm := &TestModel{}
examples := []struct {
assign Assignment
assignStr string
wantSQL string
wantArgs []interface{}
}{
{
assign: Assign("Age", 18),
assignStr: `Assign("Age", 18)`,
wantSQL: "UPDATE `test_model` SET `age`=?;",
wantArgs: []interface{}{18},
},
{
assign: Assign("Age", C("Id")),
assignStr: `Assign("Age", C("Id"))`,
wantSQL: "UPDATE `test_model` SET `age`=`id`;",
},
{
assign: Assign("Age", C("Age").Add(1)),
assignStr: `Assign("Age", C("Age").Add(1))`,
wantSQL: "UPDATE `test_model` SET `age`=`age`+?;",
wantArgs: []interface{}{1},
},
{
assign: Assign("Age", Raw("`age`+`id`+1")),
assignStr: "Assign(\"Age\", Raw(\"`age`+`id`+1\"))",
wantSQL: "UPDATE `test_model` SET `age`=`age`+`id`+1;",
},
}
for _, exp := range examples {
query, _ := db.Update(tm).Set(exp.assign).Build()
fmt.Printf(`
Assignment: %s
SQL: %s
Args: %v
`, exp.assignStr, query.SQL, query.Args)
}
// Output:
//
// Assignment: Assign("Age", 18)
// SQL: UPDATE `test_model` SET `age`=?;
// Args: [18]
//
// Assignment: Assign("Age", C("Id"))
// SQL: UPDATE `test_model` SET `age`=`id`;
// Args: []
//
// Assignment: Assign("Age", C("Age").Add(1))
// SQL: UPDATE `test_model` SET `age`=(`age`+?);
// Args: [1]
//
// Assignment: Assign("Age", Raw("`age`+`id`+1"))
// SQL: UPDATE `test_model` SET `age`=`age`+`id`+1;
// Args: []
}
30 changes: 15 additions & 15 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,36 +44,36 @@ type builder struct {
}

func (b builder) quote(val string) {
b.buffer.WriteByte(b.dialect.quote)
b.buffer.WriteString(val)
b.buffer.WriteByte(b.dialect.quote)
_ = b.buffer.WriteByte(b.dialect.quote)
_, _ = b.buffer.WriteString(val)
_ = b.buffer.WriteByte(b.dialect.quote)
}

func (b builder) space() {
b.buffer.WriteByte(' ')
_ = b.buffer.WriteByte(' ')
}

func (b builder) end() {
b.buffer.WriteByte(';')
_ = b.buffer.WriteByte(';')
}

func (b builder) comma() {
b.buffer.WriteByte(',')
_ = b.buffer.WriteByte(',')
}

func (b *builder) parameter(arg interface{}) {
if b.args == nil {
// TODO 4 may be not a good number
b.args = make([]interface{}, 0, 4)
}
b.buffer.WriteByte('?')
_ = b.buffer.WriteByte('?')
b.args = append(b.args, arg)
}

func (b *builder) buildExpr(expr Expr) error {
switch e := expr.(type) {
case RawExpr:
b.buffer.WriteString(string(e))
_, _ = b.buffer.WriteString(string(e))
case Column:
cm, ok := b.meta.fieldMap[e.name]
if !ok {
Expand Down Expand Up @@ -117,30 +117,30 @@ func (b *builder) buildBinaryExpr(e binaryExpr) error {
if err != nil {
return err
}
b.buffer.WriteString(e.op.text)
_, _ = b.buffer.WriteString(e.op.text)
return b.buildSubExpr(e.right)
}

func (b *builder) buildSubExpr(subExpr Expr) error {
switch r := subExpr.(type) {
case MathExpr:
b.buffer.WriteByte('(')
_ = b.buffer.WriteByte('(')
if err := b.buildBinaryExpr(binaryExpr(r)); err != nil {
return err
}
b.buffer.WriteByte(')')
_ = b.buffer.WriteByte(')')
case binaryExpr:
b.buffer.WriteByte('(')
_ = b.buffer.WriteByte('(')
if err := b.buildBinaryExpr(r); err != nil {
return err
}
b.buffer.WriteByte(')')
_ = b.buffer.WriteByte(')')
case Predicate:
b.buffer.WriteByte('(')
_ = b.buffer.WriteByte('(')
if err := b.buildBinaryExpr(binaryExpr(r)); err != nil {
return err
}
b.buffer.WriteByte(')')
_ = b.buffer.WriteByte(')')
default:
if err := b.buildExpr(r); err != nil {
return err
Expand Down
19 changes: 8 additions & 11 deletions column.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@

package eql

// Column represents column
// it could have alias
// in general, we use it in two ways
// 1. specify the column in query
// 2. it's the start point of building complex expression
type Column struct {
name string
alias string
Expand Down Expand Up @@ -88,6 +93,7 @@ func (c Column) As(alias string) Selectable {
}
}

// Add generate an additive expression
func (c Column) Add(val interface{}) MathExpr {
return MathExpr{
left: c,
Expand All @@ -96,6 +102,7 @@ func (c Column) Add(val interface{}) MathExpr {
}
}

// Multi generate a multiplication expression
func (c Column) Multi(val interface{}) MathExpr {
return MathExpr{
left: c,
Expand Down Expand Up @@ -129,18 +136,8 @@ func (c columns) assign() {
}

// Columns specify columns
func Columns(cs...string) columns {
func Columns(cs ...string) columns {
return columns{
cs: cs,
}
}

func valueOf(val interface{}) Expr {
switch v := val.(type) {
case Expr:
return v
default:
return valueExpr{val: val}
}
}

Loading