Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Group by in Coordinator SHOW #771

Merged
merged 5 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 101 additions & 17 deletions pkg/clientinteractor/interactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ const TEXTOID = 25
// DOUBLEOID https://github.com/postgres/postgres/blob/master/src/include/catalog/pg_type.dat#L223
const DOUBLEOID = 701

// INTOID https://github.com/postgres/postgres/blob/master/src/include/catalog/pg_type.dat#L55
const INTOID = 20

// TODO : unit tests

// TextOidFD generates a pgproto3.FieldDescription object with the provided statement text.
Expand All @@ -106,6 +109,13 @@ func TextOidFD(stmt string) pgproto3.FieldDescription {
}
}

// FloatOidFD generates a pgproto3.FieldDescription object of FLOAT8 type with the provided statement text.
//
// Parameters:
// - stmt (string): The statement text to use in the FieldDescription.
//
// Returns:
// - A pgproto3.FieldDescription object initialized with the provided statement text and default values.
func FloatOidFD(stmt string) pgproto3.FieldDescription {
return pgproto3.FieldDescription{
Name: []byte(stmt),
Expand All @@ -118,6 +128,25 @@ func FloatOidFD(stmt string) pgproto3.FieldDescription {
}
}

// IntOidFD generates a pgproto3.FieldDescription object of INT type with the provided statement text.
//
// Parameters:
// - stmt (string): The statement text to use in the FieldDescription.
//
// Returns:
// - A pgproto3.FieldDescription object initialized with the provided statement text and default values.
func IntOidFD(stmt string) pgproto3.FieldDescription {
return pgproto3.FieldDescription{
Name: []byte(stmt),
TableOID: 0,
TableAttributeNumber: 0,
DataTypeOID: INTOID,
DataTypeSize: 8,
TypeModifier: -1,
Format: 0,
}
}

// TODO : unit tests

// WriteHeader sends the row description message with the specified field descriptions.
Expand Down Expand Up @@ -1298,32 +1327,58 @@ func (pi *PSQLInteractor) KillClient(clientID uint) error {
// BackendConnections writes backend connection information to the PSQL client.
//
// Parameters:
// - ctx (context.Context): The context for the operation.
// - _ (context.Context): The context for the operation.
// - shs ([]shard.Shardinfo): The list of shard information.
// - stmt (*spqrparser.Show): The query itself.
//
// Returns:
// - error: An error if any occurred during the operation.
func (pi *PSQLInteractor) BackendConnections(ctx context.Context, shs []shard.Shardinfo) error {
if err := pi.WriteHeader("backend connection id", "router", "shard key name", "hostname", "pid", "user", "dbname", "sync", "tx_served", "tx status"); err != nil {
spqrlog.Zero.Error().Err(err).Msg("")
return err
}

for _, sh := range shs {
router := "no data"
s, ok := sh.(shard.CoordShardinfo)
if ok {
router = s.Router()
}

if err := pi.WriteDataRow(fmt.Sprintf("%d", sh.ID()), router, sh.ShardKeyName(), sh.InstanceHostname(), fmt.Sprintf("%d", sh.Pid()), sh.Usr(), sh.DB(), strconv.FormatInt(sh.Sync(), 10), strconv.FormatInt(sh.TxServed(), 10), sh.TxStatus().String()); err != nil {
func (pi *PSQLInteractor) BackendConnections(_ context.Context, shs []shard.Shardinfo, stmt *spqrparser.Show) error {
headers := []string{"backend connection id", "router", "shard key name", "hostname", "pid", "user", "dbname", "sync", "tx_served", "tx status"}
getters := []func(sh shard.Shardinfo) string{
func(sh shard.Shardinfo) string { return fmt.Sprintf("%d", sh.ID()) },
func(sh shard.Shardinfo) string {
router := "no data"
s, ok := sh.(shard.CoordShardinfo)
if ok {
router = s.Router()
}
return router
},
func(sh shard.Shardinfo) string { return sh.ShardKeyName() },
func(sh shard.Shardinfo) string { return sh.InstanceHostname() },
func(sh shard.Shardinfo) string { return fmt.Sprintf("%d", sh.Pid()) },
func(sh shard.Shardinfo) string { return sh.Usr() },
func(sh shard.Shardinfo) string { return sh.DB() },
func(sh shard.Shardinfo) string { return strconv.FormatInt(sh.Sync(), 10) },
func(sh shard.Shardinfo) string { return strconv.FormatInt(sh.TxServed(), 10) },
func(sh shard.Shardinfo) string { return sh.TxStatus().String() },
}

switch gb := stmt.GroupBy.(type) {
case spqrparser.GroupBy:
return groupBy(headers, shs, getters, gb.Col.ColName, pi)
case spqrparser.GroupByClauseEmpty:
if err := pi.WriteHeader(headers...); err != nil {
spqrlog.Zero.Error().Err(err).Msg("")
return err
}

}
for _, sh := range shs {
vals := make([]string, 0)
for _, getter := range getters {
vals = append(vals, getter(sh))
}
if err := pi.WriteDataRow(vals...); err != nil {
spqrlog.Zero.Error().Err(err).Msg("")
return err
}
}

return pi.CompleteMsg(len(shs))
return pi.CompleteMsg(len(shs))
default:
return spqrerror.NewByCode(spqrerror.SPQR_INVALID_REQUEST)
}
}

// TODO unit tests
Expand Down Expand Up @@ -1408,3 +1463,32 @@ func (pi *PSQLInteractor) PreparedStatements(ctx context.Context, shs []shard.Pr

return pi.CompleteMsg(len(shs))
}

func groupBy[T any](headers []string, values []T, getters []func(s T) string, groupByCol string, pi *PSQLInteractor) error {
ind := -1
for i, header := range headers {
if header == groupByCol {
if err := pi.cl.Send(&pgproto3.RowDescription{
Fields: []pgproto3.FieldDescription{TextOidFD(groupByCol), IntOidFD("count")},
}); err != nil {
spqrlog.Zero.Error().Err(err).Msg("Could not write header for backend connections")
return err
}
ind = i
break
}
}

cnt := make(map[string]int)
for _, value := range values {
cnt[getters[ind](value)]++
}

for k, v := range cnt {
if err := pi.WriteDataRow(k, fmt.Sprintf("%d", v)); err != nil {
return err
}
}

return pi.CompleteMsg(len(cnt))
}
2 changes: 1 addition & 1 deletion pkg/meta/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ func ProcessShow(ctx context.Context, stmt *spqrparser.Show, mngr EntityMgr, ci
return err
}

return cli.BackendConnections(ctx, resp)
return cli.BackendConnections(ctx, resp, stmt)
case spqrparser.ShardsStr:
shards, err := mngr.ListShards(ctx)
if err != nil {
Expand Down
55 changes: 55 additions & 0 deletions test/feature/features/coordinator_show.feature
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,61 @@ Feature: Coordinator show clients, pools and backend_connections
]
"""

Scenario: 'show backend_connections group by hostname' works
When I run SQL on host "coordinator"
"""
SHOW backend_connections group by hostname
"""
Then command return code should be "0"
And SQL result should match json
"""
[
{
"hostname":"spqr_shard_1:6432",
"count": "2"
}
]
"""
And SQL result should match json
"""
[
{
"hostname":"spqr_shard_2:6432",
"count": "2"
}
]
"""

When I run SQL on host "coordinator"
"""
SHOW backend_connections group by user
"""
Then command return code should be "0"
And SQL result should match json
"""
[
{
"user":"regress",
"count": "4"
}
]
"""

When I run SQL on host "coordinator"
"""
SHOW backend_connections group by dbname
"""
Then command return code should be "0"
And SQL result should match json
"""
[
{
"dbname":"regress",
"count": "4"
}
]
"""

Scenario: show pools works
When I run SQL on host "coordinator"
"""
Expand Down
18 changes: 15 additions & 3 deletions yacc/console/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ type Order struct {
Col ColumnRef
}

type GroupByClause interface{}

type GroupByClauseEmpty struct {
GroupByClause
}

type GroupBy struct {
GroupByClause
Col ColumnRef
}

type WhereClauseNode interface {
}

Expand All @@ -47,9 +58,10 @@ type WhereClauseOp struct {
}

type Show struct {
Cmd string
Where WhereClauseNode
Order OrderClause
Cmd string
Where WhereClauseNode
Order OrderClause
GroupBy GroupByClause
}

type Set struct {
Expand Down
Loading
Loading