Пример #1
0
    async def test_aggregate_max_with_f_expression(self):
        await testmodels.DecimalFields.create(decimal=Decimal("0"),
                                              decimal_nodec=1)
        await testmodels.DecimalFields.create(decimal=Decimal("9.99"),
                                              decimal_nodec=1)
        await testmodels.DecimalFields.create(decimal=Decimal("27.27"),
                                              decimal_nodec=1)
        values = (await testmodels.DecimalFields.all().annotate(
            max_decimal=Max(F("decimal"))).values("max_decimal"))
        self.assertEqual(
            values[0],
            {"max_decimal": Decimal("27.27")},
        )

        values = (await testmodels.DecimalFields.all().annotate(
            max_decimal=Max(F("decimal") + 1)).values("max_decimal"))
        self.assertEqual(
            values[0],
            {"max_decimal": Decimal("28.27")},
        )

        values = (await testmodels.DecimalFields.all().annotate(
            max_decimal=Max(F("decimal") + F("decimal"))
        ).values("max_decimal"))
        self.assertEqual(
            values[0],
            {"max_decimal": Decimal("54.54")},
        )

        values = (await testmodels.DecimalFields.all().annotate(
            max_decimal=Max(F("decimal") + F("decimal_nodec"))
        ).values("max_decimal"))
        self.assertEqual(
            values[0],
            {"max_decimal": Decimal("28")},
        )

        values = (await testmodels.DecimalFields.all().annotate(
            max_decimal=Max(F("decimal") + F("decimal_null"))
        ).values("max_decimal"))
        self.assertEqual(
            values[0],
            {"max_decimal": None},
        )
Пример #2
0
    async def test_order_by_annotation(self):
        t1 = await Tournament.create(name="Tournament")
        await Event.create(name="event1", tournament=t1)
        await Event.create(name="event2", tournament=t1)

        res = (await
               Event.filter(tournament=t1).annotate(max_id=Max("event_id")
                                                    ).order_by("-event_id"))
        self.assertEqual(len(res), 2)
        self.assertGreater(res[0].event_id, res[1].event_id)
        self.assertEqual(res[0].max_id, res[0].event_id)
        self.assertEqual(res[1].max_id, res[1].event_id)
Пример #3
0
 async def test_aggregate_max(self):
     await testmodels.DecimalFields.create(decimal=Decimal("0"),
                                           decimal_nodec=1)
     await testmodels.DecimalFields.create(decimal=Decimal("9.99"),
                                           decimal_nodec=1)
     await testmodels.DecimalFields.create(decimal=Decimal("27.27"),
                                           decimal_nodec=1)
     values = (await testmodels.DecimalFields.all().annotate(
         max_decimal=Max("decimal")).values("max_decimal"))
     self.assertEqual(
         values[0],
         {"max_decimal": Decimal("27.27")},
     )
Пример #4
0
async def get_pr_stats() -> List:
    pr_stats_result = (
        await PullRequest
            .annotate(
                min=Min("duration"),
                max=Max("duration"),
                avg=Avg("duration")
            )
            .filter(state='closed')
            .limit(1)
            .values("min", "max", "avg")
    )
    print(pr_stats_result)
    print(type(pr_stats_result))
    return pr_stats_result
Пример #5
0
 async def test_concat_functions(self):
     author = await Author.create(name="Some One")
     await Book.create(name="Physics Book",
                       author=author,
                       rating=4,
                       subject="physics ")
     await Book.create(name="Mathematics Book",
                       author=author,
                       rating=3,
                       subject=" mathematics")
     await Book.create(name="No-subject Book", author=author, rating=3)
     ret = (await Book.all().annotate(long_info=Max(
         Concat("name", "(", Coalesce(Trim("subject"), "others"), ")"))
                                      ).values("long_info"))
     self.assertEqual(ret, [{"long_info": "Physics Book(physics)"}])
Пример #6
0
async def leaderboard(network_id,
                      from_date=0,
                      to_date=0,
                      offset=0,
                      limit=10,
                      currency='rune'):
    results = await leaderboard_raw(network_id, from_date, to_date, offset,
                                    limit, currency)

    last_dates = await ThorTx \
        .annotate(last_date=Max('date')) \
        .filter(network=network_id, type=ThorTxType.TYPE_SWAP, date__gte=from_date) \
        .group_by('user_address') \
        .values('user_address', 'last_date')
    last_dates_cache = {e['user_address']: e['last_date'] for e in last_dates}

    for item in results:
        item['date'] = last_dates_cache.get(item['user_address'], item['date'])

    return results
Пример #7
0
    async def accounts_create(self, count=0, using_db=None) -> List[str]:
        """Create {count} accounts on this seed and return the created accounts"""
        count = max(1, count)
        async with await (await RedisDB.instance().get_lock_manager()).lock(
                f"pippin:{str(self.id)}:account_create") as lock:
            account = await acct.Account.filter(
                wallet=self).annotate(max_index=Max("account_index")
                                      ).order_by('-account_index').first()
            log.server_logger.debug(f"Creating {count} accounts for {self.id}")
            current_index = account.max_index + 1 if account is not None and account.max_index is not None and account.max_index >= 0 else 0
            accounts = []
            for i in range(count):
                private_key, public_key, address = nanopy.deterministic_key(
                    self.seed, index=current_index)
                accounts.append(
                    acct.Account(wallet=self,
                                 account_index=current_index,
                                 address=address))
                current_index += 1
            await acct.Account.bulk_create(accounts, using_db=using_db)

            return [a.address for a in accounts]
Пример #8
0
 def __call__(self, *args, **kwargs):
     loop = asyncio.get_event_loop()
     max_number = loop.run_until_complete(
         self.model.annotate(m=Max(self.field)).values_list("m",
                                                            flat=True))[0]
     return (max_number or 0) + 1
Пример #9
0
 async def get_newest_account(self) -> acct.Account:
     """Get account with highest index beloning to this wallet"""
     return await acct.Account.filter(wallet=self).annotate(
         max_index=Max("account_index")).order_by('-account_index').first()
Пример #10
0
 def inner():
     loop = asyncio.get_event_loop()
     model = globals()[model_name]
     max_number = loop.run_until_complete(
         model.annotate(m=Max(field)).values_list("m", flat=True))[0]
     return max_number + 1 if max_number is not None else 1
Пример #11
0
async def get_sherpa_time_played(member_db: object) -> Tuple[int, list]:
    await member_db.member
    clan_sherpas = ClanMember.filter(is_sherpa=True,
                                     id__not=member_db.id).only("member_id")

    full_list = list(constants.SUPPORTED_GAME_MODES.values())
    mode_list = list(set([mode for sublist in full_list for mode in sublist]))

    all_games = GameMember.filter(
        game__mode_id__in=mode_list,
        member=member_db.member,
        time_played__not_isnull=True,
    ).only("game_id")

    sherpa_games = (GameMember.filter(
        game_id__in=Subquery(all_games),
        member_id__in=Subquery(clan_sherpas),
        time_played__not_isnull=True,
    ).distinct().only("game_id"))

    # Ideally one more optimal query whould look like this, which would return all the data we'd need
    # in one query. But this is not currently possible with Tortoise.
    # SELECT DISTINCT ON (m.game_id) m.game_id, m.member_id, t.sherpa_time
    # FROM(
    # 	SELECT "game_id" "game_id", MAX("time_played") "sherpa_time"
    # 	FROM "gamemember"
    # 	WHERE "game_id" IN(2078188, 2078189)
    # 	AND "member_id" IN(7, 75, 92, 108, 14, 11, 56, 95, 38, 167, 220, 48, 263, 47)
    # 	AND NOT "time_played" IS NULL
    # 	GROUP BY "game_id"
    # ) AS t
    # JOIN gamemember m ON m.game_id = t.game_id

    query = (await GameMember.annotate(sherpa_time=Max("time_played")).filter(
        game_id__in=Subquery(sherpa_games),
        member_id__in=Subquery(clan_sherpas),
        sherpa_time__not_isnull=True,
    ).group_by("game_id").values("game_id", "sherpa_time"))

    total_time = 0
    for result in query:
        total_time += result["sherpa_time"]

    # https://github.com/tortoise/tortoise-orm/issues/780
    all_games = GameMember.filter(
        game__mode_id__in=mode_list,
        member=member_db.member,
        time_played__not_isnull=True,
    ).only("game_id")

    sherpa_games = (GameMember.filter(
        game_id__in=Subquery(all_games),
        member_id__in=Subquery(clan_sherpas),
        time_played__not_isnull=True,
    ).distinct().only("game_id"))

    sherpa_ids = (GameMember.filter(
        game_id__in=Subquery(sherpa_games),
        member_id__in=Subquery(clan_sherpas),
        time_played__not_isnull=True,
    ).distinct().values_list("member__discord_id", flat=True))

    return (total_time, sherpa_ids)