Skip to content

Commit 9d0b7b0

Browse files
committed
init
1 parent b6e2b9d commit 9d0b7b0

File tree

3 files changed

+120
-0
lines changed

3 files changed

+120
-0
lines changed

go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/JeffyLu/gormqy
2+
3+
go 1.15

go.sum

Whitespace-only changes.

query.go

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
package gormqy
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
type Column string
9+
type Operator string
10+
type Logic string
11+
type OrderMethod string
12+
13+
const (
14+
OpEq Operator = "="
15+
OpLe Operator = "<="
16+
OpGe Operator = ">="
17+
OpLt Operator = "<"
18+
OpGt Operator = "<"
19+
OpNotEq Operator = "!="
20+
OpLike Operator = "LIKE"
21+
OpIn Operator = "IN"
22+
)
23+
24+
const (
25+
LogicOr Logic = "OR"
26+
LogicAnd Logic = "AND"
27+
)
28+
29+
const (
30+
OrderASC OrderMethod = "ASC"
31+
OrderDesc OrderMethod = "DESC"
32+
)
33+
34+
func Col(col string) Column {
35+
return Column(col)
36+
}
37+
38+
func ConcatCol(cols ...Column) Column {
39+
var cs []string
40+
for _, c := range cols {
41+
cs = append(cs, string(c))
42+
}
43+
return Column(fmt.Sprintf("concat_ws(' | ', %s)", strings.Join(cs, ", ")))
44+
}
45+
46+
type Query struct {
47+
condCols []string
48+
condVals []interface{}
49+
orders []string
50+
limit uint64
51+
}
52+
53+
func (q *Query) OrderExpr() string {
54+
return strings.Join(q.orders, ", ")
55+
}
56+
57+
func (q *Query) WhereExpr() (string, []interface{}) {
58+
if len(q.condCols) == 0 {
59+
return "", nil
60+
}
61+
return strings.Join(q.condCols[:len(q.condCols)-1], " "), q.condVals
62+
}
63+
64+
func (q *Query) LimitExpr() uint64 {
65+
return q.limit
66+
}
67+
68+
func (q *Query) Condition(col Column, op Operator, value interface{}, logic Logic) *Query {
69+
if logic != LogicOr {
70+
logic = LogicAnd
71+
}
72+
var c string
73+
var v interface{}
74+
switch op {
75+
case OpLike:
76+
c = fmt.Sprintf("%s LIKE ?", col)
77+
v = fmt.Sprintf("%%%s%%", value)
78+
case OpIn:
79+
c = fmt.Sprintf("%s IN (?)", col)
80+
default:
81+
c = fmt.Sprintf("%s %s ?", col, op)
82+
}
83+
q.condCols = append(q.condCols, c, string(logic))
84+
q.condVals = append(q.condVals, v)
85+
return q
86+
}
87+
88+
func (q *Query) Order(col Column, method OrderMethod) *Query {
89+
if method != OrderASC {
90+
method = OrderDesc
91+
}
92+
q.orders = append(q.orders, fmt.Sprintf("%s %s", col, method))
93+
return q
94+
}
95+
96+
func (q *Query) Limit(limit uint64) *Query {
97+
q.limit = limit
98+
return q
99+
}
100+
101+
type PageQuery struct {
102+
Query
103+
Page uint
104+
Size uint
105+
Offset uint
106+
}
107+
108+
func (pq *PageQuery) Validate() *PageQuery {
109+
if pq.Size == 0 {
110+
pq.Size = 10
111+
}
112+
if pq.Page == 0 {
113+
pq.Page = 1
114+
}
115+
pq.Offset = (pq.Page - 1) * pq.Size
116+
return pq
117+
}

0 commit comments

Comments
 (0)