-
Notifications
You must be signed in to change notification settings - Fork 10
/
connection.go
86 lines (79 loc) · 1.71 KB
/
connection.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
package main
import (
"database/sql"
"encoding/json"
)
const (
selectConnectionSQL = `SELECT key, data
FROM connections WHERE
workspace_id = $1
AND key = $2
LIMIT 1
`
insertConnectionSQL = `
WITH existing_connection AS (
UPDATE connections SET data = $3
WHERE workspace_id = $1 AND key = $2
RETURNING key
),
inserted_connection AS (
INSERT INTO connections(workspace_id, key, data)
SELECT $1, $2, $3
WHERE NOT EXISTS (SELECT 1 FROM existing_connection)
RETURNING key
)
SELECT * FROM inserted_connection
UNION
SELECT * FROM existing_connection
`
)
type Connection struct {
workspaceID int
serviceID string
pipeID string
key string
Data map[string]int
}
func NewConnection(s Service, pipeID string) *Connection {
return &Connection{
workspaceID: s.WorkspaceID(),
key: s.keyFor(pipeID),
Data: make(map[string]int),
}
}
func loadConnection(s Service, pipeID string) (*Connection, error) {
rows, err := db.Query(selectConnectionSQL, s.WorkspaceID(), s.keyFor(pipeID))
if err != nil {
return nil, err
}
defer rows.Close()
connection := Connection{Data: make(map[string]int)}
if rows.Next() {
if err := connection.load(rows); err != nil {
return nil, err
}
}
return &connection, nil
}
func (c *Connection) save() error {
b, err := json.Marshal(c)
if err != nil {
return err
}
_, err = db.Exec(insertConnectionSQL, c.workspaceID, c.key, b)
if err != nil {
return err
}
return nil
}
func (c *Connection) load(rows *sql.Rows) error {
var b []byte
if err := rows.Scan(&c.key, &b); err != nil {
return err
}
err := json.Unmarshal(b, c)
if err != nil {
return err
}
return nil
}