-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
36 lines (29 loc) · 837 Bytes
/
parser.py
File metadata and controls
36 lines (29 loc) · 837 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import re
def parse_query(query):
query = query.strip()
pattern = re.compile(
r"SELECT (.+) FROM (\w+)"
r"(?: WHERE (.+?))?"
r"(?: ORDER BY (\w+)(?: (ASC|DESC))?)?"
r"(?: LIMIT (\d+))?$",
re.IGNORECASE
)
match = pattern.match(query)
if not match:
raise ValueError("Invalid query format")
columns = match.group(1)
table = match.group(2)
where_clause = match.group(3)
order_by = match.group(4)
order_dir = match.group(5)
limit = match.group(6)
if columns != "*":
columns = [col.strip() for col in columns.split(",")]
return {
"columns": columns,
"table": table,
"where": where_clause,
"order_by": order_by,
"order_dir": order_dir,
"limit": int(limit) if limit else None
}