|
| 1 | +-- Validate epoch table values against recalculated values from tx/block tables. |
| 2 | +-- |
| 3 | +-- Usage: |
| 4 | +-- Validate a specific epoch: |
| 5 | +-- psql -v epoch_no=620 -f scripts/validate-epoch-table.sql cexplorer |
| 6 | +-- |
| 7 | +-- Validate all epochs: |
| 8 | +-- psql -v epoch_no=-1 -f scripts/validate-epoch-table.sql cexplorer |
| 9 | +-- |
| 10 | +-- Any row in the output means a mismatch. No rows = all correct. |
| 11 | + |
| 12 | +WITH calculated AS ( |
| 13 | + SELECT |
| 14 | + b.epoch_no, |
| 15 | + COUNT(DISTINCT b.id) AS blk_count, |
| 16 | + MIN(b.time) AS start_time, |
| 17 | + MAX(b.time) AS end_time, |
| 18 | + COALESCE(SUM(tx.out_sum), 0) AS out_sum, |
| 19 | + COALESCE(SUM(tx.fee), 0) AS fee_sum, |
| 20 | + COUNT(tx.id) AS tx_count |
| 21 | + FROM block b |
| 22 | + LEFT JOIN tx ON tx.block_id = b.id |
| 23 | + WHERE b.epoch_no IS NOT NULL |
| 24 | + AND (CAST(:epoch_no AS bigint) = -1 OR b.epoch_no = CAST(:epoch_no AS bigint)) |
| 25 | + GROUP BY b.epoch_no |
| 26 | +), |
| 27 | +compared AS ( |
| 28 | + SELECT |
| 29 | + c.epoch_no, |
| 30 | + -- Calculated values |
| 31 | + c.out_sum AS calc_out_sum, |
| 32 | + c.fee_sum AS calc_fees, |
| 33 | + c.tx_count AS calc_tx_count, |
| 34 | + c.blk_count AS calc_blk_count, |
| 35 | + c.start_time AS calc_start_time, |
| 36 | + c.end_time AS calc_end_time, |
| 37 | + -- Stored values |
| 38 | + e.out_sum AS stored_out_sum, |
| 39 | + e.fees AS stored_fees, |
| 40 | + e.tx_count AS stored_tx_count, |
| 41 | + e.blk_count AS stored_blk_count, |
| 42 | + e.start_time AS stored_start_time, |
| 43 | + e.end_time AS stored_end_time, |
| 44 | + -- Differences |
| 45 | + c.out_sum - e.out_sum AS out_sum_diff, |
| 46 | + c.fee_sum - e.fees AS fees_diff, |
| 47 | + c.tx_count - e.tx_count AS tx_count_diff, |
| 48 | + c.blk_count - e.blk_count AS blk_count_diff |
| 49 | + FROM calculated c |
| 50 | + LEFT JOIN epoch e ON e.no = c.epoch_no |
| 51 | +) |
| 52 | +SELECT |
| 53 | + epoch_no, |
| 54 | + CASE WHEN stored_out_sum IS NULL THEN 'MISSING' ELSE '' END AS status, |
| 55 | + calc_out_sum, |
| 56 | + stored_out_sum, |
| 57 | + out_sum_diff, |
| 58 | + calc_fees, |
| 59 | + stored_fees, |
| 60 | + fees_diff, |
| 61 | + calc_tx_count, |
| 62 | + stored_tx_count, |
| 63 | + tx_count_diff, |
| 64 | + calc_blk_count, |
| 65 | + stored_blk_count, |
| 66 | + blk_count_diff, |
| 67 | + calc_start_time, |
| 68 | + stored_start_time, |
| 69 | + calc_end_time, |
| 70 | + stored_end_time |
| 71 | +FROM compared |
| 72 | +WHERE stored_out_sum IS NULL |
| 73 | + OR out_sum_diff != 0 |
| 74 | + OR fees_diff != 0 |
| 75 | + OR tx_count_diff != 0 |
| 76 | + OR blk_count_diff != 0 |
| 77 | +ORDER BY epoch_no; |
0 commit comments