def update_repository_score(repo): """ Updates the repository score entry for the given table by retrieving information from the RepositoryActionCount table. Note that count_repository_actions for the repo should be called first. Returns True if the row was updated and False otherwise. """ today = date.today() # Retrieve the counts for each bucket and calculate the final score. final_score = 0.0 last_end_timedelta = timedelta(days=0) for bucket in SEARCH_BUCKETS: start_date = today - bucket.delta end_date = today - last_end_timedelta last_end_timedelta = bucket.delta query = RepositoryActionCount.select( fn.Sum(RepositoryActionCount.count), fn.Count(RepositoryActionCount.id) ).where( RepositoryActionCount.date >= start_date, RepositoryActionCount.date < end_date, RepositoryActionCount.repository == repo, ) bucket_tuple = query.tuples()[0] logger.debug( "Got bucket tuple %s for bucket %s for repository %s", bucket_tuple, bucket, repo.id ) if bucket_tuple[0] is None: continue bucket_sum = float(bucket_tuple[0]) bucket_count = int(bucket_tuple[1]) if not bucket_count: continue bucket_score = bucket_sum / (bucket_count * 1.0) final_score += bucket_score * bucket.weight # Update the existing repo search score row or create a new one. normalized_score = int(final_score * 100.0) try: try: search_score_row = RepositorySearchScore.get(repository=repo) search_score_row.last_updated = datetime.now() search_score_row.score = normalized_score search_score_row.save() return True except RepositorySearchScore.DoesNotExist: RepositorySearchScore.create( repository=repo, score=normalized_score, last_updated=today ) return True except IntegrityError: logger.debug("RepositorySearchScore row already existed; skipping") return False
def test_update_repository_score(bucket_sums, expected_score, initialized_db): # Create a new repository. repo = create_repository('devtable', 'somenewrepo', None, repo_kind='image') # Delete the RAC created in create_repository. RepositoryActionCount.delete().where( RepositoryActionCount.repository == repo).execute() # Add RAC rows for each of the buckets. for index, bucket in enumerate(SEARCH_BUCKETS): for day in range(0, bucket.days): RepositoryActionCount.create( repository=repo, count=(bucket_sums[index] / bucket.days * 1.0), date=date.today() - bucket.delta + timedelta(days=day)) assert update_repository_score(repo) assert RepositorySearchScore.get(repository=repo).score == expected_score