-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbinder.go
279 lines (248 loc) · 8.31 KB
/
binder.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
Copyright 2023 eatmoreapple
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 juice
import (
"database/sql"
"errors"
"iter"
"reflect"
"time"
)
var (
// scannerType is the reflect.Type of sql.Scanner
// nolint:unused
scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
// timeType is the reflect.Type of time.Time
timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
)
// bindWithResultMap maps sql.Rows to a destination value using the specified ResultMap.
// It serves as the core binding function for all mapping operations in the package.
//
// Parameters:
// - rows: The source sql.Rows to map from. Must not be nil.
// - v: The destination value to map to. Must be a pointer and not nil.
// - resultMap: The mapping strategy to use. If nil, a default mapper will be selected
// based on the destination type (SingleRowResultMap for struct, MultiRowsResultMap for slice).
//
// The function follows this process:
// 1. Validates input parameters
// 2. Checks if the destination implements RowScanner for custom mapping
// 3. Falls back to reflection-based mapping using the provided or default ResultMap
//
// Returns an error if:
// - The destination is nil (ErrNilDestination)
// - The rows parameter is nil (ErrNilRows)
// - The destination is not a pointer (ErrPointerRequired)
// - Any error occurs during the mapping process
func bindWithResultMap(rows *sql.Rows, v any, resultMap ResultMap) error {
if v == nil {
return ErrNilDestination
}
if rows == nil {
return ErrNilRows
}
// Try custom row scanning if the destination implements RowScanner
if rowScanner, ok := v.(RowScanner); ok {
return rowScanner.ScanRows(rows)
}
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr {
return ErrPointerRequired
}
// Select default mapper if none provided
if resultMap == nil {
if kd := reflect.Indirect(rv).Kind(); kd == reflect.Slice {
resultMap = MultiRowsResultMap{}
} else {
resultMap = SingleRowResultMap{}
}
}
// Perform the actual mapping
return resultMap.MapTo(rv, rows)
}
// BindWithResultMap bind sql.Rows to given entity with given ResultMap
// bind cover sql.Rows to given entity
// dest can be a pointer to a struct, a pointer to a slice of struct, or a pointer to a slice of any type.
// rows won't be closed when the function returns.
func BindWithResultMap[T any](rows *sql.Rows, resultMap ResultMap) (result T, err error) {
// ptr is the pointer of the result, it is the destination of the binding.
var ptr any = &result
if _type := reflect.TypeOf(result); _type.Kind() == reflect.Ptr {
// if the result is a pointer, create a new instance of the element.
// you'd better not use a nil pointer as the result.
result = reflect.New(_type.Elem()).Interface().(T)
ptr = result
}
err = bindWithResultMap(rows, ptr, resultMap)
return
}
// Bind sql.Rows to given entity with default mapper
// Example usage of the binder package
//
// Example_bind shows how to use the Bind function:
//
// type User struct {
// ID int `column:"id"`
// Name string `column:"name"`
// }
//
// rows, err := db.Query("SELECT id, name FROM users")
// if err != nil {
// log.Fatal(err)
// }
// defer rows.Close()
//
// user, err := Bind[[]User](rows)
// if err != nil {
// log.Fatal(err)
// }
func Bind[T any](rows *sql.Rows) (result T, err error) {
return BindWithResultMap[T](rows, nil)
}
// List converts sql.Rows to a slice of the given entity type.
// If there are no rows, it will return an empty slice.
//
// Differences between List and Bind:
// - List always returns a slice, even if there is only one row.
// - Bind always returns the entity of the given type.
//
// Bind is more flexible; you can use it to bind a single row to a struct, a slice of structs, or a slice of any type.
// However, if you are sure that the result will be a slice, you can use List. It could be faster than Bind.
//
// Example_list shows how to use the List function:
//
// type User struct {
// ID int `column:"id"`
// Name string `column:"name"`
// }
//
// rows, err := db.Query("SELECT id, name FROM users")
// if err != nil {
// log.Fatal(err)
// }
// defer rows.Close()
//
// users, err := List[User](rows)
// if err != nil {
// log.Fatal(err)
// }
func List[T any](rows *sql.Rows) (result []T, err error) {
var multiRowsResultMap MultiRowsResultMap
element := reflect.TypeOf((*T)(nil)).Elem()
// using reflect.New to create a new instance of the element is a very time-consuming operation.
// if the element is not a pointer, we can create a new instance of it directly.
if element.Kind() != reflect.Ptr {
multiRowsResultMap.New = func() reflect.Value { return reflect.ValueOf(new(T)) }
}
err = bindWithResultMap(rows, &result, multiRowsResultMap)
return
}
// List2 converts database query results into a slice of pointers.
// Unlike List function, List2 returns a slice of pointers []*T instead of a slice of values []T.
// This is particularly useful when you need to modify slice elements or handle large structs.
func List2[T any](rows *sql.Rows) ([]*T, error) {
items, err := List[T](rows)
if err != nil {
return nil, err
}
var result = make([]*T, len(items))
for i := range items {
result[i] = &items[i]
}
return result, nil
}
// RowsIter provides an iterator interface for sql.Rows.
// It implements Go's built-in iter.Seq interface for type-safe iteration over database rows.
// Type parameter T represents the type of values that will be yielded during iteration.
type RowsIter[T any] struct {
rows *sql.Rows // The underlying sql.Rows to iterate over
err error // Stores any error that occurs during iteration
}
// Err returns any error that occurred during iteration.
// This method should be checked after iteration is complete to ensure
// no errors occurred while processing the rows.
func (r *RowsIter[T]) Err() error {
return errors.Join(r.err, r.rows.Err())
}
// Iter implements the iter.Seq interface for row iteration.
// It yields values of type T, automatically handling memory allocation
// and type conversion for each row.
//
// Example usage:
//
// iter := Iter[User](rows)
// for v := range iter.Iter() {
// // Process each user
// fmt.Println(v.Name)
// }
// if err := iter.Err(); err != nil {
// // Handle error
// }
func (r *RowsIter[T]) Iter() iter.Seq[T] {
columns, err := r.rows.Columns()
if err != nil {
r.err = err
return nil
}
columnDest := &rowDestination{}
t := reflect.TypeFor[T]()
// Default object factory for non-pointer types
var objectFactory = func() T { return *new(T) }
isPtr := t.Kind() == reflect.Ptr
// Override object factory for pointer types to properly allocate memory
if isPtr {
objectFactory = func() T { return reflect.New(t.Elem()).Interface().(T) }
}
// handler encapsulates the row scanning logic and object creation
handler := func() (T, error) {
var t = objectFactory()
var v reflect.Value
if isPtr {
v = reflect.ValueOf(t)
} else {
v = reflect.ValueOf(&t)
}
// Create destination slice for scanning row values
dest, err := columnDest.Destination(v.Elem(), columns)
if err != nil {
return t, err
}
if err = r.rows.Scan(dest...); err != nil {
return t, err
}
return t, nil
}
return func(yield func(T) bool) {
for r.rows.Next() {
value, err := handler()
if err != nil {
r.err = err
return
}
if !yield(value) {
return
}
}
}
}
// Iter creates an iterator over SQL rows that yields values of type T.
// It handles both pointer and non-pointer types automatically and provides
// proper memory management for each iteration.
//
// Note: This function does not close the sql.Rows. The caller is responsible
// for closing the rows when iteration is complete. This design allows for more
// flexible resource management, especially when using the iterator in different
// contexts or when early termination is needed.
func Iter[T any](rows *sql.Rows) *RowsIter[T] {
return &RowsIter[T]{rows: rows}
}