-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
62 lines (53 loc) · 1.44 KB
/
query.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
package pogo
import (
"context"
"database/sql"
"github.com/pkg/errors"
"github.com/sanggonlee/pogo/internal/query"
"github.com/sanggonlee/pogo/internal/version"
)
// Query prepares a query running instance. Note that it does not run a
// query by itself.
func Query(queryor Queryor) QueryRunner {
safeguardPostgresVersion()
return QueryRunner{
queryor: queryor,
}
}
// QueryContext is like Query, except it also takes a context.
func QueryContext(ctx context.Context, queryor Queryor) QueryRunner {
safeguardPostgresVersion()
return QueryRunner{
queryor: queryor,
ctx: ctx,
}
}
// QueryRunner is an encapsulation for running a single query.
type QueryRunner struct {
queryor Queryor
ctx context.Context
}
// For is used to run a query on arbitrary relations. It returns sql.Rows, which
// you can scan to the structure you see fit.
func (qr QueryRunner) For(queryable query.Queryable) (*sql.Rows, error) {
q, err := queryable.ToQuery()
if err != nil {
return nil, errors.Wrap(err, "converting queryable to query string")
}
var rows *sql.Rows
if qr.ctx == nil {
rows, err = qr.queryor.Query(q)
} else {
rows, err = qr.queryor.QueryContext(qr.ctx, q)
}
if err != nil {
return nil, errors.Wrap(err, "querying rows")
}
return rows, nil
}
func safeguardPostgresVersion() {
// Ensure Postgres version is locked down before running any queries.
if !version.IsSet() {
_ = SetPostgresVersion(defaultPostgresVersion)
}
}