-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstmt.go
104 lines (80 loc) · 2.24 KB
/
stmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package asql
import (
"context"
"database/sql"
"fmt"
"sync"
)
// Stmt is a wrapper around sql.Stmt that provides asynchronous methods.
type Stmt struct {
*sql.Stmt
wg *sync.WaitGroup
}
// Exec executes a prepared statement with the given arguments without returning any rows.
func (s *Stmt) Exec(args ...any) (<-chan *Result, context.CancelFunc) {
return s.ExecContext(context.Background(), args...)
}
// ExecContext executes a prepared statement with the given arguments without returning any rows.
func (s *Stmt) ExecContext(ctx context.Context, args ...any) (<-chan *Result, context.CancelFunc) {
ctx, cancel := context.WithCancel(ctx)
ch := make(chan *Result)
if s.wg != nil {
s.wg.Add(1)
}
go func() {
result, err := s.Stmt.ExecContext(ctx, args...)
ch <- &Result{
Result: result,
err: fmt.Errorf("error executing the query: %w", err),
}
if s.wg != nil {
s.wg.Done()
}
}()
return ch, cancel
}
// Query executes a prepared query statement with the given arguments.
func (s *Stmt) Query(args ...any) (<-chan *Rows, context.CancelFunc) {
return s.QueryContext(context.Background(), args...)
}
// QueryContext executes a prepared query statement with the given arguments.
func (s *Stmt) QueryContext(ctx context.Context, args ...any) (<-chan *Rows, context.CancelFunc) {
ctx, cancel := context.WithCancel(ctx)
ch := make(chan *Rows)
if s.wg != nil {
s.wg.Add(1)
}
go func() {
rows, err := s.Stmt.QueryContext(ctx, args...)
ch <- &Rows{
Rows: rows,
err: fmt.Errorf("error querying the database: %w", err),
}
if s.wg != nil {
s.wg.Done()
}
}()
return ch, cancel
}
// QueryRow executes a prepared query statement with the given arguments.
func (s *Stmt) QueryRow(args ...any) (<-chan *Row, context.CancelFunc) {
return s.QueryRowContext(context.Background(), args...)
}
// QueryRowContext executes a prepared query statement with the given arguments.
func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) (<-chan *Row, context.CancelFunc) {
ctx, cancel := context.WithCancel(ctx)
ch := make(chan *Row)
if s.wg != nil {
s.wg.Add(1)
}
go func() {
row := s.Stmt.QueryRowContext(ctx, args...)
ch <- &Row{
Row: row,
}
if s.wg != nil {
s.wg.Done()
}
}()
return ch, cancel
}