advsql/query.go
2022-07-09 23:55:22 +02:00

63 lines
1.1 KiB
Go

package advsql
import "context"
func Query[T any](db *Database, query string, decoder func(v *T, decode DecodeFunc) error) QueryManyFunc[T] {
s, err := db.prepare(query)
if err != nil {
panic(err)
}
return func(args ...interface{}) <-chan *T {
out := make(chan *T, 10)
rows, err := s.Query(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
}
}
func QueryContext[T any](db *Database, query string, decoder func(v *T, decode DecodeFunc) 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
}
}