This repository has been archived by the owner on May 30, 2024. It is now read-only.
forked from orus-io/yago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
240 lines (210 loc) · 5.59 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package yago
import (
"database/sql"
"fmt"
"reflect"
"github.com/slicebit/qb"
)
// Query helps querying structs from the database
type Query struct {
db IDB
mapper Mapper
selectStmt qb.SelectStmt
}
// NewQuery creates a new query
func NewQuery(db IDB, mapper Mapper) Query {
return Query{
db: db,
mapper: mapper,
selectStmt: mapper.Table().Select(mapper.FieldList()...),
}
}
// SelectStmt returns the builded SelectStmt
func (q Query) SelectStmt() qb.SelectStmt {
return q.selectStmt
}
// Select redefines the SELECT clauses
func (q Query) Select(clause ...qb.Clause) Query {
q.selectStmt = q.selectStmt.Select(clause...)
return q
}
// Where set the filter clause of the query
func (q Query) Where(clauses ...qb.Clause) Query {
return Query{
db: q.db,
mapper: q.mapper,
selectStmt: q.selectStmt.Where(clauses...),
}
}
// Filter combines the given clauses with the current Where clause of the Query
func (q Query) Filter(clauses ...qb.Clause) Query {
if q.selectStmt.WhereClause == nil {
q.selectStmt = q.selectStmt.Where(clauses...)
} else {
where := q.selectStmt.WhereClause.And(clauses...)
q.selectStmt.WhereClause = &where
}
return q
}
// InnerJoin joins a table
func (q Query) InnerJoin(mp MapperProvider, clause ...qb.Clause) Query {
q.selectStmt = q.selectStmt.InnerJoin(mp.GetMapper().Table(), clause...)
return q
}
// LeftJoin joins a table
func (q Query) LeftJoin(mp MapperProvider, clause ...qb.Clause) Query {
q.selectStmt = q.selectStmt.LeftJoin(mp.GetMapper().Table(), clause...)
return q
}
// RightJoin joins a table
func (q Query) RightJoin(mp MapperProvider, clause ...qb.Clause) Query {
q.selectStmt = q.selectStmt.RightJoin(mp.GetMapper().Table(), clause...)
return q
}
// OrderBy add a ORDER BY clause
func (q Query) OrderBy(clauses ...qb.Clause) Query {
// Right now qb.selectStmt.OrderBy only accepts ColumnElem
var columns []qb.ColumnElem
for _, clause := range clauses {
scalf, ok := clause.(ScalarField)
if ok {
columns = append(columns, scalf.Column)
continue
}
col, ok := clause.(qb.ColumnElem)
if !ok {
panic("OrderBy only accepts ScalarField and qb.ColumnElem arguments")
}
columns = append(columns, col)
}
q.selectStmt = q.selectStmt.OrderBy(columns...)
return q
}
// ForUpdate add a FOR UPDATE clause
func (q Query) ForUpdate(mps ...MapperProvider) Query {
var tables []qb.TableElem
for _, mp := range mps {
tables = append(tables, *mp.GetMapper().Table())
}
q.selectStmt = q.selectStmt.ForUpdate(tables...)
return q
}
// SQLQuery runs the query
func (q Query) SQLQuery() (*sql.Rows, error) {
return q.db.GetEngine().Query(q.selectStmt)
}
// SQLQueryRow runs the query and expects at most one row in the result
func (q Query) SQLQueryRow() qb.Row {
return q.db.GetEngine().QueryRow(q.selectStmt)
}
// One returns one and only one struct from the query.
// If query has no result or more than one, an error is returned
func (q Query) One(s MappedStruct) error {
rows, err := q.SQLQuery()
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return ErrRecordNotFound
}
err = q.mapper.Scan(rows, s)
if err != nil {
return err
}
if rows.Next() {
return ErrMultipleRecords
}
return nil
}
// Get returns a record from its primary key values
func (q Query) Get(s MappedStruct, pkey ...interface{}) error {
return q.Where(q.mapper.PKeyClause(pkey)).One(s)
}
// All load all the structs matching the query
func (q Query) All(value interface{}) error {
rows, err := q.SQLQuery()
if err != nil {
return err
}
defer rows.Close()
resultType := q.mapper.StructType()
results := reflect.Indirect(reflect.ValueOf(value))
var (
isPtr bool
wrongType bool
)
if results.Kind() != reflect.Slice {
wrongType = true
} else {
elemType := results.Type().Elem()
if elemType.Kind() == reflect.Ptr {
isPtr = true
wrongType = results.Type().Elem().Elem() != resultType
} else {
wrongType = results.Type().Elem() != resultType
}
}
if wrongType {
return fmt.Errorf("yago Query.All(): Expected a []%s, got %v", resultType, results.Type())
}
// Empty the slice
results.Set(reflect.MakeSlice(results.Type(), 0, 0))
for rows.Next() {
elem := reflect.New(resultType).Elem()
if err := q.mapper.Scan(rows, elem.Addr().Interface().(MappedStruct)); err != nil {
return fmt.Errorf("yago Query.All(): Error while scanning: %s", err)
}
if isPtr {
results.Set(reflect.Append(results, elem.Addr()))
} else {
results.Set(reflect.Append(results, elem))
}
}
if err != nil {
return err
}
return nil
}
// Scalar execute the query and retrieve a single value from it
func (q Query) Scalar(value interface{}) error {
rows, err := q.SQLQuery()
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return ErrRecordNotFound
}
if columns, err := rows.Columns(); err != nil || len(columns) != 1 {
return ErrInvalidColumns
}
err = rows.Scan(value)
if err != nil {
return err
}
if rows.Next() {
return ErrMultipleRecords
}
return nil
}
// Count change the columns to COUNT(*), execute the query and returns
// the result
func (q Query) Count(count interface{}) error {
// XXX mapper should be able to return a list of pkey fields
// XXX When qb supports COUNT(*), use it
q.selectStmt = q.selectStmt.Select(qb.Count(
q.mapper.Table().PrimaryCols()[0]),
)
return q.Select(
qb.Count(qb.SQLText("*")),
).Scalar(count)
}
// Exists return true if any record matches the current query
func (q Query) Exists() (exists bool, err error) {
q.selectStmt = qb.Select(qb.Exists(
q.selectStmt.Select(qb.SQLText("1")).Limit(0, 1),
))
err = q.Scalar(&exists)
return
}