Add PID in lockfile
Fix query testsuite, code cleanup and minor refactoring