Fixed database cleanup routine