Created
July 13, 2020 08:11
-
-
Save zhangysh1995/fb4847bce5c971a7331ce3dff8823c49 to your computer and use it in GitHub Desktop.
How To Use moz_sql_parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from moz_sql_parser import parse | |
import json | |
def makeSpace(char, depth, end=''): | |
return char * depth | |
def walk(node, depth, flag=0, char = ' '): | |
if isinstance(node, dict): | |
print() | |
for index, (key, item) in enumerate(node.items()): | |
print(makeSpace(char, depth+1) + key, end=': ') | |
if index == len(node) - 1 or len(item) == 1: | |
flag = 1 | |
else: | |
flag = 0 | |
walk(item, depth+1, flag=flag) | |
elif isinstance(node, list): | |
for index, it in enumerate(node): | |
if index == len(node) -1: | |
flag = 1 | |
else: | |
flag = 0 | |
walk(it, depth+1, flag=flag) | |
else: | |
if flag: | |
print(makeSpace(char, depth+1) + str(node)) | |
else: | |
print(str(node), end=' ') | |
tokens = json.dumps(parse("select a, b from t;")) | |
print(tokens) | |
tokens = parse("SELECT a, b FROM t WHERE a > 0 and b < 1 GROUP BY a HAVING count(*) > 2 ORDER BY a DESC ;") | |
print(tokens) | |
for i in tokens.items(): | |
print(i) | |
walk(tokens, -1, flag=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment