Wrapper for asynchronous DB queries
- Dominant language
- Go
- Stars
- 14.3k
- Forks
- 1.1k
- Avg merge
- 6d 9h
- Merged PRs (30d)
- 11
Description
**Is your feature request related to a problem? Please describe.**
There's a simple use case: _run several DB queries in parallel instead of sequentially for better response time_.
**Describe the solution you'd like**
I've create a wrapper like this:
```
func withDbAsync[T any](dbPool *pgxpool.Pool, handler func(*pgxpool.Conn) (*T, error)) (chan *T, chan error) {
resultChan := make(chan *T)
errorChan := make(chan error)
go func() {
conn, err := dbPool.Acquire(context.Background())
if err != nil {
errorChan <- err
return
}
defer conn.Release()
res, err := handler(conn)
if err != nil {
errorChan <- err
return
} else {
errorChan <- nil
resultChan <- res
}
}()
return resultChan, errorChan
}
```
(handler function does actual querying synchronously).
Then it's possible to combine 2 (and more) queries like this:
```
res1Chan, err1Chan := withDbAsync(
dbPool,
func(conn *pgxpool.Conn) (*int32, error) {
var count int32
row := conn.QueryRow(context.Background(), "SELECT COUNT(*) FROM item1")
if err := row.Scan(&count); err != nil {
return nil, err
}
return &count, nil
},
)
res2Chan, err2Chan := withDbAsync(
dbPool,
func(conn *pgxpool.Conn) (*int32, error) {
var count int32
row := conn.QueryRow(context.Background(), "SELECT COUNT(*) FROM item2")
if err := row.Scan(&count); err != nil {
return nil, err
}
return &count, nil
},
)
err1 := <- err1Chan
if err1 != nil {
// return err1
}
err2 := <- err2Chan
if err2 != nil {
// return err2
}
// no errors
res1 := <- res1Chan
res2 := <- res2Chan
```
The task of querying DB asynchronously seems to be a must have in modern times...
Contributor guide
Research direction
Start by reviewing the pgxpool.Pool.Acquire entry point and the asynchronous wrapper shown in the issue. No repository files or tests are named, so the first step is to determine whether this belongs in pgxpool and what API and concurrency semantics are required. Done would require an agreed design, implementation, and tests for parallel queries and error handling.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go, postgresql
- Domain
- backend, databases
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100