2020-07-23 02:37:34 +00:00
|
|
|
package scheduler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
2020-08-27 21:09:03 +00:00
|
|
|
|
2020-07-23 02:37:34 +00:00
|
|
|
"golang.org/x/xerrors"
|
|
|
|
)
|
|
|
|
|
2020-07-24 20:11:16 +00:00
|
|
|
func setupTopMinerByBaseRewardSchema(ctx context.Context, db *sql.DB) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
tx, err := db.Begin()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := tx.Exec(`
|
|
|
|
create materialized view if not exists top_miners_by_base_reward as
|
|
|
|
with total_rewards_by_miner as (
|
|
|
|
select
|
|
|
|
b.miner,
|
2020-08-28 00:09:33 +00:00
|
|
|
sum(cr.new_reward * b.win_count) as total_reward
|
2020-07-24 20:11:16 +00:00
|
|
|
from blocks b
|
2020-08-28 00:09:33 +00:00
|
|
|
inner join chain_reward cr on b.parentstateroot = cr.state_root
|
2020-07-24 20:11:16 +00:00
|
|
|
group by 1
|
|
|
|
) select
|
|
|
|
rank() over (order by total_reward desc),
|
|
|
|
miner,
|
|
|
|
total_reward
|
|
|
|
from total_rewards_by_miner
|
|
|
|
group by 2, 3;
|
|
|
|
|
|
|
|
create index if not exists top_miners_by_base_reward_miner_index
|
|
|
|
on top_miners_by_base_reward (miner);
|
|
|
|
|
|
|
|
create materialized view if not exists top_miners_by_base_reward_max_height as
|
|
|
|
select
|
|
|
|
b."timestamp"as current_timestamp,
|
|
|
|
max(b.height) as current_height
|
|
|
|
from blocks b
|
2020-08-28 00:09:33 +00:00
|
|
|
join chain_reward cr on b.parentstateroot = cr.state_root
|
|
|
|
where cr.new_reward is not null
|
2020-07-24 20:11:16 +00:00
|
|
|
group by 1
|
|
|
|
order by 1 desc
|
|
|
|
limit 1;
|
|
|
|
`); err != nil {
|
2020-08-28 00:09:33 +00:00
|
|
|
return xerrors.Errorf("create top_miners_by_base_reward views: %w", err)
|
2020-07-24 20:11:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := tx.Commit(); err != nil {
|
2020-08-28 00:09:33 +00:00
|
|
|
return xerrors.Errorf("committing top_miners_by_base_reward views; %w", err)
|
2020-07-24 20:11:16 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-07-23 02:37:34 +00:00
|
|
|
func refreshTopMinerByBaseReward(ctx context.Context, db *sql.DB) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2020-07-24 20:11:16 +00:00
|
|
|
_, err := db.Exec("refresh materialized view top_miners_by_base_reward;")
|
2020-07-23 02:37:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return xerrors.Errorf("refresh top_miners_by_base_reward: %w", err)
|
|
|
|
}
|
|
|
|
|
2020-07-24 20:11:16 +00:00
|
|
|
_, err = db.Exec("refresh materialized view top_miners_by_base_reward_max_height;")
|
|
|
|
if err != nil {
|
|
|
|
return xerrors.Errorf("refresh top_miners_by_base_reward_max_height: %w", err)
|
|
|
|
}
|
|
|
|
|
2020-07-23 02:37:34 +00:00
|
|
|
return nil
|
|
|
|
}
|