Generalizes the function for getting access sql, adds a plugin hook, and adds unit tests

This is an update on #5521

@brettp wrote the first version of this, @jrtilson did a lot of updates, and I finished it off (hopefully).