We've been doing copypasta for this for too long... A bit of work on this will go a long way towards ease and reliability of many future queries.
Now that we have Druid, many types of queries can run much faster, too.
A small library like this would also help create a feed of data for monitoring and visualization tools (see T124132).