Fix SQL bugs in messaging