replaced in-memory legacy_codes by db query