Change behaviour on disconnect, add some paranoia checks and optimize some sql-statements for mysql