| 1 |
// Copyright (c) 2024 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package dbutil |
| 8 |
|
| 9 |
import ( |
| 10 |
"reflect" |
| 11 |
) |
| 12 |
|
| 13 |
func reflectScan[T any](row Scannable) (*T, error) { |
| 14 |
t := new(T) |
| 15 |
val := reflect.ValueOf(t).Elem() |
| 16 |
fields := reflect.VisibleFields(val.Type()) |
| 17 |
scanInto := make([]any, len(fields)) |
| 18 |
for i, field := range fields { |
| 19 |
scanInto[i] = val.FieldByIndex(field.Index).Addr().Interface() |
| 20 |
} |
| 21 |
err := row.Scan(scanInto...) |
| 22 |
return t, err |
| 23 |
} |
| 24 |
|
| 25 |
// NewSimpleReflectRowIter creates a new RowIter that uses reflection to scan rows into the given type. |
| 26 |
// |
| 27 |
// This is a simplified implementation that always scans to all struct fields. It does not support any kind of struct tags. |
| 28 |
func NewSimpleReflectRowIter[T any](rows Rows, err error) RowIter[*T] { |
| 29 |
return ConvertRowFn[*T](reflectScan[T]).NewRowIter(rows, err) |
| 30 |
} |