|
| 1 | +from sqlalchemy import select, insert, update, bindparam, delete |
| 2 | +from sqlalchemy.orm import outerjoin, aliased |
| 3 | + |
| 4 | +from db_init import Session, Department, Employee |
| 5 | + |
| 6 | + |
| 7 | +def execute_query(query): |
| 8 | + result = session.execute(query) |
| 9 | + for row in result: |
| 10 | + print(row) |
| 11 | + |
| 12 | + |
| 13 | +def select_single_target(): |
| 14 | + query = select(Department).order_by(Department.name) |
| 15 | + execute_query(query) |
| 16 | + |
| 17 | + |
| 18 | +def select_multiple(): |
| 19 | + query = select(Employee, Department).join(Employee.department, isouter=True) |
| 20 | + execute_query(query) |
| 21 | + |
| 22 | + |
| 23 | +def select_with_alias(): |
| 24 | + emp_cls = aliased(Employee, name="emp") |
| 25 | + dep_cls = aliased(Department, name="dep") |
| 26 | + query = select(emp_cls, dep_cls).join(emp_cls.department.of_type(dep_cls)) |
| 27 | + execute_query(query) |
| 28 | + |
| 29 | + |
| 30 | +def select_fields(): |
| 31 | + query = select(Employee.name.label('emp_name'), Department.name.label('dep_name')).join_from(Employee, Department) |
| 32 | + execute_query(query) |
| 33 | + |
| 34 | + |
| 35 | +def select_fields_outer(): |
| 36 | + query = select(Employee.name.label('emp_name'), Department.name.label('dep_name'))\ |
| 37 | + .select_from(outerjoin(Employee, Department)) |
| 38 | + execute_query(query) |
| 39 | + |
| 40 | + |
| 41 | +def where_obj(): |
| 42 | + dep = session.get(Department, 1) |
| 43 | + # query = select(Employee).where(Employee.department == dep) |
| 44 | + query = select(Employee).where(Employee.dep_id != dep.id) |
| 45 | + execute_query(query) |
| 46 | + |
| 47 | + |
| 48 | +def select_contains(): |
| 49 | + emp = session.get(Employee, 1) |
| 50 | + query = select(Department).where(Department.employees.contains(emp)) |
| 51 | + execute_query(query) |
| 52 | + |
| 53 | + |
| 54 | +session = Session() |
| 55 | +# select_single_target() |
| 56 | +# select_multiple() |
| 57 | +# select_with_alias() |
| 58 | +# select_fields() |
| 59 | +# select_fields_outer() |
| 60 | +# where_obj() |
| 61 | +select_contains() |
0 commit comments