github.com/supabase/cli@v1.168.1/internal/inspect/role_connections/role_connections.go (about)

     1  package role_connections
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/go-errors/errors"
     8  	"github.com/jackc/pgconn"
     9  	"github.com/jackc/pgx/v4"
    10  	"github.com/spf13/afero"
    11  	"github.com/supabase/cli/internal/inspect"
    12  	"github.com/supabase/cli/internal/migration/list"
    13  	"github.com/supabase/cli/internal/utils"
    14  	"github.com/supabase/cli/internal/utils/pgxv5"
    15  )
    16  
    17  type Result struct {
    18  	Rolname            string
    19  	Active_connections int
    20  	Connection_limit   int
    21  }
    22  
    23  func Run(ctx context.Context, config pgconn.Config, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
    24  	conn, err := utils.ConnectByConfig(ctx, config, options...)
    25  	if err != nil {
    26  		return err
    27  	}
    28  	rows, err := conn.Query(ctx, inspect.ROLE_CONNECTIONS_QUERY)
    29  	if err != nil {
    30  		return errors.Errorf("failed to query rows: %w", err)
    31  	}
    32  	result, err := pgxv5.CollectRows[Result](rows)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	table := "|Role Name|Active connction|\n|-|-|\n"
    38  	sum := 0
    39  	for _, r := range result {
    40  		table += fmt.Sprintf("|`%s`|`%d`|\n", r.Rolname, r.Active_connections)
    41  		sum += r.Active_connections
    42  	}
    43  
    44  	if err := list.RenderTable(table); err != nil {
    45  		return err
    46  	}
    47  
    48  	if len(result) > 0 {
    49  		fmt.Printf("\nActive connections %d/%d\n\n", sum, result[0].Connection_limit)
    50  	}
    51  
    52  	if matches := utils.ProjectHostPattern.FindStringSubmatch(config.Host); len(matches) == 4 {
    53  		fmt.Println("Go to the dashboard for more here:")
    54  		fmt.Printf("https://app.supabase.com/project/%s/database/roles\n", matches[2])
    55  	}
    56  
    57  	return nil
    58  }