public async Task <ImmutableArray <OrganizationInfo> > GetOrganizationsAsync(
            CancellationToken cancellationToken = default)
        {
            using (IQuerySession session = _documentStore.QuerySession())
            {
                try
                {
                    IReadOnlyList <DeploymentTargetData> targets =
                        await session.Query <DeploymentTargetData>()
                        .ToListAsync <DeploymentTargetData>(cancellationToken);

                    IReadOnlyList <ProjectData> projects =
                        await session.Query <ProjectData>()
                        .ToListAsync <ProjectData>(cancellationToken);

                    IReadOnlyList <OrganizationData> organizations =
                        await session.Query <OrganizationData>()
                        .ToListAsync <OrganizationData>(
                            cancellationToken);

                    ImmutableArray <OrganizationInfo> organizationsInfo =
                        MapDataToOrganizations(organizations, projects, targets);

                    return(organizationsInfo);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    _logger.Warning(ex, "Could not get any organizations targets");
                    return(ImmutableArray <OrganizationInfo> .Empty);
                }
            }
        }
            public IQueryable <TValue> Query(
                Expression <Func <TKey, bool> > predicate = null)
            {
                var memberValues = EmptyReadOnlyDictionary <string, object> .Instance as
                                   IReadOnlyDictionary <string, object>;

                if (predicate != null)
                {
                    memberValues = new InvariantExtractor().ExtractInvariantDictionary(
                        predicate,
                        out var invariantExpression);
                }

                var queryable = _querySession.Query <TValue>() as IQueryable <TValue>;

                var keyPrefix = _dataStore.EvaluatePath(
                    memberValues,
                    allowPartialMap: true);

                if (!string.IsNullOrWhiteSpace(keyPrefix))
                {
                    queryable = queryable.Where(e => e.Id.StartsWith(keyPrefix));
                }

                return(queryable);
            }
Esempio n. 3
0
 public void use_distinct(IQuerySession session)
 {
     var surnames = session
         .Query<User>()
         .Select(x => x.LastName)
         .Distinct();
 }
Esempio n. 4
0
        public async Task Group(IQuerySession session, IEnumerable <IEvent> events, ITenantSliceGroup <Guid> grouping)
        {
            var licenceFeatureTogglesEvents = events
                                              .OfType <IEvent <LicenseFeatureToggled> >()
                                              .ToList();

            if (!licenceFeatureTogglesEvents.Any())
            {
                return;
            }

            // TODO -- let's build more samples first, but see if there's a useful
            // pattern for the next 3/4 operations later
            var licenceIds = licenceFeatureTogglesEvents
                             .Select(e => e.Data.LicenseId)
                             .ToList();

            var result = await session.Query <UserFeatureToggles>()
                         .Where(x => licenceIds.Contains(x.LicenseId))
                         .Select(x => new { x.Id, x.LicenseId })
                         .ToListAsync();

            var streamIds = (IDictionary <Guid, List <Guid> >)result.GroupBy(ks => ks.LicenseId, vs => vs.Id)
                            .ToDictionary(ks => ks.Key, vs => vs.ToList());

            grouping.AddEvents <LicenseFeatureToggled>(e => streamIds[e.LicenseId], licenceFeatureTogglesEvents);
        }
Esempio n. 5
0
 public void use_distinct(IQuerySession session)
 {
     var surnames = session
                    .Query <User>()
                    .Select(x => x.LastName)
                    .Distinct();
 }
        public async Task <DeploymentTarget> GetDeploymentTargetAsync(
            [NotNull] string deploymentTargetId,
            CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(deploymentTargetId))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(deploymentTargetId));
            }

            using (IQuerySession session = _documentStore.QuerySession())
            {
                try
                {
                    DeploymentTargetData deploymentTargetData = await session.Query <DeploymentTargetData>()
                                                                .SingleOrDefaultAsync(target =>
                                                                                      target.Id.Equals(deploymentTargetId, StringComparison.OrdinalIgnoreCase),
                                                                                      cancellationToken);

                    DeploymentTarget deploymentTarget = MapDataToTarget(deploymentTargetData);

                    return(deploymentTarget);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    _logger.Warning(ex, "Could not get deployment target with id {Id}", deploymentTargetId);
                    return(DeploymentTarget.None);
                }
            }
        }
Esempio n. 7
0
 public async Task <IActionResult> GetBooks()
 {
     using (IQuerySession session = this.DocumentStore.QuerySession())
     {
         return(Ok(await session.Query <Book>().ToListAsync()));
     }
 }
Esempio n. 8
0
        public async Task <SagaRepositoryQueryContext <TSaga> > Query(ISagaQuery <TSaga> query, CancellationToken cancellationToken = default)
        {
            IReadOnlyList <TSaga> instances = await _session.Query <TSaga>()
                                              .Where(query.FilterExpression)
                                              .ToListAsync(cancellationToken).ConfigureAwait(false);

            return(new LoadedSagaRepositoryQueryContext <TSaga>(this, instances));
        }
Esempio n. 9
0
        public override async Task Compare(IQuerySession session, Target[] documents)
        {
            var expected = _func(documents.AsQueryable()).Select(x => x.Id).ToArray();

            var actual = (await(_func(session.Query <Target>()).Select(x => x.Id).ToListAsync())).ToArray();

            assertSame(expected, actual);
        }
Esempio n. 10
0
        public void QueryForWholeDocumentByWhereClause(IQuerySession session)
        {
            #region sample_query_for_whole_document_by_where_clause

            var millers = session
                          .Query <User>("where data ->> 'LastName' = 'Miller'");

            #endregion
        }
Esempio n. 11
0
        public void QueryWithParameters(IQuerySession session)
        {
            #region sample_query_with_sql_async

            var millers = session
                          .Query <User>("where data ->> 'LastName' = ?", "Miller");

            #endregion
        }
Esempio n. 12
0
 public Task OpenIssues([FromServices] IQuerySession session)
 {
     // This "streams" the raw JSON to the HttpResponse
     // w/o ever having to read the full JSON string or
     // deserialize/serialize within the HTTP request
     return(session.Query <Issue>()
            .Where(x => x.Open)
            .WriteArray(HttpContext));
 }
Esempio n. 13
0
 public Task <IReadOnlyList <IssueTitle> > Issues([FromServices] IQuerySession session, IssueStatus status)
 {
     return(session.Query <Issue>()
            .Where(x => x.Status == status)
            .Select(x => new IssueTitle {
         Title = x.Title, Id = x.Id
     })
            .ToListAsync());
 }
Esempio n. 14
0
        public async Task <bool> ShouldDelete(IQuerySession session, Trip trip, Breakdown breakdown)
        {
            var anyRepairShopsInState = await session.Query <RepairShop>()
                                        .Where(x => x.State == trip.State)
                                        .AnyAsync();

            // Delete the trip if there are no repair shops in
            // the current state
            return(!anyRepairShopsInState);
        }
Esempio n. 15
0
        public async Task sample_usage(IQuerySession session)
        {
            var fiveMinutesAgo = DateTime.UtcNow.AddMinutes(-5);
            var tenMinutesAgo  = DateTime.UtcNow.AddMinutes(-10);

            // Query for documents modified between 5 and 10 minutes ago
            var recents = await session.Query <Target>()
                          .Where(x => x.ModifiedSince(tenMinutesAgo))
                          .Where(x => x.ModifiedBefore(fiveMinutesAgo))
                          .ToListAsync();
        }
        private static async Task <IDictionary <Guid, List <Guid> > > FindUserIdsWithLicense(IQuerySession session, IEnumerable <LicenseFeatureToggled> events)
        {
            var licenceIds = events.Select(e => e.LicenseId).ToList();

            var result = await session.Query <UserFeatureToggles>()
                         .Where(x => licenceIds.Contains(x.LicenseId))
                         .Select(x => new { x.Id, x.LicenseId })
                         .ToListAsync();

            return(result.GroupBy(ks => ks.LicenseId, vs => vs.Id)
                   .ToDictionary(ks => ks.Key, vs => vs.ToList()));
        }
Esempio n. 17
0
        public async Task sample_aggregation_operations(IQuerySession session)
        {
            var count  = session.Query <Target>().Count();
            var count2 = await session.Query <Target>().CountAsync();

            var count3 = session.Query <Target>().LongCount();
            var count4 = await session.Query <Target>().LongCountAsync();

            var min = await session.Query <Target>().MinAsync(x => x.Number);

            var max = await session.Query <Target>().MaxAsync(x => x.Number);

            var sum = await session.Query <Target>().SumAsync(x => x.Number);

            var average = await session.Query <Target>().AverageAsync(x => x.Number);
        }
Esempio n. 18
0
        public override TResult Execute <TResult>(IQuerySession session)
        {
            if (typeof(TResult) != typeof(TModel))
            {
                throw new NotSupportedException();
            }

            var targetQueryable = Target;

            if (Expression != null)
            {
                targetQueryable = new WhereQueryable <TModel>(session, Target, Expression, JsonSettings);
            }

            var query = targetQueryable.BuildQuery();

            var results = session.Query <TResult>(query)
                          .GetAwaiter()
                          .GetResult();

            switch (Type)
            {
            case SingularExecutorType.First:
            {
                return(IsOrDefault
                        ? results.FirstOrDefault()
                        : results.First());
            }

            case SingularExecutorType.Single:
            {
                return(IsOrDefault
                        ? results.SingleOrDefault()
                        : results.Single());
            }

            case SingularExecutorType.Last:
            {
                return(IsOrDefault
                        ? results.LastOrDefault()
                        : results.Last());
            }

            default:     // not sure how this is possible, but it makes the compiler happy
            {
                throw new NotSupportedException();
            }
            }
        }
Esempio n. 19
0
        private async Task <TeamData> GetTeam(IQuerySession runningDocumentSession, string uncheckedTeamCode)
        {
            var teamData = await runningDocumentSession
                           .Query <TeamData>()
                           .Where(t => t.TeamCode.Equals(uncheckedTeamCode, StringComparison.OrdinalIgnoreCase))
                           .SingleOrDefaultAsync()
                           .ConfigureAwait(false);

            if (teamData == null)
            {
                throw new ArgumentException($"No team exists with team code: {uncheckedTeamCode}");
            }

            return(teamData);
        }
        public static T GetFirst <T>(this IQuerySession session, Expression <Func <T, bool> > predicate)
            where T : class
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            return(session.Query <T>()
                   .FirstOrDefault(predicate));
        }
        public async Task <ImmutableArray <ProjectInfo> > GetProjectsAsync(
            string organizationId,
            CancellationToken cancellationToken = default)
        {
            using (IQuerySession session = _documentStore.QuerySession())
            {
                IReadOnlyList <ProjectData> projects =
                    await session.Query <ProjectData>().Where(project =>
                                                              project.OrganizationId.Equals(organizationId, StringComparison.OrdinalIgnoreCase))
                    .ToListAsync(cancellationToken);

                return(projects.Select(project =>
                                       new ProjectInfo(project.OrganizationId, project.Id, ImmutableArray <DeploymentTarget> .Empty))
                       .ToImmutableArray());
            }
        }
        public async Task <ImmutableArray <DeploymentTarget> > GetDeploymentTargetsAsync(CancellationToken stoppingToken)
        {
            using (IQuerySession session = _documentStore.QuerySession())
            {
                try
                {
                    IReadOnlyList <DeploymentTargetData> targets = await session.Query <DeploymentTargetData>()
                                                                   .ToListAsync <DeploymentTargetData>(stoppingToken);

                    ImmutableArray <DeploymentTarget> deploymentTargets =
                        targets.Select(MapDataToTarget).ToImmutableArray();

                    return(deploymentTargets);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    _logger.Warning(ex, "Could not get any deployment targets");
                    return(ImmutableArray <DeploymentTarget> .Empty);
                }
            }
        }
 // A shorthand for generating the required SQL statement for a sequence value query
 public static int NextInSequence(this IQuerySession session, Sequence sequence)
 {
     return(session.Query <int>("select nextval(?)", sequence.Identifier.QualifiedName).First());
 }
Esempio n. 24
0
 public ActionResult <IEnumerable <Dummy> > Get()
 {
     return(session.Query <Dummy>().Where(x => x.Value != null).ToList());
 }
Esempio n. 25
0
 public string Index()
 {
     return(_session.Query <User>().OrderBy(x => x.Id).ToArray().Select(x => x.Id).Join(", "));
 }
Esempio n. 26
0
 public IMartenQueryable <T> Query <T>()
 {
     return((IMartenQueryable <T>)_querySession.Query <T>()
            .OnlyItemsTheUserCanSee(_securityQueryProvider, _martenContext));
 }
Esempio n. 27
0
 public Task Get3(Guid issueId, [FromServices] IQuerySession session)
 {
     return(session.Query <Issue>().Where(x => x.Id == issueId)
            .WriteSingle(HttpContext));
 }