'This will delete all the stats_demographic_aggregate records and
then rebuild them by triggering off a request for each
stats_demographic_data record.
This function is normally only run during prepop or postpop so we
don\'t need to worry about the aggregate data being unavailable for
any length of time'

@staticmethod
def stats_demographic_rebuild_all_aggregates():

    db = current.db
    ttable = db.scheduler_task
    rtable = db.scheduler_run
    wtable = db.scheduler_worker
    query = (((ttable.task_name == 'stats_demographic_update_aggregates') & (rtable.task_id == ttable.id)) & (rtable.status == 'RUNNING'))
    rows = db(query).select(rtable.id, rtable.task_id, rtable.worker_name)
    now = current.request.utcnow
    for row in rows:
        db((wtable.worker_name == row.worker_name)).update(status='KILL')
        db((rtable.id == row.id)).update(stop_time=now, status='STOPPED')
        db((ttable.id == row.task_id)).update(stop_time=now, status='STOPPED')
    current.s3db.stats_demographic_aggregate.truncate()
    dtable = db.stats_demographic
    ddtable = db.stats_demographic_data
    query = (((ddtable.deleted != True) & (ddtable.parameter_id == dtable.parameter_id)) & (ddtable.approved_by != None))
    records = db(query).select(ddtable.data_id, ddtable.parameter_id, ddtable.date, ddtable.location_id, ddtable.value, dtable.total_id)
    current.s3task.async('stats_demographic_update_aggregates', vars=dict(records=records.json()), timeout=21600)
