-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
200 lines (176 loc) · 6.67 KB
/
utils.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
package postgres
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"ariga.io/atlas/sql/postgres"
"ariga.io/atlas/sql/schema"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/turbot/steampipe-plugin-sdk/v5/grpc/proto"
"github.com/turbot/steampipe-plugin-sdk/v5/plugin"
)
func connect(connectionString string) (*sql.DB, error) {
return sql.Open("pgx", connectionString)
}
/*
GetAtlasSchemaForDBSchema gets the Atlas schema (as in, the metadata) for a Postgres schema (as in, the hierarchy below a database and above a table, such as `public`).
Must receive a connection string in the format expected by pgx (https://pkg.go.dev/github.com/jackc/pgx/v5#hdr-Establishing_a_Connection)
*/
func GetAtlasSchemaForDBSchema(ctx context.Context, connectionString, schema string) (*schema.Schema, error) {
conn, err := connect(connectionString)
if err != nil {
return nil, fmt.Errorf("can't connect to DB: %w", err)
}
driver, err := postgres.Open(conn)
if err != nil {
return nil, fmt.Errorf("can't open Postgres driver: %w", err)
}
sch, err := driver.InspectSchema(ctx, schema, nil)
if err != nil {
return nil, fmt.Errorf("error inspecting schema: %w", err)
}
return sch, nil
}
/*
FindCommentOnAttrs tries to locate an Attr among the passed array that corresponds to a comment, and returns it if found.
Otherwise, returns an empty string.
This function can be used to identify the comment that is attached to a schema, table or column.
*/
func FindCommentOnAttrs(attrs []schema.Attr) string {
var comment string
for _, attr := range attrs {
if _attr, ok := attr.(*schema.Comment); ok {
comment = _attr.Text
}
}
return comment
}
/*
PostgresColTypeToSteampipeColType converts an Atlas column type to a Steampipe column.
Atlas column types correspond almost one-to-one to actual SQL types, either standard SQL or Postgres extensions.
For example, DECIMAL, FLOAT and CURRENCY become DOUBLEs on Steampipe
*/
func PostgresColTypeToSteampipeColType(ctx context.Context, col *schema.Column) proto.ColumnType {
var x proto.ColumnType
switch t := col.Type.Type.(type) {
case *schema.BinaryType, *postgres.BitType, *schema.EnumType, *schema.StringType, *schema.UUIDType:
x = proto.ColumnType_STRING
case *schema.BoolType:
x = proto.ColumnType_BOOL
case *schema.DecimalType, *schema.FloatType, *postgres.CurrencyType:
x = proto.ColumnType_DOUBLE
case *schema.IntegerType, *postgres.SerialType:
x = proto.ColumnType_INT
case *schema.JSONType:
x = proto.ColumnType_JSON
case *schema.TimeType, *postgres.IntervalType:
x = proto.ColumnType_TIMESTAMP
case *postgres.NetworkType:
if t.T == "inet" {
x = proto.ColumnType_INET
} else if t.T == "cidr" {
x = proto.ColumnType_CIDR
} else {
x = proto.ColumnType_UNKNOWN
}
default:
// As of writing this, these are the types that fall here, AKA those that we don't know how to translate
// *schema.SpatialType, *schema.UnsupportedType, *postgres.TextSearchType, *postgres.ArrayType, *postgres.OIDType, *postgres.RangeType, *postgres.UserDefinedType, *postgres.XMLType
x = proto.ColumnType_UNKNOWN
}
return x
}
/*
Builds a slice to hold the columns of a single result row. Returns an array of pointers, that can be passed to DB.Scan()
*/
func prepareSliceForScanResults(columns []string) []any {
arr := make([]any, len(columns))
// Convert arr into an array of pointers, so we can save the results there
for i := range arr {
arr[i] = &arr[i]
}
return arr
}
func protoToPostgresValue(val *proto.QualValue) string {
switch val.GetValue().(type) {
case *proto.QualValue_BoolValue:
return fmt.Sprintf("%t", val.GetBoolValue())
case *proto.QualValue_DoubleValue:
return fmt.Sprintf("%f", val.GetDoubleValue())
case *proto.QualValue_InetValue:
return fmt.Sprintf("'%s'", val.GetInetValue().GetCidr())
case *proto.QualValue_Int64Value:
return fmt.Sprintf("%d", val.GetInt64Value())
case *proto.QualValue_JsonbValue:
return fmt.Sprintf("'%s'", val.GetJsonbValue())
case *proto.QualValue_StringValue:
return fmt.Sprintf("'%s'", val.GetStringValue())
case *proto.QualValue_TimestampValue:
return fmt.Sprintf("'%s'", val.GetTimestampValue().AsTime().Format(time.RFC3339))
default:
return "<INVALID>" // this will probably cause an error on the query, which is OK
}
}
/*
MakeSQLQuery composes a SQL query from a set of quals, sends it to a remote DB, and returns any results
*/
func MakeSQLQuery(ctx context.Context, connectionString, schema string, table string, quals plugin.KeyColumnQualMap) ([]map[string]any, error) {
query := fmt.Sprintf("SELECT * FROM %s.%s", schema, table)
// If there are any quals, build up a WHERE clause
conds := make([]string, 0)
for _, qualsForCol := range quals {
for _, qual := range qualsForCol.Quals {
if qual.Value.Value == nil {
conds = append(conds, fmt.Sprintf("%s %s", qual.Column, qual.Operator))
} else {
conds = append(conds, fmt.Sprintf("%s %s %s", qual.Column, qual.Operator, protoToPostgresValue(qual.Value)))
}
}
}
// If there are any quals, actually append the WHERE ... part to the query string (which currently has SELECT * FROM tablename)
if len(conds) > 0 {
query = query + " WHERE " + strings.Join(conds, " AND ")
}
return MakeRawSQLQuery(ctx, connectionString, schema, table, query)
}
/*
MakeRawSQLQuery sends a raw SQL query to a remote DB, and returns any results
*/
func MakeRawSQLQuery(ctx context.Context, connectionString, schema string, table string, query string) ([]map[string]any, error) {
conn, err := connect(connectionString)
if err != nil {
return nil, fmt.Errorf("can't connect to DB: %w", err)
}
defer conn.Close()
plugin.Logger(ctx).Debug("MakeRawSQLQuery.beforeExec", "query", query)
rows, err := conn.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("error while making query \"%s\": %w", query, err)
}
defer rows.Close()
colNames, err := rows.Columns()
if err != nil {
return nil, fmt.Errorf("error while reading column names: %w", err)
}
// The code here that stores results on a slice of map[string]any was inspired by https://lazypro.medium.com/make-sql-scan-result-be-map-in-golang-e04f0de5950f
var results []map[string]any
for rows.Next() {
rowData := make(map[string]any)
cols := prepareSliceForScanResults(colNames)
if err := rows.Scan(cols...); err != nil {
return nil, fmt.Errorf("error while reading columns: %w", err)
}
for i, v := range cols {
rowData[colNames[i]] = v
}
plugin.Logger(ctx).Debug("Scan", "data", cols, "mapData", rowData)
results = append(results, rowData)
}
// This must always be called after the for rows.Next() loop, since it may have terminated with an error
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error while reading columns: %w", err)
}
return results, nil
}