SQL fixes and new tests