3
0

QueryParser.py 1.8 KB

1234567891011121314151617181920212223242526
  1. import pyparsing as pp
  2. class QueryParser:
  3. def __init__(self):
  4. extractor = pp.Keyword("random") ^ pp.Keyword("first") ^ pp.Keyword("last")
  5. selector = pp.Keyword("most_used") ^ pp.Keyword("least_used") ^ pp.Keyword("avg") ^ pp.Keyword("all")
  6. attribute = pp.Keyword("ipaddress") ^ pp.Keyword("macaddress") ^ pp.Keyword("portnumber") ^ pp.Keyword("protocolname") ^ pp.Keyword("ttlvalue") ^ pp.Keyword("mssvalue") ^ pp.Keyword("winsize") ^ pp.Keyword("ipclass") ^ pp.Keyword("pktssent") ^ pp.Keyword("pktsreceived") ^ pp.Keyword("mss") ^ pp.Keyword("kbytesreceived") ^ pp.Keyword("kbytessent")
  7. simple_selector_query = selector + pp.Suppress("(") + attribute + pp.Suppress(")")
  8. param_selectors = pp.Keyword("ipaddress").setParseAction(pp.replaceWith("ipaddress_param")) ^ pp.Keyword("macaddress").setParseAction(pp.replaceWith("macaddress_param"))
  9. operators = pp.Literal("=") ^ pp.Literal("<=") ^ pp.Literal("<") ^ pp.Literal(">=") ^ pp.Literal(">")
  10. expr = pp.Forward()
  11. comparison = pp.Group(attribute + operators + (pp.Word(pp.alphanums + ".:") ^ expr))
  12. parameterized_query = param_selectors + pp.Suppress("(") + pp.Group(pp.delimitedList(comparison)) + pp.Suppress(")")
  13. # parameterized_query = param_selectors + pp.Suppress("(") + comparison + pp.Suppress(")")
  14. all_selector_queries = (simple_selector_query ^ parameterized_query)
  15. extractor_selector_query = extractor + pp.Suppress("(") + all_selector_queries + pp.Suppress(")")
  16. named_query = (extractor_selector_query ^ all_selector_queries)
  17. expr << pp.Group(named_query)
  18. self.full_query = named_query + pp.Suppress(";")
  19. def parse_query(self, querystring):
  20. return self.full_query.parseString(querystring)