-
Notifications
You must be signed in to change notification settings - Fork 265
/
create_client.go
83 lines (67 loc) · 2.36 KB
/
create_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
package db_local
import (
"database/sql"
"fmt"
"log"
"github.com/turbot/steampipe/constants"
"github.com/turbot/steampipe/db/db_common"
"github.com/turbot/steampipe/utils"
)
func getLocalSteampipeConnectionString() (string, error) {
utils.LogTime("db.createDbClient start")
defer utils.LogTime("db.createDbClient end")
log.Println("[TRACE] createDbClient")
info, err := GetStatus()
if err != nil {
return "", err
}
if info == nil {
return "", fmt.Errorf("steampipe service is not running")
}
// Connect to the database using the first listen address, which is usually localhost
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=%s", info.Listen[0], info.Port, constants.DatabaseUser, info.Database, sslMode())
return psqlInfo, nil
}
type CreateDbOptions struct {
DatabaseName, Username string
}
// createLocalDbClient connects and returns a connection to the given database using
// the provided username
// if the database is not provided (empty), it connects to the default database in the service
// that was created during installation.
func createLocalDbClient(opts *CreateDbOptions) (*sql.DB, error) {
utils.LogTime("db.createDbClient start")
defer utils.LogTime("db.createDbClient end")
// load the db status
info, err := GetStatus()
if err != nil {
return nil, err
}
if info == nil {
return nil, fmt.Errorf("steampipe service is not running")
}
// if no database name is passed, deduce it from the db status
if len(opts.DatabaseName) == 0 {
opts.DatabaseName = info.Database
}
// if we still don't have it, fallback to default "postgres"
if len(opts.DatabaseName) == 0 {
opts.DatabaseName = "postgres"
}
// Connect to the database using the first listen address, which is usually localhost
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=%s", info.Listen[0], info.Port, opts.Username, opts.DatabaseName, sslMode())
log.Println("[TRACE] status: ", info)
log.Println("[TRACE] Connection string: ", psqlInfo)
// connect to the database using the postgres driver
utils.LogTime("db.createDbClient connection open start")
db, err := sql.Open("postgres", psqlInfo)
db.SetMaxOpenConns(1)
utils.LogTime("db.createDbClient connection open end")
if err != nil {
return nil, err
}
if db_common.WaitForConnection(db) {
return db, nil
}
return nil, fmt.Errorf("could not establish connection with database")
}