Skip to content

Commit

Permalink
wrap sql query in goqu
Browse files Browse the repository at this point in the history
  • Loading branch information
sasha-bitfly committed Jan 17, 2025
1 parent ac58ef8 commit e2d5e13
Showing 1 changed file with 45 additions and 39 deletions.
84 changes: 45 additions & 39 deletions backend/pkg/api/data_access/vdb_summary.go
Original file line number Diff line number Diff line change
Expand Up @@ -525,45 +525,51 @@ func (d *DataAccessService) GetValidatorDashboardGroupSummary(ctx context.Contex
// Initialize the result variable
var totalMissedRewardsEl float64

// SQL query
query := `
WITH targets AS (
SELECT
b.slot AS slot
FROM
blocks b
JOIN
users_val_dashboards_validators uvdv
ON
b.proposer = uvdv.validator_index
WHERE
uvdv.dashboard_id = $1
AND b.status != '1'
AND epoch >= $2
AND epoch <= $3
),
res AS (
SELECT
a.slot,
percentile_cont(0.5) WITHIN GROUP (ORDER BY b.value)::numeric(76,0) AS v
FROM
targets a
LEFT JOIN
execution_rewards_finalized b
ON
b.slot >= a.slot - 16
AND b.slot < a.slot + 16
GROUP BY
a.slot
)
SELECT
COALESCE(SUM(v), 0)
FROM
res;
`

// Execute the query with the provided parameters
err := d.readerDb.GetContext(ctx, &totalMissedRewardsEl, query, dashboardId.Id, epochStart, epochEnd)
// Define the `targets` CTE
targets := goqu.
From("blocks").
Join(
goqu.T("users_val_dashboards_validators").As("uvdv"),
goqu.On(goqu.I("blocks.proposer").Eq(goqu.I("uvdv.validator_index"))),
).
Where(
goqu.I("blocks.status").Neq("1"),
goqu.I("uvdv.dashboard_id").Eq(dashboardId.Id),
goqu.I("epoch").Gte(epochStart),
goqu.I("epoch").Lte(epochEnd),
).
Select(goqu.I("blocks.slot").As("slot"))

// Define the `res` CTE
res := goqu.
From("targets").
LeftJoin(
goqu.T("execution_rewards_finalized").As("b"),
goqu.On(
goqu.I("b.slot").Gte(goqu.L("targets.slot - 16")),
goqu.I("b.slot").Lt(goqu.L("targets.slot + 16")),
),
).
Select(
goqu.I("targets.slot"),
goqu.L("percentile_cont(0.5) WITHIN GROUP (ORDER BY b.value)::numeric(76,0)").As("v"),
).
GroupBy(goqu.I("targets.slot"))

// Build the final query
query := goqu.From("res").
With("targets", targets).
With("res", res).
Select(goqu.L("COALESCE(SUM(v), 0)"))

// Generate SQL and arguments
sql, args, err := query.ToSQL()
if err != nil {
return 0, fmt.Errorf("failed to generate SQL: %w", err)
}

// Execute the query with the generated SQL and arguments
err = d.readerDb.GetContext(ctx, &totalMissedRewardsEl, sql, args...)
if err != nil {
return 0, fmt.Errorf("failed to execute query: %w", err)
}
Expand Down

0 comments on commit e2d5e13

Please sign in to comment.