File size: 1,234 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package swoinfo

import (
	"context"

	"github.com/jackc/pgx/v5"
	"github.com/target/goalert/swo/swodb"
)

// ConnCount represents the number of connections to a database for the given application name.
type ConnCount struct {
	// Name is the application name of the connection.
	Name string

	// IsNext indicates that the connection is to the new database.
	IsNext bool

	Count int
}

// ConnInfo provides information about the connections to both old and new databases.
func ConnInfo(ctx context.Context, oldConn, newConn *pgx.Conn) ([]ConnCount, error) {
	oldConns, err := swodb.New(oldConn).ConnectionInfo(ctx)
	if err != nil {
		return nil, err
	}
	newConns, err := swodb.New(newConn).ConnectionInfo(ctx)
	if err != nil {
		return nil, err
	}

	type connType struct {
		Name   string
		IsNext bool
	}
	counts := make(map[connType]int)
	for _, oldConn := range oldConns {
		counts[connType{Name: oldConn.Name.String}] += int(oldConn.Count)
	}
	for _, newConn := range newConns {
		counts[connType{Name: newConn.Name.String, IsNext: true}] += int(newConn.Count)
	}

	var result []ConnCount
	for t, count := range counts {
		result = append(result, ConnCount{Name: t.Name, IsNext: t.IsNext, Count: count})
	}

	return result, nil
}