32 lines
1.5 KiB
TypeScript
32 lines
1.5 KiB
TypeScript
import db from '@adonisjs/lucid/services/db'
|
|
|
|
/**
|
|
* range_blocks (migration 3900): per group, each run of consecutive done ranges with its posting time span, read by
|
|
* release_final(). A few thousand rows from ~650k ranges, rebuilt whole in one statement each time; a run breaks at a
|
|
* range that isn't done or doesn't start where the one before ended.
|
|
*/
|
|
class RangeBlocks {
|
|
async rebuild(): Promise<number> {
|
|
return db.transaction(async (trx) => {
|
|
await trx.rawQuery(`DELETE FROM range_blocks`)
|
|
const result = await trx.rawQuery(
|
|
`WITH r AS (
|
|
SELECT group_id, start_id, end_id, status = 'done' AS done, posted_low, posted_high,
|
|
min(start_id) OVER (PARTITION BY group_id) AS group_first,
|
|
lag(status = 'done') OVER w AS done_before, lag(end_id) OVER w AS end_before
|
|
FROM ranges WINDOW w AS (PARTITION BY group_id ORDER BY start_id)),
|
|
runs AS (
|
|
SELECT *, sum(CASE WHEN done IS DISTINCT FROM done_before OR end_before IS DISTINCT FROM start_id - 1 THEN 1 ELSE 0 END)
|
|
OVER (PARTITION BY group_id ORDER BY start_id) AS run
|
|
FROM r)
|
|
INSERT INTO range_blocks (group_id, start_id, end_id, posted_low, posted_high, at_group_start)
|
|
SELECT group_id, min(start_id), max(end_id), min(posted_low), max(posted_high), min(start_id) = min(group_first)
|
|
FROM runs WHERE done GROUP BY group_id, run`
|
|
)
|
|
return result.rowCount ?? 0
|
|
})
|
|
}
|
|
}
|
|
|
|
export default new RangeBlocks()
|