forked from cockroachdb/cockroach
/
sql_util.go
165 lines (144 loc) · 5.05 KB
/
sql_util.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
//
// Author: Marc berhault (marc@cockroachlabs.com)
package cli
import (
"database/sql"
"fmt"
"github.com/olekukonko/tablewriter"
"github.com/cockroachdb/cockroach/security"
)
func makeSQLClient() *sql.DB {
// Use the sql administrator by default (root user).
// TODO(marc): allow passing on the commandline.
db, err := sql.Open("cockroach",
fmt.Sprintf("%s://%s@%s?certs=%s",
context.HTTPRequestScheme(),
security.RootUser,
context.Addr,
context.Certs))
if err != nil {
fmt.Fprintf(osStderr, "failed to initialize SQL client: %s\n", err)
osExit(1)
}
return db
}
// fmtMap is a mapping from column name to a function that takes the raw input,
// and outputs the string to be displayed.
type fmtMap map[string]func(interface{}) string
// runQuery takes a 'query' with optional 'parameters'.
// It runs the sql query and returns a list of columns names and a list of rows.
func runQuery(db *sql.DB, query string, parameters ...interface{}) (
[]string, [][]string, error) {
return runQueryWithFormat(db, nil, query, parameters...)
}
// runQuery takes a 'query' with optional 'parameters'.
// It runs the sql query and returns a list of columns names and a list of rows.
// If 'format' is not nil, the values with column name
// found in the map are run through the corresponding callback.
func runQueryWithFormat(db *sql.DB, format fmtMap, query string, parameters ...interface{}) (
[]string, [][]string, error) {
rows, err := db.Query(query, parameters...)
if err != nil {
return nil, nil, fmt.Errorf("query error: %s", err)
}
defer rows.Close()
return sqlRowsToStrings(rows, format)
}
// runPrettyQueryWithFormat takes a 'query' with optional 'parameters'.
// It runs the sql query and writes pretty output to osStdout.
func runPrettyQuery(db *sql.DB, query string, parameters ...interface{}) error {
return runPrettyQueryWithFormat(db, nil, query, parameters...)
}
// runPrettyQueryWithFormat takes a 'query' with optional 'parameters'.
// It runs the sql query and writes pretty output to osStdout.
// If 'format' is not nil, the values with column name
// found in the map are run through the corresponding callback.
func runPrettyQueryWithFormat(db *sql.DB, format fmtMap, query string, parameters ...interface{}) error {
cols, allRows, err := runQueryWithFormat(db, format, query, parameters...)
if err != nil {
return err
}
return printQueryOutput(cols, allRows)
}
// sqlRowsToStrings turns 'rows' into a list of rows, each of which
// is a list of column values.
// 'rows' should be closed by the caller.
// If 'format' is not nil, the values with column name
// found in the map are run through the corresponding callback.
// It returns the header row followed by all data rows.
// If both the header row and list of rows are empty, it means no row
// information was returned (eg: statement was not a query).
func sqlRowsToStrings(rows *sql.Rows, format fmtMap) ([]string, [][]string, error) {
cols, err := rows.Columns()
if err != nil {
return nil, nil, fmt.Errorf("rows.Columns() error: %s", err)
}
if len(cols) == 0 {
return nil, nil, nil
}
vals := make([]interface{}, len(cols))
for i := range vals {
vals[i] = new(interface{})
}
allRows := [][]string{}
for rows.Next() {
rowStrings := make([]string, len(cols))
if err := rows.Scan(vals...); err != nil {
return nil, nil, fmt.Errorf("scan error: %s", err)
}
for i, v := range vals {
if f, ok := format[cols[i]]; ok {
rowStrings[i] = f(*v.(*interface{}))
} else {
rowStrings[i] = formatVal(*v.(*interface{}))
}
}
allRows = append(allRows, rowStrings)
}
return cols, allRows, nil
}
// printQueryOutput takes a list of column names and a list of row contents
// writes a pretty table to osStdout, or "OK" if empty.
func printQueryOutput(cols []string, allRows [][]string) error {
if len(cols) == 0 {
// This operation did not return rows, just show success.
fmt.Fprintln(osStdout, "OK")
return nil
}
// Initialize tablewriter and set column names as the header row.
table := tablewriter.NewWriter(osStdout)
table.SetAutoFormatHeaders(false)
table.SetAutoWrapText(false)
table.SetHeader(cols)
for _, row := range allRows {
if err := table.Append(row); err != nil {
return err
}
}
table.Render()
return nil
}
func formatVal(val interface{}) string {
switch t := val.(type) {
case nil:
return "NULL"
case []byte:
// Ensure that binary protobufs print escaped.
return fmt.Sprintf("%q", t)
}
return fmt.Sprint(val)
}