advsql/query.go

63 lines
1.1 KiB
Go
Raw Normal View History

2022-07-05 12:38:39 +02:00
package advsql
import "context"
func Query[T any](db *Database, query string, decoder func(v *T, decode DecodeFunc) error) QueryManyFunc[T] {
2022-07-05 12:38:39 +02:00
s, err := db.prepare(query)
if err != nil {
return nil
}
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 {
2022-07-05 12:38:39 +02:00
out <- v
}
}
}()
return out
}
}
func QueryContext[T any](db *Database, query string, decoder func(v *T, decode DecodeFunc) error) QueryManyContextFunc[T] {
2022-07-05 12:38:39 +02:00
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 {
2022-07-05 12:38:39 +02:00
out <- v
}
}
}()
return out
}
}