data-structureshqlejbql

Data structure to hold HQL or EJB QL


We need to produce a fairly complex dynamic query builder for retrieving reports on the fly. We're scratching our heads a little on what sort of data structure would be best.

It's really nothing more than holding a list of selectParts, a list of fromParts, a list of where criteria, order by, group by, that sort of thing, for persistence. When we start thinking about joins, especially outer joins, having clauses, and aggregate functions, things start getting a little fuzzy.

We're building it up interfaces first for now and trying to think as far ahead as we can, but definitely will go through a series of refactorings when we discover limitations with our structures.

I'm posting this question here in the hopes that someone has already come up with something that we can base it on. Or know of some library or some such. It would be nice to get some tips or heads-up on potential issues before we dive into implementations next week.


Solution

  • I've done something similar couple of times in the past. A couple of the bigger things spring to mind..

    e.g. If you had

    "where upper(column1) = :param1 AND ( column2 is null OR column3 between :param2 and param3)"
    

    Then the tree is

    Root
    - AND
      - Equal
        - Function(upper)
          - ColumnReference(column1)
        - Parameter(param1)
      - OR
        - IsNull
          - ColumnReference(column2)
        - Between
          - ColumnReference(column3)
          - Parameter(param2)
          - Parameter(param3)
    

    Then you walk the tree depth first and merge rendered bits of HQL on the way back up. The upper function for example would expect one piece of child HQL to be rendered and it would then generate

    "upper( " + childHql + " )"

    and pass that up to it's parent. Something like Between expects three child HQL pieces.

    Plus, if you ever get into wanting to parse a query language (or anything really) then I can highly recommend ANTLR. Learning curve is quite steep but there are plenty of example grammars to look at.

    HTH.