Factor query into prepared parameterized statement and better input check.
Merge upstream changes.