forked from grafana/xk6-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.go
79 lines (64 loc) · 1.54 KB
/
sql.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
package sql
import (
dbsql "database/sql"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"go.k6.io/k6/js/modules"
)
func init() {
modules.Register("k6/x/sql", new(SQL))
}
// SQL is the k6 SQL plugin.
type SQL struct{}
type keyValue map[string]interface{}
func contains(array []string, element string) bool {
for _, item := range array {
if item == element {
return true
}
}
return false
}
func (*SQL) Open(database string, connectionString string) (*dbsql.DB, error) {
supportedDatabases := []string{"mysql", "postgres", "sqlite3", "sqlserver"}
if !contains(supportedDatabases, database) {
return nil, fmt.Errorf("database %s is not supported", database)
}
db, err := dbsql.Open(database, connectionString)
if err != nil {
return nil, err
}
return db, nil
}
func (*SQL) Query(db *dbsql.DB, query string, args ...interface{}) ([]keyValue, error) {
rows, err := db.Query(query, args...)
if err != nil {
return nil, err
}
cols, err := rows.Columns()
if err != nil {
return nil, err
}
values := make([]interface{}, len(cols))
valuePtrs := make([]interface{}, len(cols))
result := make([]keyValue, 0)
for rows.Next() {
for i := range values {
valuePtrs[i] = &values[i]
}
err := rows.Scan(valuePtrs...)
if err != nil {
return nil, err
}
data := make(keyValue, len(cols))
for i, colName := range cols {
data[colName] = *valuePtrs[i].(*interface{})
}
result = append(result, data)
}
rows.Close()
return result, nil
}