|
| 1 | +""" |
| 2 | +This module demonstrates the use of SQLAlchemy for executing raw SQL queries |
| 3 | + directly. The example provided queries an enterprise database for information |
| 4 | + about employees and their departments, specifically focusing on those within |
| 5 | + the Engineering department. |
| 6 | +""" |
| 7 | + |
| 8 | +import csv |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +# import pandas as pd |
| 12 | +from sqlalchemy import CursorResult, Engine, TextClause, create_engine, text |
| 13 | + |
| 14 | +engine: Engine = create_engine( |
| 15 | + "postgresql://user:password@server/database", |
| 16 | +) |
| 17 | +text_clause: TextClause = text( |
| 18 | + """ |
| 19 | +SELECT |
| 20 | + employees.name, |
| 21 | + departments.name AS department, |
| 22 | + COUNT(projects.id) AS project_count, |
| 23 | + AVG(salaries.amount) AS average_salary |
| 24 | +FROM |
| 25 | + employees |
| 26 | +JOIN |
| 27 | + departments ON employees.department_id = departments.id |
| 28 | +LEFT JOIN |
| 29 | + projects ON projects.employee_id = employees.id |
| 30 | +JOIN |
| 31 | + salaries ON employees.id = salaries.employee_id |
| 32 | +WHERE |
| 33 | + departments.name = 'Engineering' |
| 34 | +GROUP BY |
| 35 | + employees.name, departments.name |
| 36 | +HAVING |
| 37 | + COUNT(projects.id) > 5 |
| 38 | +ORDER BY |
| 39 | + average_salary DESC; |
| 40 | +""" |
| 41 | +) |
| 42 | + |
| 43 | +with engine.connect() as connection: |
| 44 | + cursor_result: CursorResult[Any] = connection.execute( |
| 45 | + text_clause, |
| 46 | + ) |
| 47 | + data: list[tuple[Any, ...]] = [tuple(row) for row in cursor_result] |
| 48 | + for record in data: |
| 49 | + print(record) |
| 50 | + |
| 51 | +file_header: list[str] = [ |
| 52 | + "EMPLOYEE_NAME", |
| 53 | + "DEPARTMENT", |
| 54 | + "PROJECT_COUNT", |
| 55 | + "AVERAGE_SALARY", |
| 56 | +] |
| 57 | +filename: str = "data.csv" |
| 58 | +with open(filename, "w") as text_io_wrapper: |
| 59 | + writer = csv.writer( |
| 60 | + text_io_wrapper, |
| 61 | + ) |
| 62 | + writer.writerow(file_header) |
| 63 | + for record in data: |
| 64 | + writer.writerow(record) |
| 65 | + |
| 66 | +# dataframe: pd.DataFrame = pd.DataFrame(data, columns=file_header,) |
0 commit comments