Bug fixes for the packet handling refactoring

It looks like I sent a pull request for the branch I was working on last time so some later work-in-progress commits were merged too. What was merged apart from what I described in the previous pull request is various minor bug fixes, a refactoring of some of the SQL handling stuff, and a rewrite of the string allocation strategy to an explicit reference-counting technique, yielding pretty big speed-ups (as in cutting query time in half).

Anyway, I have some extra bug fixes here. This time I'm sending them from a separate branch. :)

More stuff may be coming later, there's still some opportunities for squeezing more out of it.