model_scan.go (924B)
1 package bun 2 3 import ( 4 "context" 5 "database/sql" 6 "reflect" 7 8 "github.com/uptrace/bun/schema" 9 ) 10 11 type scanModel struct { 12 db *DB 13 14 dest []interface{} 15 scanIndex int 16 } 17 18 var _ Model = (*scanModel)(nil) 19 20 func newScanModel(db *DB, dest []interface{}) *scanModel { 21 return &scanModel{ 22 db: db, 23 dest: dest, 24 } 25 } 26 27 func (m *scanModel) Value() interface{} { 28 return m.dest 29 } 30 31 func (m *scanModel) ScanRows(ctx context.Context, rows *sql.Rows) (int, error) { 32 if !rows.Next() { 33 return 0, rows.Err() 34 } 35 36 dest := makeDest(m, len(m.dest)) 37 38 m.scanIndex = 0 39 if err := rows.Scan(dest...); err != nil { 40 return 0, err 41 } 42 43 return 1, nil 44 } 45 46 func (m *scanModel) ScanRow(ctx context.Context, rows *sql.Rows) error { 47 return rows.Scan(m.dest...) 48 } 49 50 func (m *scanModel) Scan(src interface{}) error { 51 dest := reflect.ValueOf(m.dest[m.scanIndex]) 52 m.scanIndex++ 53 54 scanner := schema.Scanner(dest.Type()) 55 return scanner(dest, src) 56 }