/
postgres_driver.go
203 lines (168 loc) · 4.52 KB
/
postgres_driver.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
package adapters
import (
"bytes"
"context"
"database/sql"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
nurl "net/url"
"strings"
"github.com/kndndrj/nvim-dbee/dbee/core"
"github.com/kndndrj/nvim-dbee/dbee/core/builders"
)
var (
_ core.Driver = (*postgresDriver)(nil)
_ core.DatabaseSwitcher = (*postgresDriver)(nil)
)
type postgresDriver struct {
c *builders.Client
url *nurl.URL
}
func (c *postgresDriver) Query(ctx context.Context, query string) (core.ResultStream, error) {
action := strings.ToLower(strings.Split(query, " ")[0])
hasReturnValues := strings.Contains(strings.ToLower(query), " returning ")
if (action == "update" || action == "delete" || action == "insert") && !hasReturnValues {
return c.c.Exec(ctx, query)
}
return c.c.QueryUntilNotEmpty(ctx, query)
}
func (c *postgresDriver) Columns(opts *core.TableOptions) ([]*core.Column, error) {
return c.c.ColumnsFromQuery(`
SELECT column_name, data_type
FROM information_schema.columns
WHERE
table_schema='%s' AND
table_name='%s'
`, opts.Schema, opts.Table)
}
func (c *postgresDriver) Structure() ([]*core.Structure, error) {
query := `
SELECT table_schema, table_name, table_type FROM information_schema.tables UNION ALL
SELECT schemaname, matviewname, 'VIEW' FROM pg_matviews;
`
rows, err := c.Query(context.TODO(), query)
if err != nil {
return nil, err
}
return getPGStructure(rows)
}
func (c *postgresDriver) Close() {
c.c.Close()
}
func (c *postgresDriver) ListDatabases() (current string, available []string, err error) {
query := `
SELECT current_database(), datname FROM pg_database
WHERE datistemplate = false
AND datname != current_database();
`
rows, err := c.Query(context.TODO(), query)
if err != nil {
return "", nil, err
}
for rows.HasNext() {
row, err := rows.Next()
if err != nil {
return "", nil, err
}
// We know for a fact there are 2 string fields (see query above)
current = row[0].(string)
available = append(available, row[1].(string))
}
return current, available, nil
}
func (c *postgresDriver) SelectDatabase(name string) error {
c.url.Path = fmt.Sprintf("/%s", name)
db, err := sql.Open("postgres", c.url.String())
if err != nil {
return fmt.Errorf("unable to switch databases: %w", err)
}
c.c.Swap(db)
return nil
}
// getPGStructure fetches the layout from the postgres database.
// rows is at least 3 column wide result
func getPGStructure(rows core.ResultStream) ([]*core.Structure, error) {
children := make(map[string][]*core.Structure)
for rows.HasNext() {
row, err := rows.Next()
if err != nil {
return nil, err
}
if len(row) < 3 {
return nil, errors.New("could not retrieve structure: insufficient info")
}
schema, table, tableType := row[0].(string), row[1].(string), row[2].(string)
children[schema] = append(children[schema], &core.Structure{
Name: table,
Schema: schema,
Type: getPGStructureType(tableType),
})
}
var structure []*core.Structure
for k, v := range children {
structure = append(structure, &core.Structure{
Name: k,
Schema: k,
Type: core.StructureTypeNone,
Children: v,
})
}
return structure, nil
}
// getPGStructureType returns the structure type based on the provided string.
func getPGStructureType(typ string) core.StructureType {
switch typ {
case "TABLE", "BASE TABLE", "FOREIGN", "FOREIGN TABLE":
return core.StructureTypeTable
case "VIEW", "SYSTEM VIEW":
return core.StructureTypeView
default:
return core.StructureTypeNone
}
}
// postgresJSONResponse serves as a wrapper around the json response
// to pretty-print the return values
type postgresJSONResponse struct {
value []byte
}
func newPostgresJSONResponse(val []byte) *postgresJSONResponse {
return &postgresJSONResponse{
value: val,
}
}
func (pj *postgresJSONResponse) String() string {
var parsed bytes.Buffer
err := json.Indent(&parsed, pj.value, "", " ")
if err != nil {
return string(pj.value)
}
return parsed.String()
}
func (pj *postgresJSONResponse) MarshalJSON() ([]byte, error) {
if json.Valid(pj.value) {
return pj.value, nil
}
return json.Marshal(pj.value)
}
func (pj *postgresJSONResponse) GobEncode() ([]byte, error) {
var err error
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
err = encoder.Encode(pj.value)
if err != nil {
return nil, err
}
return w.Bytes(), err
}
func (pj *postgresJSONResponse) GobDecode(buf []byte) error {
var err error
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
err = decoder.Decode(&pj.value)
if err != nil {
return err
}
return err
}