forked from sosedoff/pgweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
258 lines (194 loc) · 5.17 KB
/
client.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package client
import (
"fmt"
"reflect"
_ "github.com/lib/pq"
"github.com/jmoiron/sqlx"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/connection"
"github.com/sosedoff/pgweb/pkg/history"
"github.com/sosedoff/pgweb/pkg/statements"
)
type Client struct {
db *sqlx.DB
History []history.Record `json:"history"`
ConnectionString string `json:"connection_string"`
}
// Struct to hold table rows browsing options
type RowsOptions struct {
Where string // Custom filter
Offset int // Number of rows to skip
Limit int // Number of rows to fetch
SortColumn string // Column to sort by
SortOrder string // Sort direction (ASC, DESC)
}
func New() (*Client, error) {
str, err := connection.BuildString(command.Opts)
if command.Opts.Debug && str != "" {
fmt.Println("Creating a new client for:", str)
}
if err != nil {
return nil, err
}
db, err := sqlx.Open("postgres", str)
if err != nil {
return nil, err
}
client := Client{
db: db,
ConnectionString: str,
History: history.New(),
}
return &client, nil
}
func NewFromUrl(url string) (*Client, error) {
if command.Opts.Debug {
fmt.Println("Creating a new client for:", url)
}
db, err := sqlx.Open("postgres", url)
if err != nil {
return nil, err
}
client := Client{
db: db,
ConnectionString: url,
History: history.New(),
}
return &client, nil
}
func (client *Client) Test() error {
return client.db.Ping()
}
func (client *Client) Info() (*Result, error) {
return client.query(statements.PG_INFO)
}
func (client *Client) Databases() ([]string, error) {
return client.fetchRows(statements.PG_DATABASES)
}
func (client *Client) Schemas() ([]string, error) {
return client.fetchRows(statements.PG_SCHEMAS)
}
func (client *Client) Tables() ([]string, error) {
return client.fetchRows(statements.PG_TABLES)
}
func (client *Client) Table(table string) (*Result, error) {
return client.query(statements.PG_TABLE_SCHEMA, table)
}
func (client *Client) TableRows(table string, opts RowsOptions) (*Result, error) {
sql := fmt.Sprintf(`SELECT * FROM "%s"`, table)
if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where)
}
if opts.SortColumn != "" {
if opts.SortOrder == "" {
opts.SortOrder = "ASC"
}
sql += fmt.Sprintf(" ORDER BY %s %s", opts.SortColumn, opts.SortOrder)
}
if opts.Limit > 0 {
sql += fmt.Sprintf(" LIMIT %d", opts.Limit)
}
if opts.Offset > 0 {
sql += fmt.Sprintf(" OFFSET %d", opts.Offset)
}
return client.query(sql)
}
func (client *Client) TableRowsCount(table string, opts RowsOptions) (*Result, error) {
sql := fmt.Sprintf(`SELECT COUNT(1) FROM "%s"`, table)
if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where)
}
return client.query(sql)
}
func (client *Client) TableInfo(table string) (*Result, error) {
return client.query(statements.PG_TABLE_INFO, table)
}
func (client *Client) TableIndexes(table string) (*Result, error) {
res, err := client.query(statements.PG_TABLE_INDEXES, table)
if err != nil {
return nil, err
}
return res, err
}
func (client *Client) TableConstraints(table string) (*Result, error) {
res, err := client.query(statements.PG_TABLE_CONSTRAINTS, table)
if err != nil {
return nil, err
}
return res, err
}
func (client *Client) Sequences() ([]string, error) {
return client.fetchRows(statements.PG_SEQUENCES)
}
// Returns all active queriers on the server
func (client *Client) Activity() (*Result, error) {
return client.query(statements.PG_ACTIVITY)
}
func (client *Client) Query(query string) (*Result, error) {
res, err := client.query(query)
// Save history records only if query did not fail
if err == nil && !client.hasHistoryRecord(query) {
client.History = append(client.History, history.NewRecord(query))
}
return res, err
}
func (client *Client) query(query string, args ...interface{}) (*Result, error) {
rows, err := client.db.Queryx(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return nil, err
}
result := Result{Columns: cols}
for rows.Next() {
obj, err := rows.SliceScan()
for i, item := range obj {
if item == nil {
obj[i] = nil
} else {
t := reflect.TypeOf(item).Kind().String()
if t == "slice" {
obj[i] = string(item.([]byte))
}
}
}
if err == nil {
result.Rows = append(result.Rows, obj)
}
}
result.PrepareBigints()
return &result, nil
}
// Close database connection
func (client *Client) Close() error {
if client.db != nil {
return client.db.Close()
}
return nil
}
// Fetch all rows as strings for a single column
func (client *Client) fetchRows(q string) ([]string, error) {
res, err := client.query(q)
if err != nil {
return nil, err
}
// Init empty slice so json.Marshal will encode it to "[]" instead of "null"
results := make([]string, 0)
for _, row := range res.Rows {
results = append(results, row[0].(string))
}
return results, nil
}
func (client *Client) hasHistoryRecord(query string) bool {
result := false
for _, record := range client.History {
if record.Query == query {
result = true
break
}
}
return result
}