cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2020.6.4

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

dbconnect/sql.go

318lines · modeblame

759cd019Ashcon Partovi6 years ago1package dbconnect
2
3import (
4"context"
5"database/sql"
6"encoding/json"
7"fmt"
8"net/url"
9"reflect"
10"strings"
11
12"github.com/jmoiron/sqlx"
13"github.com/pkg/errors"
14"github.com/xo/dburl"
15
16// SQL drivers self-register with the database/sql package.
17// https://github.com/golang/go/wiki/SQLDrivers
18_ "github.com/denisenkom/go-mssqldb"
19_ "github.com/go-sql-driver/mysql"
20_ "github.com/mattn/go-sqlite3"
21
22"github.com/kshvakov/clickhouse"
23"github.com/lib/pq"
24)
25
26// SQLClient is a Client that talks to a SQL database.
27type SQLClient struct {
28Dialect string
29driver *sqlx.DB
30}
31
32// NewSQLClient creates a SQL client based on its URL scheme.
33func NewSQLClient(ctx context.Context, originURL *url.URL) (Client, error) {
34res, err := dburl.Parse(originURL.String())
35if err != nil {
36helpText := fmt.Sprintf("supported drivers: %+q, see documentation for more details: %s", sql.Drivers(), "https://godoc.org/github.com/xo/dburl")
37return nil, fmt.Errorf("could not parse sql database url '%s': %s\n%s", originURL, err.Error(), helpText)
38}
39
40// Establishes the driver, but does not test the connection.
41driver, err := sqlx.Open(res.Driver, res.DSN)
42if err != nil {
43return nil, fmt.Errorf("could not open sql driver %s: %s\n%s", res.Driver, err.Error(), res.DSN)
44}
45
46// Closes the driver, will occur when the context finishes.
47go func() {
48<-ctx.Done()
49driver.Close()
50}()
51
52return &SQLClient{driver.DriverName(), driver}, nil
53}
54
55// Ping verifies a connection to the database is still alive.
56func (client *SQLClient) Ping(ctx context.Context) error {
57return client.driver.PingContext(ctx)
58}
59
60// Submit queries or executes a command to the SQL database.
61func (client *SQLClient) Submit(ctx context.Context, cmd *Command) (interface{}, error) {
62txx, err := cmd.ValidateSQL(client.Dialect)
63if err != nil {
64return nil, err
65}
66
67ctx, cancel := context.WithTimeout(ctx, cmd.Timeout)
68defer cancel()
69
70var res interface{}
71
72// Get the next available sql.Conn and submit the Command.
73err = sqlConn(ctx, client.driver, txx, func(conn *sql.Conn) error {
74stmt := cmd.Statement
75args := cmd.Arguments.Positional
76
77if cmd.Mode == "query" {
78res, err = sqlQuery(ctx, conn, stmt, args)
79} else {
80res, err = sqlExec(ctx, conn, stmt, args)
81}
82
83return err
84})
85
86return res, err
87}
88
89// ValidateSQL extends the contract of Command for SQL dialects:
90// mode is conformed, arguments are []sql.NamedArg, and isolation is a sql.IsolationLevel.
91//
92// When the command should not be wrapped in a transaction, *sql.TxOptions and error will both be nil.
93func (cmd *Command) ValidateSQL(dialect string) (*sql.TxOptions, error) {
94err := cmd.Validate()
95if err != nil {
96return nil, err
97}
98
99mode, err := sqlMode(cmd.Mode)
100if err != nil {
101return nil, err
102}
103
104// Mutates Arguments to only use positional arguments with the type sql.NamedArg.
105// This is a required by the sql.Driver before submitting arguments.
106cmd.Arguments.sql(dialect)
107
108iso, err := sqlIsolation(cmd.Isolation)
109if err != nil {
110return nil, err
111}
112
113// When isolation is out-of-range, this is indicative that no
114// transaction should be executed and sql.TxOptions should be nil.
115if iso < sql.LevelDefault {
116return nil, nil
117}
118
119// In query mode, execute the transaction in read-only, unless it's Microsoft SQL
120// which does not support that type of transaction.
121readOnly := mode == "query" && dialect != "mssql"
122
123return &sql.TxOptions{Isolation: iso, ReadOnly: readOnly}, nil
124}
125
126// sqlConn gets the next available sql.Conn in the connection pool and runs a function to use it.
127//
128// If the transaction options are nil, run the useIt function outside a transaction.
129// This is potentially an unsafe operation if the command does not clean up its state.
130func sqlConn(ctx context.Context, driver *sqlx.DB, txx *sql.TxOptions, useIt func(*sql.Conn) error) error {
131conn, err := driver.Conn(ctx)
132if err != nil {
133return err
134}
135defer conn.Close()
136
137// If transaction options are specified, begin and defer a rollback to catch errors.
138var tx *sql.Tx
139if txx != nil {
140tx, err = conn.BeginTx(ctx, txx)
141if err != nil {
142return err
143}
144defer tx.Rollback()
145}
146
147err = useIt(conn)
148
149// Check if useIt was successful and a transaction exists before committing.
150if err == nil && tx != nil {
151err = tx.Commit()
152}
153
154return err
155}
156
157// sqlQuery queries rows on a sql.Conn and returns an array of result objects.
158func sqlQuery(ctx context.Context, conn *sql.Conn, stmt string, args []interface{}) ([]map[string]interface{}, error) {
159rows, err := conn.QueryContext(ctx, stmt, args...)
160if err == nil {
161return sqlRows(rows)
162}
163return nil, err
164}
165
166// sqlExec executes a command on a sql.Conn and returns the result of the operation.
167func sqlExec(ctx context.Context, conn *sql.Conn, stmt string, args []interface{}) (sqlResult, error) {
168exec, err := conn.ExecContext(ctx, stmt, args...)
169if err == nil {
170return sqlResultFrom(exec), nil
171}
172return sqlResult{}, err
173}
174
175// sql mutates Arguments to contain a positional []sql.NamedArg.
176//
177// The actual return type is []interface{} due to the native Golang
178// function signatures for sql.Exec and sql.Query being generic.
179func (args *Arguments) sql(dialect string) {
180result := args.Positional
181
182for i, val := range result {
183result[i] = sqlArg("", val, dialect)
184}
185
186for key, val := range args.Named {
187result = append(result, sqlArg(key, val, dialect))
188}
189
190args.Positional = result
191args.Named = map[string]interface{}{}
192}
193
194// sqlArg creates a sql.NamedArg from a key-value pair and an optional dialect.
195//
196// Certain dialects will need to wrap objects, such as arrays, to conform its driver requirements.
197func sqlArg(key, val interface{}, dialect string) sql.NamedArg {
198switch reflect.ValueOf(val).Kind() {
199
200// PostgreSQL and Clickhouse require arrays to be wrapped before
201// being inserted into the driver interface.
202case reflect.Slice, reflect.Array:
203switch dialect {
204case "postgres":
205val = pq.Array(val)
206case "clickhouse":
207val = clickhouse.Array(val)
208}
209}
210
211return sql.Named(fmt.Sprint(key), val)
212}
213
214// sqlIsolation tries to match a string to a sql.IsolationLevel.
215func sqlIsolation(str string) (sql.IsolationLevel, error) {
216if str == "none" {
217return sql.IsolationLevel(-1), nil
218}
219
220for iso := sql.LevelDefault; ; iso++ {
221if iso > sql.LevelLinearizable {
222return -1, fmt.Errorf("cannot provide an invalid sql isolation level: '%s'", str)
223}
224
225if str == "" || strings.EqualFold(iso.String(), strings.ReplaceAll(str, "_", " ")) {
226return iso, nil
227}
228}
229}
230
231// sqlMode tries to match a string to a command mode: 'query' or 'exec' for now.
232func sqlMode(str string) (string, error) {
233switch str {
234case "query", "exec":
235return str, nil
236default:
237return "", fmt.Errorf("cannot provide invalid sql mode: '%s'", str)
238}
239}
240
241// sqlRows scans through a SQL result set and returns an array of objects.
242func sqlRows(rows *sql.Rows) ([]map[string]interface{}, error) {
243columns, err := rows.Columns()
244if err != nil {
245return nil, errors.Wrap(err, "could not extract columns from result")
246}
247defer rows.Close()
248
249types, err := rows.ColumnTypes()
250if err != nil {
251// Some drivers do not support type extraction, so fail silently and continue.
252types = make([]*sql.ColumnType, len(columns))
253}
254
255values := make([]interface{}, len(columns))
256pointers := make([]interface{}, len(columns))
257
258var results []map[string]interface{}
259for rows.Next() {
260for i := range columns {
261pointers[i] = &values[i]
262}
263rows.Scan(pointers...)
264
265// Convert a row, an array of values, into an object where
266// each key is the name of its respective column.
267entry := make(map[string]interface{})
268for i, col := range columns {
269entry[col] = sqlValue(values[i], types[i])
270}
271results = append(results, entry)
272}
273
274return results, nil
275}
276
277// sqlValue handles special cases where sql.Rows does not return a "human-readable" object.
278func sqlValue(val interface{}, col *sql.ColumnType) interface{} {
279bytes, ok := val.([]byte)
280if ok {
281// Opportunistically check for embeded JSON and convert it to a first-class object.
282var embeded interface{}
283if json.Unmarshal(bytes, &embeded) == nil {
284return embeded
285}
286
287// STOR-604: investigate a way to coerce PostgreSQL arrays '{a, b, ...}' into JSON.
288// Although easy with strings, it becomes more difficult with special types like INET[].
289
290return string(bytes)
291}
292
293return val
294}
295
296// sqlResult is a thin wrapper around sql.Result.
297type sqlResult struct {
298LastInsertId int64 `json:"last_insert_id"`
299RowsAffected int64 `json:"rows_affected"`
300}
301
302// sqlResultFrom converts sql.Result into a JSON-marshable sqlResult.
303func sqlResultFrom(res sql.Result) sqlResult {
304insertID, errID := res.LastInsertId()
305rowsAffected, errRows := res.RowsAffected()
306
307// If an error occurs when extracting the result, it is because the
308// driver does not support that specific field. Instead of passing this
309// to the user, omit the field in the response.
310if errID != nil {
311insertID = -1
312}
313if errRows != nil {
314rowsAffected = -1
315}
316
317return sqlResult{insertID, rowsAffected}
318}