import debug from "debug" ; const L = debug ( "hub:db:delete-patches" ) ; import { PostgreSQL } from "./types" ; import { delay } from "awaiting" ; const MAX_AT_ONCE = parseInt ( process . env . SYNCSTRING_DELETE_MAX_AT_ONCE ?? "10000" ) ; const DELAY_S = parseInt ( process . env . SYNCSTRING_DELETE_DELAY_CHUNK_S ?? "1" ) ; interface DeletePatchesOpts { db : PostgreSQL ; string_id : string ; cb ? : Function ; } async function patchset_limit ( opts ) { const { db , string_id } = opts ; const q = await db . async_query ( { query : "SELECT time FROM patches" , where : { "string_id = $::CHAR(40)" : string_id } , limit : 1 , offset : MAX_AT_ONCE , } ) ; if ( q . rows . length == 0 ) { return undefined ; } else { return q . rows [ 0 ] . time ; } } export async function delete_patches ( opts ) { const { db , string_id , cb } = opts ; while ( true ) { const limit = await patchset_limit ( { db , string_id } ) ; L ( `deleting patches string_id='${ string_id }' until limit='${ limit }'` ) ; const where = { "string_id = $::CHAR(40)" : string_id } ; if ( limit != null ) { where [ "time <= $::TIMESTAMP" ] = limit ; } await db . async_query ( { query : "DELETE FROM patches" , where , timeout_s : 300 , } ) ; if ( limit != null ) { await delay ( DELAY_S * 1000 ) ; } else { break ; } } if ( typeof cb === "function" ) cb ( ) ; }