-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
64 lines (51 loc) · 1.31 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
63
64
package wuery
import (
"context"
"database/sql"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/nvcnvn/wuery/translator"
)
// Wuery can validate the SQL statement
type Wuery struct {
db dbQueryInterface
parser *parser.Parser
}
// NewWuery retuns new Wuery
func NewWuery(db *sql.DB) *Wuery {
return &Wuery{
db: db,
parser: &parser.Parser{},
}
}
type dbQueryInterface interface {
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
}
func (w *Wuery) validate(sql string) error {
stmts, err := w.parser.Parse(sql)
if err != nil {
return err
}
if len(stmts) != 1 {
return pgerror.NewAssertionErrorf("expected 1 statement, but found %d", len(stmts))
}
if stmts[0].StatementType() != tree.Rows {
return pgerror.NewAssertionErrorf("expected the statement returns the affected rows")
}
println(stmts[0].String())
return nil
}
// Query actually send the query to DB
func (w *Wuery) Query(ctx context.Context, query string) ([]byte, error) {
err := w.validate(query)
if err != nil {
return nil, err
}
rows, err := w.db.QueryContext(ctx, query)
if err != nil {
return nil, err
}
t := &translator.CockRoachTranslate{}
return t.Translate(rows), err
}