pyparsing, Each, results name

风流意气都作罢 提交于 2019-12-02 07:09:15

问题


I'm trying to use pyparsing to build a little not-quite-sql parser (I don't have from clauses, I don't have any joins, etc). I've been basing my work today on the simpleSQL.py example script included with pyparsing. I'm trying to add the "GROUP BY" and "ORDER BY" clauses to the parser, but trying to match them no matter which comes before the other.

I'm using the Each class, and it seems to be matching them, but it does not set the result name from within the Each class. I am either not doing something right, or something is happening I'm not clear on.

Again, from the simpleSQL.py example, I removed the fromToken, so my selectStmt now looks like:

# define the grammar
selectStmt      << ( selectToken + 
                     columnNameList.setResultsName('columns') + 
                     Optional( CaselessKeyword('where') + whereExpression, "" ).setResultsName('where') + 
                     Each( [ Optional( CaselessKeyword('group by') + columnNameList, "" ).setResultsName('group'),
                             Optional( CaselessKeyword('order by') + columnNameList, "" ).setResultsName('order') ] ) )

I get the result:

SELECT a WHERE a=b  and c = d GROUP BY c, e ORDER By d ->
tokens =  ['select', ['a'], 'where', ['a', '=', 'b'], 'and', ['c', '=', 'd'], 'group by', ['c', 'e'], 'order by', ['d']]

SELECT a WHERE a=b and c =d ORDER BY z, y GROUP BY c ->
tokens =  ['select', ['a'], 'where', ['a', '=', 'b'], 'and', ['c', '=', 'd'], 'order by', ['z', 'y'], 'group by', ['c']]

So, it looks like it's parsing the group and order clauses in either order, but does not assign the results name (to 'order' and 'group'). I can see this being completely dumb and I'm missing something, or I can see it being that I'm going about finding those clauses in any order (and more clauses in the future, like LIMIT) completely wrong.

Any help would be greatly appreciated! LOVING pyparsing so far.


回答1:


Give this a shot:

Stmt      << ( selectToken +
                columnNameList('columns') + 
                Optional( CaselessKeyword('where') + whereExpression('where'), "" ) +
                Each( [ Optional( CaselessKeyword('group by') + columnNameList('group'), "" ).setDebug(),
                        Optional( CaselessKeyword('order by') + columnNameList('order'), "" ).setDebug() ] 
                    ) 
            )


来源:https://stackoverflow.com/questions/6795252/pyparsing-each-results-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!