-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
56 lines (50 loc) · 1.36 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
package dali
import (
"context"
"database/sql"
"fmt"
)
// Query represents an arbitrary SQL statement.
// The SQL is preprocessed by Preprocessor before running.
type Query struct {
ctx context.Context
execer Execer
query string
args []interface{}
err error
}
// Exec executes the query that shouldn't return rows.
// For example: INSERT or UPDATE.
func (q *Query) Exec() (sql.Result, error) {
if q.err != nil {
return nil, q.err
}
return q.execer.ExecContext(q.ctx, q.query, q.args...)
}
// Rows executes that query that should return rows, typically a SELECT.
func (q *Query) Rows() (*sql.Rows, error) {
if q.err != nil {
return nil, q.err
}
return q.execer.QueryContext(q.ctx, q.query, q.args...)
}
// ScanRow executes the query that is expected to return at most one row.
// It copies the columns from the matched row into the values
// pointed at by dest. If more than one row matches the query,
// ScanRow uses the first row and discards the rest. If no row matches
// the query, ScanRow returns sql.ErrNoRows.
func (q *Query) ScanRow(dest ...interface{}) error {
if q.err != nil {
return q.err
}
return q.execer.QueryRowContext(q.ctx, q.query, q.args...).Scan(dest...)
}
func (q *Query) String() string {
if q.err != nil {
panic(q.err)
}
if len(q.args) > 0 {
return fmt.Sprintf("%s /* args: %v */", q.query, q.args)
}
return q.query
}