advsql/query_many.go

41 lines
892 B
Go
Raw Normal View History

package advsql
import "context"
func QueryMany[T any](db *Database, query string, decoder func(v *T, decode ScanFunc) error) QueryManyFunc[T] {
ctxfunc := QueryManyContext(db, query, decoder)
return func(args ...interface{}) <-chan *T {
return ctxfunc(context.Background(), args...)
}
}
func QueryManyContext[T any](db *Database, query string, decoder func(v *T, decode ScanFunc) error) QueryManyContextFunc[T] {
s, err := db.db.Prepare(query)
if err != nil {
return nil
}
db.closefuncs = append(db.closefuncs, s.Close)
return func(ctx context.Context, args ...interface{}) <-chan *T {
out := make(chan *T, 10)
rows, err := s.QueryContext(ctx, args...)
if err != nil {
panic(err)
}
go func() {
defer rows.Close()
defer close(out)
for rows.Next() {
v := new(T)
if decoder(v, rows.Scan) == nil {
out <- v
}
}
}()
return out
}
}