forked from hackintoshrao/sqlglot
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtesting5.py
More file actions
641 lines (583 loc) · 25.8 KB
/
testing5.py
File metadata and controls
641 lines (583 loc) · 25.8 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
from typing import List, Dict, Any, Optional
import sqlglot
from sqlglot.expressions import (
Expression,
Select,
Column,
Table,
Alias,
With,
CTE,
Join,
Literal,
Star,
)
from sqlglot import parse_one
from collections import defaultdict
import logging
# Configure logging for debugging purposes
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
def build_alias_mapping(expressions: List[Expression]) -> Dict[str, str]:
"""
First pass: Gathers all table aliases from all SELECT ... FROM ... clauses and JOINs.
Returns:
alias_mapping: a dict of alias -> real_table_name
"""
alias_mapping = {}
for expr in expressions:
# Walk entire tree
for node in expr.walk():
if isinstance(node, Select):
# FROM
from_clause = node.args.get("from")
if from_clause:
for source in from_clause.find_all(Table):
table_name = source.name
if not table_name:
continue
if isinstance(source.parent, Alias):
alias = source.parent.alias
else:
alias = source.alias
if alias:
alias_mapping[alias] = table_name
# JOIN
for join in node.find_all(Join):
joined_table = join.this
if isinstance(joined_table, Table):
jtable = joined_table.name
if jtable:
if isinstance(joined_table.parent, Alias):
jalias = joined_table.parent.alias
else:
jalias = joined_table.alias
if jalias:
alias_mapping[jalias] = jtable
return alias_mapping
def ccextract_sql_components_per_table_with_alias(
expressions: List[Expression],
) -> List[Dict[str, Any]]:
"""
Extracts SQL components (tables, columns, where_columns, limits) from parsed SQL expressions,
associating LIMIT clauses with the specific tables involved in their respective SELECT statements.
Args:
expressions (List[Expression]): Parsed SQL expressions from sqlglot.parse().
Returns:
List[Dict[str, Any]]: A list of dictionaries, each representing a table with its associated columns,
where_columns, and limits.
"""
components = []
alias_mapping = {} # Maps aliases to actual table names
# Helper function to find or create a table entry
def get_or_create_table_entry(table_name: str) -> Dict[str, Any]:
table_entry = next((item for item in components if item["table"] == table_name), None)
if not table_entry:
table_entry = {"table": table_name, "columns": [], "where_columns": [], "limits": []}
components.append(table_entry)
return table_entry
cte_names = set()
for expr in expressions:
with_clause = expr.args.get("with")
if with_clause:
for cte in with_clause.find_all(CTE):
cte_name = cte.alias_or_name
if cte_name:
cte_names.add(cte_name) # Use lowercase for consistent comparison
print("cte_names: ", cte_names)
# Traverse the AST using the walk method provided by Expression class
i = 0
for expression in expressions:
for node in expression.walk():
i += 1
if isinstance(node, Select):
current_select_tables = set()
# Extract FROM tables and their aliases
from_clause = node.args.get("from")
if from_clause:
for source in from_clause.find_all(Table):
table_name = source.name
if not table_name:
continue
# Check if the table has an alias
if isinstance(source.parent, Alias):
alias = source.parent.alias
else:
alias = source.alias
if alias:
alias_mapping[alias] = table_name
current_select_tables.add(table_name)
get_or_create_table_entry(table_name)
for join in node.find_all(Join):
joined_table = join.this
if isinstance(joined_table, Table):
table_name = joined_table.name
if table_name:
# Check alias
if isinstance(joined_table.parent, Alias):
alias = joined_table.parent.alias
else:
alias = joined_table.alias
if alias:
alias_mapping[alias] = table_name
current_select_tables.add(table_name)
get_or_create_table_entry(table_name)
alias_mapping = build_alias_mapping(expressions)
# Handle JOIN tables
for join in node.find_all(Join):
joined_table = join.this
if isinstance(joined_table, Table):
table_name = joined_table.name
alias = None
# Check if the joined table has an alias
if isinstance(joined_table.parent, Alias):
alias = joined_table.parent.alias
alias_mapping[alias] = table_name
elif joined_table.alias:
alias = joined_table.alias
alias_mapping[alias] = table_name
if table_name:
current_select_tables.add(table_name)
get_or_create_table_entry(table_name)
# Extract columns from SELECT expressions
for expr in node.expressions:
if isinstance(expr, Column):
column_name = expr.name
table_alias = expr.table
if table_alias:
actual_table = alias_mapping.get(table_alias, table_alias)
table_entry = next(
(item for item in components if item["table"] == actual_table), None
)
if table_entry and column_name:
table_entry["columns"].append(column_name)
else:
logger.warning(
f"Column '{column_name}' has an alias '{table_alias}' which does not match any table."
)
else:
# If no table alias, associate with all tables in the current SELECT (ambiguous)
if current_select_tables:
for table in current_select_tables:
table_entry = next(
(item for item in components if item["table"] == table),
None,
)
if table_entry and column_name:
table_entry["columns"].append(column_name)
else:
logger.warning(
f"Column '{column_name}' has no table alias and no tables found in SELECT."
)
elif isinstance(expr, Star):
# Handle wildcard '*'
# Check if the Star has a table alias (e.g., 'e.*')
# print("expr.parent: ", expr)
table_alias = (
expr.parent.alias_or_name if isinstance(expr.parent, Alias) else None
)
if table_alias:
actual_table = alias_mapping.get(table_alias, table_alias)
table_entry = next(
(
item
for item in components
if item["table"].lower() == actual_table.lower()
),
None,
)
if table_entry:
if "*" not in table_entry["columns"]:
table_entry["columns"].append("*")
else:
# Unqualified '*', associate with all current SELECT tables
if current_select_tables:
for table in current_select_tables:
table_entry = next(
(
item
for item in components
if item["table"].lower() == table.lower()
),
None,
)
if table_entry:
if "*" not in table_entry["columns"]:
table_entry["columns"].append("*")
else:
logger.warning(
"Unqualified '*' found but no tables are associated with the current SELECT."
)
elif isinstance(expr, Alias):
# Handle aliased columns or expressions
if isinstance(expr.this, Column):
column_name = expr.this.name
table_alias = expr.this.table
if table_alias:
actual_table = alias_mapping.get(table_alias, table_alias)
table_entry = next(
(item for item in components if item["table"] == actual_table),
None,
)
# print("Table entry is ->: ",table_entry, "actual_table is ->: ",actual_table, "table_alias is ->: ",table_alias, "column_name is ->: ",column_name)
if table_entry and column_name:
table_entry["columns"].append(column_name)
else:
logger.warning(
f"Aliased column '{column_name}' has an alias '{table_alias}' which does not match any table."
)
else:
# If no table alias, associate with all tables in the current SELECT (ambiguous)
if current_select_tables:
for table in current_select_tables:
table_entry = next(
(item for item in components if item["table"] == table),
None,
)
if table_entry and column_name:
table_entry["columns"].append(column_name)
else:
logger.warning(
f"Aliased column '{column_name}' has no table alias and no tables found in SELECT."
)
# print("values is ",table_entry['columns'])
elif isinstance(node, Star):
# Handle wildcard '*'
# Check if the Star has a table alias (e.g., 'e.*')
table_alias = (
node.parent.alias_or_name
if isinstance(node.parent, Alias)
else None
)
if table_alias:
actual_table = alias_mapping.get(table_alias, table_alias)
table_entry = next(
(
item
for item in components
if item["table"].lower() == actual_table.lower()
),
None,
)
if table_entry:
if "*" not in table_entry["columns"]:
table_entry["columns"].append("*")
else:
# Unqualified '*', associate with all current SELECT tables
if current_select_tables:
for table in current_select_tables:
table_entry = next(
(
item
for item in components
if item["table"].lower() == table.lower()
),
None,
)
if table_entry:
if "*" not in table_entry["columns"]:
table_entry["columns"].append("*")
else:
logger.warning(
"Unqualified '*' found but no tables are associated with the current SELECT."
)
else:
# Handle expressions or functions aliased as columns
pass # Can be extended if needed
# Extract WHERE columns
where_clause = node.args.get("where")
if where_clause:
for condition in where_clause.find_all(Column):
column_name = condition.name
table_alias = condition.table
if table_alias:
actual_table = alias_mapping.get(table_alias, table_alias)
table_entry = next(
(item for item in components if item["table"] == actual_table), None
)
if table_entry and column_name:
table_entry["where_columns"].append(column_name)
else:
logger.warning(
f"WHERE condition column '{column_name}' has an alias '{table_alias}' which does not match any table."
)
else:
# If no table alias, associate with all tables in the current SELECT (ambiguous)
if current_select_tables:
for table in current_select_tables:
table_entry = next(
(item for item in components if item["table"] == table),
None,
)
if table_entry and column_name:
table_entry["where_columns"].append(column_name)
else:
logger.warning(
f"WHERE condition column '{column_name}' has no table alias and no tables found in SELECT."
)
# Extract LIMIT
limit_clause = node.args.get("limit")
if limit_clause:
# print("len is ",len(limit_clause))
for limit_value in limit_clause.find_all(Literal):
if isinstance(limit_value, Literal):
limit_num = limit_value.this
if current_select_tables:
print("limit current_select_tables: ", current_select_tables)
for table in current_select_tables:
# print("limit table: ", table)
table_entry = next(
(item for item in components if item["table"] == table),
None,
)
if table_entry:
table_entry["limits"].append(limit_num)
else:
logger.warning(
f"LIMIT '{limit_num}' found but no tables are associated with the current SELECT."
)
elif isinstance(node, CTE):
# CTEs are handled implicitly by traversing their SELECT statements
pass # Already handled via the walk
elif isinstance(node, With):
# WITH clauses are handled implicitly by traversing their CTEs
pass # Already handled via the walk
# Post-process to remove duplicates within each table entry
list_of_tables = []
entries = []
for entry in components:
if entry["table"] in cte_names:
print("found cte: ", entry["table"])
continue
list_of_tables.append(entry["table"])
entries.append(entry)
return entries
sql3 = """
SELECT
e.employee_id,
e.full_name,
e.salary,
e.department_id
FROM employees e
WHERE e.salary > (
SELECT salaries2
FROM employees e2
WHERE e2.salaries = e.department_id
LIMIT 10
);
"""
sql2 = """
WITH RECURSIVE EmployeeHierarchy AS (
-- Base case: top-level managers
SELECT
e.employee_id,
e.full_name,
e.manager_id,
e.department_id,
1 as level,
CAST(e.full_name AS VARCHAR(1000)) as hierarchy_path
FROM employees e
WHERE e.manager_id IS NULL
LIMIT 10
UNION ALL
SELECT * from diddy WHERE diddy.id = 1
UNION ALL
-- Recursive case: employees with managers
SELECT
e.employee_id,
e.full_name,
e.manager_id,
e.department_id,
eh.level + 1,
CAST(eh.hierarchy_path || ' -> ' || e.full_name AS VARCHAR(1000))
FROM employees e
INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
),
DepartmentMetrics AS (
SELECT
d.department_id,
d.department_name,
COUNT(DISTINCT e.employee_id) as employee_count,
AVG(e.salary) as avg_salary,
SUM(p.total_cost) as total_project_cost,
DENSE_RANK() OVER (ORDER BY AVG(e.salary) DESC) as salary_rank
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
LEFT JOIN project_assignments pa ON e.employee_id = pa.employee_id
LEFT JOIN projects p ON pa.project_id = p.project_id
WHERE d.active_status = 1
GROUP BY d.department_id, d.department_name
),
ProjectPerformance AS (
SELECT
p.project_id,
p.project_name,
p.start_date,
p.end_date,
COUNT(DISTINCT pa.employee_id) as team_size,
SUM(p.total_cost) as project_cost,
CASE
WHEN p.end_date < CURRENT_DATE THEN 'Completed'
WHEN p.start_date > CURRENT_DATE THEN 'Not Started'
ELSE 'In Progress'
END as project_status,
LAG(p.total_cost) OVER (PARTITION BY p.department_id ORDER BY p.start_date) as previous_project_cost
FROM projects p
LEFT JOIN project_assignments pa ON p.project_id = pa.project_id
GROUP BY p.project_id, p.project_name, p.start_date, p.end_date, p.department_id
)
SELECT
eh.hierarchy_path,
eh.level as organization_depth,
dm.department_name,
dm.employee_count,
ROUND(dm.avg_salary, 2) as average_salary,
dm.salary_rank as department_salary_rank,
pp.project_name,
pp.team_size,
pp.project_status,
ROUND(pp.project_cost, 2) as current_project_cost,
ROUND(pp.previous_project_cost, 2) as previous_project_cost,
ROUND((pp.project_cost - COALESCE(pp.previous_project_cost, 0)) /
NULLIF(pp.previous_project_cost, 0) * 100, 2) as cost_change_percentage,
FIRST_VALUE(pp.project_name) OVER (
PARTITION BY dm.department_id
ORDER BY pp.project_cost DESC
) as most_expensive_project,
COUNT(*) OVER (
PARTITION BY eh.department_id
) as total_department_projects
FROM EmployeeHierarchy eh
INNER JOIN DepartmentMetrics dm ON eh.department_id = dm.department_id
LEFT JOIN ProjectPerformance pp ON eh.department_id = pp.department_id
WHERE
eh.level <= 3
AND dm.employee_count >= 5
AND dm.total_project_cost > (
SELECT AVG(total_project_cost) * 1.2
FROM DepartmentMetrics
)
AND EXISTS (
SELECT 1
FROM project_assignments pa
WHERE pa.employee_id = eh.employee_id
AND pa.end_date > CURRENT_DATE
)
ORDER BY
eh.hierarchy_path,
dm.salary_rank,
pp.project_cost DESC
LIMIT 100;
"""
if __name__ == "__main__":
sql = """
WITH RECURSIVE EmployeeHierarchy AS (
-- Base case: top-level managers
SELECT
e.employee_id,
e.full_name,
e.manager_id,
e.department_id,
1 as level,
CAST(e.full_name AS VARCHAR(1000)) as hierarchy_path
FROM employees e
WHERE e.manager_id IS NULL
UNION ALL
-- Recursive case: employees with managers
SELECT
e.employee_id,
e.full_name,
e.manager_id,
e.department_id,
eh.level + 1,
CAST(eh.hierarchy_path || ' -> ' || e.full_name AS VARCHAR(1000))
FROM employees e
INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
),
DepartmentMetrics AS (
SELECT
d.department_id,
d.department_name,
COUNT(DISTINCT e.employee_id) as employee_count,
AVG(e.salary) as avg_salary,
SUM(p.total_cost) as total_project_cost,
DENSE_RANK() OVER (ORDER BY AVG(e.salary) DESC) as salary_rank
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
LEFT JOIN project_assignments pa ON e.employee_id = pa.employee_id
LEFT JOIN projects p ON pa.project_id = p.project_id
WHERE d.active_status = 1
GROUP BY d.department_id, d.department_name
),
ProjectPerformance AS (
SELECT
p.project_id,
p.project_name,
p.start_date,
p.end_date,
COUNT(DISTINCT pa.employee_id) as team_size,
SUM(p.total_cost) as project_cost,
CASE
WHEN p.end_date < CURRENT_DATE THEN 'Completed'
WHEN p.start_date > CURRENT_DATE THEN 'Not Started'
ELSE 'In Progress'
END as project_status,
LAG(p.total_cost) OVER (PARTITION BY p.department_id ORDER BY p.start_date) as previous_project_cost
FROM projects p
LEFT JOIN project_assignments pa ON p.project_id = pa.project_id
GROUP BY p.project_id, p.project_name, p.start_date, p.end_date, p.department_id
)
SELECT
eh.hierarchy_path,
eh.level as organization_depth,
dm.department_name,
dm.employee_count,
ROUND(dm.avg_salary, 2) as average_salary,
dm.salary_rank as department_salary_rank,
pp.project_name,
pp.team_size,
pp.project_status,
ROUND(pp.project_cost, 2) as current_project_cost,
ROUND(pp.previous_project_cost, 2) as previous_project_cost,
ROUND((pp.project_cost - COALESCE(pp.previous_project_cost, 0)) /
NULLIF(pp.previous_project_cost, 0) * 100, 2) as cost_change_percentage,
FIRST_VALUE(pp.project_name) OVER (
PARTITION BY dm.department_id
ORDER BY pp.project_cost DESC
) as most_expensive_project,
COUNT(*) OVER (
PARTITION BY eh.department_id
) as total_department_projects
FROM EmployeeHierarchy eh
INNER JOIN DepartmentMetrics dm ON eh.department_id = dm.department_id
LEFT JOIN ProjectPerformance pp ON eh.department_id = pp.department_id
WHERE
eh.level <= 3
AND dm.employee_count >= 5
AND dm.total_project_cost > (
SELECT AVG(total_project_cost) * 1.2
FROM DepartmentMetrics
)
AND EXISTS (
SELECT 1
FROM project_assignments pa
WHERE pa.employee_id = eh.employee_id
AND pa.end_date > CURRENT_DATE
)
ORDER BY
eh.hierarchy_path,
dm.salary_rank,
pp.project_cost DESC
LIMIT 100;
"""
# Parse the SQL query
parsed = sqlglot.parse(sql2, read="snowflake", error_level=None)
# Extract components per table with alias handling
# alias_mapping = build_alias_mapping(parsed)
# print("alias_mapping: ", alias_mapping)
components = ccextract_sql_components_per_table_with_alias(parsed)
# Display the result
from pprint import pprint
for c in components:
pprint(c)
print("\n")