github.com/acoshift/pgsql@v0.15.3/iter.go (about)

     1  package pgsql
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  )
     7  
     8  type Scanner func(dest ...any) error
     9  
    10  type Iterator func(scan Scanner) error
    11  
    12  // QueryContext interface
    13  type QueryContext interface {
    14  	QueryContext(context.Context, string, ...any) (*sql.Rows, error)
    15  }
    16  
    17  func Iter(q interface {
    18  	QueryContext(context.Context, string, ...any) (*sql.Rows, error)
    19  }, iter Iterator, query string, args ...any) error {
    20  	return IterContext(context.Background(), q, iter, query, args...)
    21  }
    22  
    23  func IterContext(ctx context.Context, q interface {
    24  	QueryContext(context.Context, string, ...any) (*sql.Rows, error)
    25  }, iter Iterator, query string, args ...any) error {
    26  	rows, err := q.QueryContext(ctx, query, args...)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	defer rows.Close()
    31  
    32  	for rows.Next() {
    33  		err := iter(Scan(rows.Scan))
    34  		if err != nil {
    35  			return err
    36  		}
    37  	}
    38  
    39  	return rows.Err()
    40  }