Fix sqlite ids

This cleanup and fixing branch is ready to be merged into master. We can check latest fixes there.