refactoring + sql semantics fix