001package gudusoft.gsqlparser.util;
002
003import gudusoft.gsqlparser.EDbVendor;
004
005import java.io.InputStream;
006import java.util.*;
007
008public class TBuiltFunctionUtil {
009
010    private static final Logger logger = LoggerFactory.getLogger(TBuiltFunctionUtil.class);
011    static Map<EDbVendor, Map<String, Set<Integer>>> dbFunctionMap = new HashMap<>();
012
013    public static Set<Integer> argumentsIncludeKeyword(EDbVendor vendor, String function) {
014        if (!dbFunctionMap.containsKey(vendor)) {
015            initFunctionMap(vendor);
016        }
017        Map<String, Set<Integer>> functionMap = dbFunctionMap.get(vendor);
018        return functionMap.get(function.toUpperCase());
019    }
020
021    public static void list(EDbVendor vendor){
022        if (!dbFunctionMap.containsKey(vendor)) {
023            initFunctionMap(vendor);
024        }
025
026        Map<String, Set<Integer>> functionMap = dbFunctionMap.get(vendor);
027        for (Map.Entry<String, Set<Integer>> entry : functionMap.entrySet()){
028            System.out.println("Key = " + entry.getKey() +
029                    ", Value = " + entry.getValue());
030            Iterator<Integer> namesIterator = entry.getValue().iterator();
031            while(namesIterator.hasNext()){
032                System.out.println(namesIterator.next());
033            }
034        }
035
036    }
037
038    private static void initFunctionMap(EDbVendor vendor) {
039        Map<String, Set<Integer>> functionMap = new HashMap<>();
040        try {
041            String resourceFile = "/gudusoft/gsqlparser/builtinFunctions/"
042                    + vendor.name().replace("dbv", "") + ".function.argumentswithkeywords.properties";
043
044            InputStream is = TBuiltFunctionUtil.class.getResourceAsStream(resourceFile);
045            if (is != null) {
046                String[] lines = SQLUtil.getInputStreamContent(is, false).split("\n");
047                for (String line : lines) {
048                    String[] function = line.trim().split("\\s*,\\s*", -1);
049                    if (function.length <= 1) {
050                        continue;
051                    }
052                    String functionName = function[0].toUpperCase();
053                    Integer argCount = function.length - 1;
054                    Set<Integer> relationArgs = new HashSet<>();
055                    for (int i = 1; i <= argCount; i++) {
056                         relationArgs.add(Integer.valueOf(function[i]));
057                    }
058                    functionMap.put(functionName , relationArgs);
059                }
060            }
061        } catch (Exception e) {
062            logger.error("init function map failed.", e);
063        }
064        dbFunctionMap.put(vendor, functionMap);
065    }
066}