From e2d5e13553a7ea1aacd81aaba3a57c4c5a8d585e Mon Sep 17 00:00:00 2001 From: Sasha Zezulinsky <188990923+sasha-bitfly@users.noreply.github.com> Date: Fri, 17 Jan 2025 11:13:15 +0000 Subject: [PATCH] wrap sql query in goqu --- backend/pkg/api/data_access/vdb_summary.go | 84 ++++++++++++---------- 1 file changed, 45 insertions(+), 39 deletions(-) diff --git a/backend/pkg/api/data_access/vdb_summary.go b/backend/pkg/api/data_access/vdb_summary.go index 308284ebb..5503a56c7 100644 --- a/backend/pkg/api/data_access/vdb_summary.go +++ b/backend/pkg/api/data_access/vdb_summary.go @@ -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) }