Debian Codegraph @

rows.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package dbx
6
7 import (
8 "database/sql"
9 "reflect"
10 )
11
12 // VarTypeError indicates a variable type error when trying to populating a variable with DB result.
13 type VarTypeError string
14
15 // Error returns the error message.
16 func (s VarTypeError) Error() string {
17 return "Invalid variable type: " + string(s)
18 }
19
20 // NullStringMap is a map of sql.NullString that can be used to hold DB query result.
21 // The map keys correspond to the DB column names, while the map values are their corresponding column values.
22 type NullStringMap map[string]sql.NullString
23
24 // Rows enhances sql.Rows by providing additional data query methods.
25 // Rows can be obtained by calling Query.Rows(). It is mainly used to populate data row by row.
26 type Rows struct {
27 *sql.Rows
28 fieldMapFunc FieldMapFunc
29 }
30
31 // ScanMap populates the current row of data into a NullStringMap.
32 // Note that the NullStringMap must not be nil, or it will panic.
33 // The NullStringMap will be populated using column names as keys and their values as
34 // the corresponding element values.
35 func (r *Rows) ScanMap(a NullStringMap) error {
36 cols, _ := r.Columns()
37 var refs []interface{}
38 for i := 0; i < len(cols); i++ {
39 var t sql.NullString
40 refs = append(refs, &t)
41 }
42 if err := r.Scan(refs...); err != nil {
43 return err
44 }
45
46 for i, col := range cols {
47 a[col] = *refs[i].(*sql.NullString)
48 }
49
50 return nil
51 }
52
53 // ScanStruct populates the current row of data into a struct.
54 // The struct must be given as a pointer.
55 //
56 // ScanStruct associates struct fields with DB table columns through a field mapping function.
57 // It populates a struct field with the data of its associated column.
58 // Note that only exported struct fields will be populated.
59 //
60 // By default, DefaultFieldMapFunc() is used to map struct fields to table columns.
61 // This function separates each word in a field name with a underscore and turns every letter into lower case.
62 // For example, "LastName" is mapped to "last_name", "MyID" is mapped to "my_id", and so on.
63 // To change the default behavior, set DB.FieldMapper with your custom mapping function.
64 // You may also set Query.FieldMapper to change the behavior for particular queries.
65 func (r *Rows) ScanStruct(a interface{}) error {
66 rv := reflect.ValueOf(a)
67 if rv.Kind() != reflect.Ptr || rv.IsNil() {
68 return VarTypeError("must be a pointer")
69 }
70 rv = indirect(rv)
71 if rv.Kind() != reflect.Struct {
72 return VarTypeError("must be a pointer to a struct")
73 }
74
75 si := getStructInfo(rv.Type(), r.fieldMapFunc)
76
77 cols, _ := r.Columns()
78 refs := make([]interface{}, len(cols))
79
80 for i, col := range cols {
81 if fi, ok := si.dbNameMap[col]; ok {
82 refs[i] = fi.getField(rv).Addr().Interface()
83 } else {
84 refs[i] = &sql.NullString{}
85 }
86 }
87
88 if err := r.Scan(refs...); err != nil {
89 return err
90 }
91
92 // check for PostScanner
93 if rv.CanAddr() {
94 addr := rv.Addr()
95 if addr.CanInterface() {
96 if ps, ok := addr.Interface().(PostScanner); ok {
97 if err := ps.PostScan(); err != nil {
98 return err
99 }
100 }
101 }
102 }
103
104 return nil
105 }
106
107 // all populates all rows of query result into a slice of struct or NullStringMap.
108 // Note that the slice must be given as a pointer.
109 func (r *Rows) all(slice interface{}) error {
110 defer r.Close()
111
112 v := reflect.ValueOf(slice)
113 if v.Kind() != reflect.Ptr || v.IsNil() {
114 return VarTypeError("must be a pointer")
115 }
116 v = indirect(v)
117
118 if v.Kind() != reflect.Slice {
119 return VarTypeError("must be a slice of struct or NullStringMap")
120 }
121
122 if v.IsNil() {
123 // create an empty slice
124 v.Set(reflect.MakeSlice(v.Type(), 0, 0))
125 }
126
127 et := v.Type().Elem()
128
129 if et.Kind() == reflect.Map {
130 for r.Next() {
131 ev, ok := reflect.MakeMap(et).Interface().(NullStringMap)
132 if !ok {
133 return VarTypeError("must be a slice of struct or NullStringMap")
134 }
135 if err := r.ScanMap(ev); err != nil {
136 return err
137 }
138 v.Set(reflect.Append(v, reflect.ValueOf(ev)))
139 }
140 return r.Close()
141 }
142
143 var isSliceOfPointers bool
144 if et.Kind() == reflect.Ptr {
145 isSliceOfPointers = true
146 et = et.Elem()
147 }
148
149 if et.Kind() != reflect.Struct {
150 return VarTypeError("must be a slice of struct or NullStringMap")
151 }
152
153 etPtr := reflect.PtrTo(et)
154 implementsPostScanner := etPtr.Implements(postScannerType)
155
156 si := getStructInfo(et, r.fieldMapFunc)
157
158 cols, _ := r.Columns()
159 for r.Next() {
160 ev := reflect.New(et).Elem()
161 refs := make([]interface{}, len(cols))
162 for i, col := range cols {
163 if fi, ok := si.dbNameMap[col]; ok {
164 refs[i] = fi.getField(ev).Addr().Interface()
165 } else {
166 refs[i] = &sql.NullString{}
167 }
168 }
169 if err := r.Scan(refs...); err != nil {
170 return err
171 }
172
173 if isSliceOfPointers {
174 ev = ev.Addr()
175 }
176
177 // check for PostScanner
178 if implementsPostScanner {
179 evAddr := ev
180 if ev.CanAddr() {
181 evAddr = ev.Addr()
182 }
183 if evAddr.CanInterface() {
184 if ps, ok := evAddr.Interface().(PostScanner); ok {
185 if err := ps.PostScan(); err != nil {
186 return err
187 }
188 }
189 }
190 }
191
192 v.Set(reflect.Append(v, ev))
193 }
194
195 return r.Close()
196 }
197
198 // column populates the given slice with the first column of the query result.
199 // Note that the slice must be given as a pointer.
200 func (r *Rows) column(slice interface{}) error {
201 defer r.Close()
202
203 v := reflect.ValueOf(slice)
204 if v.Kind() != reflect.Ptr || v.IsNil() {
205 return VarTypeError("must be a pointer to a slice")
206 }
207 v = indirect(v)
208
209 if v.Kind() != reflect.Slice {
210 return VarTypeError("must be a pointer to a slice")
211 }
212
213 et := v.Type().Elem()
214
215 cols, _ := r.Columns()
216 for r.Next() {
217 ev := reflect.New(et)
218 refs := make([]interface{}, len(cols))
219 for i := range cols {
220 if i == 0 {
221 refs[i] = ev.Interface()
222 } else {
223 refs[i] = &sql.NullString{}
224 }
225 }
226 if err := r.Scan(refs...); err != nil {
227 return err
228 }
229 v.Set(reflect.Append(v, ev.Elem()))
230 }
231
232 return r.Close()
233 }
234
235 // one populates a single row of query result into a struct or a NullStringMap.
236 // Note that if a struct is given, it should be a pointer.
237 func (r *Rows) one(a interface{}) error {
238 defer r.Close()
239
240 if !r.Next() {
241 if err := r.Err(); err != nil {
242 return err
243 }
244 return sql.ErrNoRows
245 }
246
247 var err error
248
249 rt := reflect.TypeOf(a)
250 if rt.Kind() == reflect.Ptr && rt.Elem().Kind() == reflect.Map {
251 // pointer to map
252 v := indirect(reflect.ValueOf(a))
253 if v.IsNil() {
254 v.Set(reflect.MakeMap(v.Type()))
255 }
256 a = v.Interface()
257 rt = reflect.TypeOf(a)
258 }
259
260 if rt.Kind() == reflect.Map {
261 v, ok := a.(NullStringMap)
262 if !ok {
263 return VarTypeError("must be a NullStringMap")
264 }
265 if v == nil {
266 return VarTypeError("NullStringMap is nil")
267 }
268 err = r.ScanMap(v)
269 } else {
270 err = r.ScanStruct(a)
271 }
272
273 if err != nil {
274 return err
275 }
276
277 return r.Close()
278 }
279
280 // row populates a single row of query result into a list of variables.
281 func (r *Rows) row(a ...interface{}) error {
282 defer r.Close()
283
284 for _, dp := range a {
285 if _, ok := dp.(*sql.RawBytes); ok {
286 return VarTypeError("RawBytes isn't allowed on Row()")
287 }
288 }
289
290 if !r.Next() {
291 if err := r.Err(); err != nil {
292 return err
293 }
294 return sql.ErrNoRows
295 }
296 if err := r.Scan(a...); err != nil {
297 return err
298 }
299
300 return r.Close()
301 }