Fix bug when cghing schema in run_sql

Also some refactoring.