-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpsqlconn_service.go
306 lines (285 loc) · 7.69 KB
/
psqlconn_service.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package psqlconn
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
_ "github.com/lib/pq"
)
type PostgresService interface {
Pid() (int, error)
Database() string
Tables() ([]string, error)
FunctionsDescriptor() ([]string, error)
ProceduresDescriptor() ([]string, error)
FunctionDDescriptor(function string) ([]IFunctionDescriptor, error)
FunctionReturnType(function string) (string, error)
AddFunction(function string) (string, error)
FunctionDescriptor(function string) (string, error)
ProcedureDescriptor(procedure string) (string, error)
ExplainAnalysis(query string) (string, error)
ExplainAnalysisFile(filename string) (string, error)
ExecuteBatch(statements []string) error
ExecuteBatchWithTransaction(statements []string) error
TableDescriptor(table string) ([]ITableDescriptor, error)
TableInfo(table string) ([]ITableInfo, error)
}
type postgresServiceImpl struct {
dbConn *Postgres
}
func NewPostgresService(dbConn *Postgres) PostgresService {
p := &postgresServiceImpl{
dbConn: dbConn,
}
return p
}
func (p *postgresServiceImpl) Pid() (int, error) {
var pid int
err := p.dbConn.conn.QueryRow("SELECT pg_backend_pid() AS pid").Scan(&pid)
if err != nil {
return 0, err
}
return pid, nil
}
func (p *postgresServiceImpl) Tables() ([]string, error) {
var tableNames []string
err := p.dbConn.conn.Select(&tableNames, "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'")
if err != nil {
return nil, err
}
return tableNames, nil
}
func (p *postgresServiceImpl) FunctionsDescriptor() ([]string, error) {
var functions []string
err := p.dbConn.conn.Select(&functions, "SELECT routine_name FROM information_schema.routines WHERE routine_catalog = $1 AND routine_schema = 'public' AND routine_type = 'FUNCTION'", p.Database())
if err != nil {
return nil, err
}
return functions, nil
}
func (p *postgresServiceImpl) Database() string {
var database string
err := p.dbConn.conn.Get(&database, "SELECT current_database()")
if err != nil {
panic(err)
}
return database
}
func (p *postgresServiceImpl) ProceduresDescriptor() ([]string, error) {
var procedures []string
err := p.dbConn.conn.Select(&procedures, "SELECT routine_name FROM information_schema.routines WHERE routine_catalog = $1 AND routine_schema = 'public' AND routine_type = 'PROCEDURE'", p.Database())
if err != nil {
return nil, err
}
return procedures, nil
}
func (p *postgresServiceImpl) FunctionDDescriptor(function string) ([]IFunctionDescriptor, error) {
var functionDetails []IFunctionDescriptor
err := p.dbConn.conn.Select(&functionDetails, `
SELECT
r.routine_name,
p.data_type,
p.parameter_name,
p.parameter_mode
FROM information_schema.routines r
JOIN information_schema.parameters p
ON r.specific_name = p.specific_name
WHERE r.routine_catalog = $1
AND r.routine_schema = 'public'
AND r.routine_name = $2
`, p.Database(), function)
if err != nil {
return nil, err
}
return functionDetails, nil
}
func (p *postgresServiceImpl) FunctionReturnType(function string) (string, error) {
var returnType string
err := p.dbConn.conn.QueryRow("SELECT pg_get_function_result(oid) FROM pg_proc WHERE proname = $1", function).Scan(&returnType)
if err != nil {
return "", err
}
return returnType, nil
}
func (p *postgresServiceImpl) AddFunction(function string) (string, error) {
functionDetails, err := p.FunctionDDescriptor(function)
if err != nil {
return "", err
}
returnType, err := p.FunctionReturnType(function)
if err != nil {
return "", err
}
var builder strings.Builder
builder.WriteString("CREATE OR REPLACE FUNCTION " + function + "(")
for i, detail := range functionDetails {
if i > 0 {
builder.WriteString(", ")
}
builder.WriteString(detail.ParameterName + " " + detail.DataType)
if detail.ParameterMode != "IN" {
builder.WriteString(" " + detail.ParameterMode)
}
}
builder.WriteString(") RETURNS " + returnType + " AS $$\n")
builder.WriteString("BEGIN\n\n")
builder.WriteString("\n")
builder.WriteString("\nEND;\n$$ LANGUAGE plpgsql;")
return builder.String(), nil
}
func (ps *postgresServiceImpl) FunctionDescriptor(function string) (string, error) {
var functionContent string
err := ps.dbConn.conn.QueryRow("SELECT pg_get_functiondef($1::regproc)", function).Scan(&functionContent)
if err != nil {
return "", err
}
return functionContent, nil
}
func (p *postgresServiceImpl) ProcedureDescriptor(procedure string) (string, error) {
var procedureContent string
err := p.dbConn.conn.QueryRow("SELECT pg_get_functiondef($1::regproc)", procedure).Scan(&procedureContent)
if err != nil {
return "", err
}
return procedureContent, nil
}
func (p *postgresServiceImpl) ExplainAnalysis(query string) (string, error) {
rows, err := p.dbConn.conn.Query(fmt.Sprintf("EXPLAIN ANALYZE %v", query))
if err != nil {
return "", err
}
defer rows.Close()
var explain strings.Builder
for rows.Next() {
var line string
if err = rows.Scan(&line); err != nil {
return "", err
}
explain.WriteString(line)
explain.WriteString("\n")
}
if err = rows.Err(); err != nil {
return "", err
}
return explain.String(), nil
}
func (p *postgresServiceImpl) ExplainAnalysisFile(filename string) (string, error) {
bytes, err := ioutil.ReadFile(filepath.Clean(filename))
if err != nil {
return "", err
}
query := string(bytes)
return p.ExplainAnalysis(query)
}
func (p *postgresServiceImpl) ExecuteBatch(statements []string) error {
if len(statements) == 0 {
return fmt.Errorf("missing statements")
}
tx, err := p.dbConn.conn.Beginx()
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
for _, statement := range statements {
_, err := tx.Exec(statement)
if err != nil {
return err
}
}
return nil
}
func (p *postgresServiceImpl) ExecuteBatchWithTransaction(statements []string) error {
tx, err := p.dbConn.conn.Beginx()
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
err = p.ExecuteBatch(statements)
if err != nil {
return err
}
return nil
}
func (p *postgresServiceImpl) TableDescriptor(table string) ([]ITableDescriptor, error) {
s := `
SELECT conname AS c_name, 'Primary Key' AS type, '' as descriptor
FROM pg_constraint
WHERE conrelid = regclass($1)
AND confrelid = 0
AND contype = 'p'
UNION
SELECT conname AS c_name, 'Unique Key' AS type, '' as descriptor
FROM pg_constraint
WHERE conrelid = regclass($1)
AND confrelid = 0
AND contype = 'u'
UNION
SELECT indexname AS c_name, 'Index' AS type, indexdef as descriptor
FROM pg_indexes
WHERE tablename = $1;
`
rows, err := p.dbConn.conn.Query(s, table)
if err != nil {
return nil, err
}
defer rows.Close()
var results []ITableDescriptor
for rows.Next() {
var m ITableDescriptor
if err := rows.Scan(&m.Name, &m.Type, &m.Descriptor); err != nil {
return nil, err
}
results = append(results, m)
}
if err := rows.Err(); err != nil {
return nil, err
}
return results, nil
}
func (p *postgresServiceImpl) TableInfo(table string) ([]ITableInfo, error) {
s := `
SELECT
column_name,
data_type,
character_maximum_length
FROM
information_schema.columns
WHERE
table_name = $1;
`
rows, err := p.dbConn.conn.Query(s, table)
if err != nil {
return nil, err
}
defer rows.Close()
var results []ITableInfo
for rows.Next() {
var m ITableInfo
if err := rows.Scan(&m.Column, &m.Type, &m.MaxLength); err != nil {
return nil, err
}
results = append(results, m)
}
if err := rows.Err(); err != nil {
return nil, err
}
return results, nil
}