1
0
Fork 0
gobelt/dbc/query.go

84 lines
2.1 KiB
Go
Raw Normal View History

2018-07-07 12:11:23 +00:00
package dbc
2018-06-24 22:22:27 +00:00
import (
"context"
"database/sql"
"time"
)
type connOrTx interface {
executer
queryPerformer
}
type executer interface {
// Exec executes a query and does not expect any result.
Exec(ctx context.Context, query string, args ...interface{}) ExecResult
ExecNamed(ctx context.Context, query string, arg interface{}) ExecResult
}
type queryPerformer interface {
// Query executes a query and returns a result object that can later be used
// to retrieve values.
2018-07-07 12:11:23 +00:00
Query(ctx context.Context, query string, args ...interface{}) Rows
QueryNamed(ctx context.Context, query string, arg interface{}) Rows
2018-06-24 22:22:27 +00:00
}
type stdConnOrTx interface {
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
}
type caller struct {
db stdConnOrTx
cb *callbacks
}
func (c *caller) Exec(ctx context.Context, query string, args ...interface{}) ExecResult {
c.cb.callBefore(ctx, query)
startedAt := time.Now()
res, err := c.db.ExecContext(ctx, query, args...)
c.cb.callAfter(ctx, query, time.Since(startedAt), err)
return &execResult{
db: c,
err: err,
res: res,
}
}
func (c *caller) ExecNamed(ctx context.Context, query string, arg interface{}) ExecResult {
2018-07-08 22:48:55 +00:00
params, err := newNamedParams(arg)
if err != nil {
return &execResult{err: err}
}
preparedQuery, args, err := prepareNamedQuery(query, params)
if err != nil {
return &execResult{err: err}
}
return c.Exec(ctx, preparedQuery, args...)
2018-06-24 22:22:27 +00:00
}
2018-07-07 12:11:23 +00:00
func (c *caller) Query(ctx context.Context, query string, args ...interface{}) Rows {
2018-06-24 22:22:27 +00:00
c.cb.callBefore(ctx, query)
startedAt := time.Now()
2018-07-07 12:11:23 +00:00
r, err := c.db.QueryContext(ctx, query, args...)
2018-06-24 22:22:27 +00:00
c.cb.callAfter(ctx, query, time.Since(startedAt), err)
2018-07-07 12:11:23 +00:00
return &rows{
2018-06-24 22:22:27 +00:00
err: err,
2018-07-07 12:11:23 +00:00
rows: r,
2018-06-24 22:22:27 +00:00
}
}
2018-07-07 12:11:23 +00:00
func (c *caller) QueryNamed(ctx context.Context, query string, arg interface{}) Rows {
2018-07-08 22:48:55 +00:00
params, err := newNamedParams(arg)
if err != nil {
return &rows{err: err}
}
preparedQuery, args, err := prepareNamedQuery(query, params)
if err != nil {
return &rows{err: err}
}
return c.Query(ctx, preparedQuery, args...)
2018-06-24 22:22:27 +00:00
}