001package gudusoft.gsqlparser.lineage.v2;
002
003import java.util.Collections;
004import java.util.LinkedHashMap;
005import java.util.LinkedHashSet;
006import java.util.List;
007import java.util.Map;
008import java.util.Set;
009
010/**
011 * The core registry of SQL-LR ({@code registry/core-registry.json}): the codes of every registry group and
012 * the validation stage of every diagnostic code.
013 *
014 * @since 4.2.17
015 */
016public final class CoreRegistry {
017
018    private final Map<String, Set<String>> groups;
019    private final Map<String, String> diagnosticStage;
020
021    private CoreRegistry(Map<String, Set<String>> groups, Map<String, String> diagnosticStage) {
022        this.groups = Collections.unmodifiableMap(groups);
023        this.diagnosticStage = Collections.unmodifiableMap(diagnosticStage);
024    }
025
026    /** The registry this library ships. */
027    public static CoreRegistry standard() {
028        return Standard.INSTANCE;
029    }
030
031    private static final class Standard {
032        static final CoreRegistry INSTANCE = of(SqllrResources.coreRegistry());
033    }
034
035    /** A registry from a parsed {@code core-registry.json}. */
036    public static CoreRegistry of(Object registry) {
037        Map<?, ?> groupsValue = (Map<?, ?>) ((Map<?, ?>) registry).get("groups");
038        Map<String, Set<String>> groups = new LinkedHashMap<String, Set<String>>();
039        Map<String, String> stages = new LinkedHashMap<String, String>();
040        for (Map.Entry<?, ?> group : groupsValue.entrySet()) {
041            Set<String> codes = new LinkedHashSet<String>();
042            for (Object entry : (List<?>) ((Map<?, ?>) group.getValue()).get("entries")) {
043                Map<?, ?> item = (Map<?, ?>) entry;
044                codes.add((String) item.get("code"));
045                if ("diagnosticCodes".equals(group.getKey())) {
046                    stages.put((String) item.get("code"), (String) item.get("stage"));
047                }
048            }
049            groups.put((String) group.getKey(), Collections.unmodifiableSet(codes));
050        }
051        return new CoreRegistry(groups, stages);
052    }
053
054    /** The codes of a group; empty for a group the registry does not have. */
055    public Set<String> group(String name) {
056        Set<String> codes = groups.get(name);
057        return codes == null ? Collections.<String>emptySet() : codes;
058    }
059
060    public Set<String> groupNames() {
061        return groups.keySet();
062    }
063
064    /** The validation stage of a diagnostic code, or null. */
065    public String stageOf(String diagnosticCode) {
066        return diagnosticStage.get(diagnosticCode);
067    }
068}