|
1 | 1 | import random
|
2 | 2 | from datetime import datetime
|
3 | 3 |
|
4 |
| -import pytest |
5 | 4 | from async_generator import yield_, async_generator
|
| 5 | +import pytest |
| 6 | +from sqlalchemy import select |
| 7 | +from sqlalchemy.sql.functions import count |
6 | 8 |
|
7 | 9 | from gino.loader import AliasLoader
|
8 | 10 | from .models import db, User, Team, Company
|
|
12 | 14 |
|
13 | 15 | @pytest.fixture
|
14 | 16 | @async_generator
|
15 |
| -async def user(bind, random_name): |
| 17 | +async def user(bind): |
16 | 18 | c = await Company.create()
|
17 | 19 | t1 = await Team.create(company_id=c.id)
|
18 | 20 | t2 = await Team.create(company_id=c.id, parent_id=t1.id)
|
19 |
| - u = await User.create(nickname=random_name, team_id=t2.id) |
| 21 | + u = await User.create(team_id=t2.id) |
20 | 22 | u.team = t2
|
21 | 23 | t2.parent = t1
|
22 | 24 | t2.company = c
|
@@ -161,6 +163,47 @@ async def test_alias_loader_columns(user):
|
161 | 163 | assert u.id is not None
|
162 | 164 |
|
163 | 165 |
|
| 166 | +async def test_multiple_models_in_one_query(bind): |
| 167 | + for _ in range(3): |
| 168 | + await User.create() |
| 169 | + |
| 170 | + ua1 = User.alias() |
| 171 | + ua2 = User.alias() |
| 172 | + join_query = select([ua1, ua2]).where(ua1.id < ua2.id) |
| 173 | + result = await join_query.gino.load((ua1.load('id'), ua2.load('id'))).all() |
| 174 | + assert len(result) == 3 |
| 175 | + for u1, u2 in result: |
| 176 | + assert u1.id is not None |
| 177 | + assert u2.id is not None |
| 178 | + assert u1.id < u2.id |
| 179 | + |
| 180 | + |
| 181 | +async def test_loader_with_aggregation(user): |
| 182 | + count_col = count().label('count') |
| 183 | + user_count = select( |
| 184 | + [User.team_id, count_col] |
| 185 | + ).group_by( |
| 186 | + User.team_id |
| 187 | + ).alias() |
| 188 | + query = Team.outerjoin(user_count).select() |
| 189 | + result = await query.gino.load( |
| 190 | + (Team.id, Team.name, user_count.columns.team_id, count_col) |
| 191 | + ).all() |
| 192 | + assert len(result) == 2 |
| 193 | + # team 1 doesn't have users, team 2 has 1 user |
| 194 | + # third and forth columns are None for team 1 |
| 195 | + for team_id, team_name, user_team_id, user_count in result: |
| 196 | + if team_id == user.team_id: |
| 197 | + assert team_name == user.team.name |
| 198 | + assert user_team_id == user.team_id |
| 199 | + assert user_count == 1 |
| 200 | + else: |
| 201 | + assert team_id is not None |
| 202 | + assert team_name is not None |
| 203 | + assert user_team_id is None |
| 204 | + assert user_count is None |
| 205 | + |
| 206 | + |
164 | 207 | async def test_adjacency_list_query_builder(user):
|
165 | 208 | group = Team.alias()
|
166 | 209 | u = await User.load(team=Team.load(parent=group.on(
|
|
0 commit comments