github.com/kunlun-qilian/sqlx/v3@v3.0.0/scanner/scan.go (about)

     1  package scanner
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  var RecordNotFound = errors.New("record is not found")
    11  
    12  func Scan(ctx context.Context, rows *sql.Rows, v interface{}) error {
    13  	if rows == nil {
    14  		return nil
    15  	}
    16  	defer rows.Close()
    17  
    18  	si, err := ScanIteratorFor(v)
    19  	if err != nil {
    20  		return err
    21  	}
    22  
    23  	for rows.Next() {
    24  		item := si.New()
    25  
    26  		if scanErr := scanTo(context.Background(), rows, item); scanErr != nil {
    27  			return scanErr
    28  		}
    29  
    30  		if err := si.Next(item); err != nil {
    31  			return err
    32  		}
    33  	}
    34  
    35  	if mustHasRecord, ok := si.(interface{ MustHasRecord() bool }); ok {
    36  		if !mustHasRecord.MustHasRecord() {
    37  			return RecordNotFound
    38  		}
    39  	}
    40  
    41  	if err := rows.Err(); err != nil {
    42  		return err
    43  	}
    44  
    45  	// Make sure the query can be processed to completion with no errors.
    46  	if err := rows.Close(); err != nil {
    47  		return err
    48  	}
    49  
    50  	return nil
    51  }