public void CombinedTest()
        {
            const string parameterName = "TestParameter";
            var          parameter     = new Parameter <int>(parameterName);

            Assert.AreEqual(parameterName, parameter.Name);
            Assert.Throws <NotSupportedException>(() => _ = parameter.Value);

            var firstContext = new ParameterContext();

            firstContext.SetValue(parameter, 10);
            Assert.AreEqual(10, firstContext.GetValue(parameter));
            firstContext.SetValue(parameter, 15);
            Assert.AreEqual(15, firstContext.GetValue(parameter));

            var secondContext = new ParameterContext(firstContext);

            Assert.AreEqual(15, secondContext.GetValue(parameter));
            secondContext.SetValue(parameter, 20);
            Assert.AreEqual(20, secondContext.GetValue(parameter));

            Assert.AreEqual(15, firstContext.GetValue(parameter));
            firstContext.SetValue(parameter, 25);
            Assert.AreEqual(25, firstContext.GetValue(parameter));
            Assert.AreEqual(20, secondContext.GetValue(parameter));
        }
Esempio n. 2
0
        private ParameterizedQuery GetScalarQuery <TResult>(
            Func <QueryEndpoint, TResult> query, bool executeAsSideEffect, out TResult result)
        {
            AllocateParameterAndReplacer();

            var parameterContext = new ParameterContext(outerContext);

            parameterContext.SetValue(queryParameter, queryTarget);
            var scope = new CompiledQueryProcessingScope(
                queryParameter, queryParameterReplacer, parameterContext, executeAsSideEffect);

            using (scope.Enter()) {
                result = query.Invoke(endpoint);
            }

            var parameterizedQuery = (ParameterizedQuery)scope.ParameterizedQuery;

            if (parameterizedQuery == null && queryTarget != null)
            {
                throw new NotSupportedException(Strings.ExNonLinqCallsAreNotSupportedWithinQueryExecuteDelayed);
            }

            PutCachedQuery(parameterizedQuery);
            return(parameterizedQuery);
        }
Esempio n. 3
0
        // Constructors

// ReSharper disable MemberCanBeProtected.Global
        public SubQuery(ProjectionExpression projectionExpression, TranslatedQuery query, Parameter <Tuple> parameter, Tuple tuple, ItemMaterializationContext context)
// ReSharper restore MemberCanBeProtected.Global
        {
            this.provider = context.Session.Query.Provider;
            var tupleParameterBindings = new Dictionary <Parameter <Tuple>, Tuple>(projectionExpression.TupleParameterBindings);
            var currentTranslatedQuery = query;

            var outerParameterContext = context.ParameterContext;
            var parameterContext      = new ParameterContext(outerParameterContext);

            // Gather Parameter<Tuple> values from current ParameterScope for future use.
            outerParameterContext.SetValue(parameter, tuple);
            foreach (var tupleParameter in currentTranslatedQuery.TupleParameters)
            {
                var value = outerParameterContext.GetValue(tupleParameter);
                tupleParameterBindings[tupleParameter] = value;
                parameterContext.SetValue(tupleParameter, value);
            }

            this.projectionExpression = new ProjectionExpression(
                projectionExpression.Type,
                projectionExpression.ItemProjector,
                tupleParameterBindings,
                projectionExpression.ResultAccessMethod);
            var translatedQuery = new TranslatedQuery(
                query.DataSource,
                query.Materializer,
                query.ResultAccessMethod,
                tupleParameterBindings,
                EnumerableUtils <Parameter <Tuple> > .Empty);

            delayedQuery = new DelayedQuery <TElement>(context.Session, translatedQuery, parameterContext);
            context.Session.RegisterUserDefinedDelayedQuery(delayedQuery.Task);
            context.MaterializationContext.MaterializationQueue.Enqueue(MaterializeSelf);
        }
Esempio n. 4
0
        private bool Contains(Key key, Entity item)
        {
            // state check
            var foundInCache = State.Contains(key);

            if (foundInCache)
            {
                return(true);
            }
            var ownerState = Owner.PersistenceState;
            var itemState  = item == null
        ? PersistenceState.Synchronized
        : item.PersistenceState;

            if (PersistenceState.New.In(ownerState, itemState) || State.IsFullyLoaded)
            {
                return(false);
            }

            // association check
            if (item != null)
            {
                var association = Field.GetAssociation(item.TypeInfo);
                if (association.IsPaired && association.Multiplicity.In(Multiplicity.ManyToOne, Multiplicity.OneToMany))
                {
                    var candidate = (IEntity)item.GetFieldValue(association.Reversed.OwnerField);
                    return(candidate == Owner);
                }
            }

            // load from storage
            EnsureIsLoaded(WellKnown.EntitySetPreloadCount);

            foundInCache = State.Contains(key);
            if (foundInCache)
            {
                return(true);
            }
            if (State.IsFullyLoaded)
            {
                return(false);
            }

            bool foundInDatabase;
            var  entitySetTypeState = GetEntitySetTypeState();

            var parameterContext = new ParameterContext();

            parameterContext.SetValue(keyParameter, entitySetTypeState.SeekTransform
                                      .Apply(TupleTransformType.TransformedTuple, Owner.Key.Value, key.Value));
            using (var recordSetReader = entitySetTypeState.SeekProvider.GetRecordSetReader(Session, parameterContext)) {
                foundInDatabase = recordSetReader.MoveNext();
            }

            if (foundInDatabase)
            {
                State.Register(key);
            }
            return(foundInDatabase);
        }
Esempio n. 5
0
        private ParameterContext CreateParameterContext(ParameterizedQuery query)
        {
            var parameterContext = new ParameterContext(outerContext);

            if (query.QueryParameter != null)
            {
                parameterContext.SetValue(query.QueryParameter, queryTarget);
            }

            return(parameterContext);
        }
        /// <summary>
        /// Executes the query in specified parameter context.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="parameterContext">The parameter context.</param>
        /// <returns>Query execution result.</returns>
        public QueryResult <T> ExecuteSequence <T>(Session session, ParameterContext parameterContext)
        {
            var newParameterContext = new ParameterContext(parameterContext);

            foreach (var(parameter, tuple) in TupleParameterBindings)
            {
                newParameterContext.SetValue(parameter, tuple);
            }
            var recordSetReader = DataSource.GetRecordSetReader(session, newParameterContext);

            return(Materializer.Invoke <T>(recordSetReader, session, newParameterContext));
        }
        public void ConfusingParameterTest()
        {
            var parameter        = new Parameter <Tuple>("ConfusingParameter");
            var parameterContext = new ParameterContext();

            parameterContext.SetValue(parameter, Tuple.Create(false));
            TestQuery(
                () =>
                from o in Session.Demand().Query.All <MyEntity>()
                where o.HasStupidName == parameterContext.GetValue(parameter).GetValueOrDefault <bool>(0)
                select o
                );
        }
Esempio n. 8
0
        private QueryTask CreateQueryTask()
        {
            var parameterContext = new ParameterContext();

            parameterContext.SetValue(ownerParameter, ownerKey.Value);
            if (ItemCountLimit != null)
            {
                parameterContext.SetValue(itemCountLimitParameter, ItemCountLimit.Value);
            }

            object key = new Pair <object, CacheKey>(itemsQueryCachingRegion, cacheKey);
            Func <object, object> generator = CreateRecordSetLoadingItems;
            var session = manager.Owner.Session;
            var scope   = new CompiledQueryProcessingScope(null, null, parameterContext, false);

            QueryProvider = (CompilableProvider)session.StorageNode.InternalQueryCache.GetOrAdd(key, generator);
            ExecutableProvider executableProvider;

            using (scope.Enter()) {
                executableProvider = session.Compile(QueryProvider);
            }
            return(new QueryTask(executableProvider, session.GetLifetimeToken(), parameterContext));
        }
        private QueryTask CreateQueryTask(List <Tuple> currentKeySet)
        {
            var parameterContext = new ParameterContext();

            parameterContext.SetValue(includeParameter, currentKeySet);
            object key = new Pair <object, CacheKey>(recordSetCachingRegion, cacheKey);
            Func <object, object> generator = CreateRecordSet;
            var session = manager.Owner.Session;

            Provider = (CompilableProvider)session.StorageNode.InternalQueryCache.GetOrAdd(key, generator);
            var executableProvider = session.Compile(Provider);

            return(new QueryTask(executableProvider, session.GetLifetimeToken(), parameterContext));
        }
        /// <summary>
        /// Asynchronously executes the query in specified parameter context.
        /// </summary>
        /// <remarks> Multiple active operations are not supported. Use <see langword="await"/>
        /// to ensure that all asynchronous operations have completed.</remarks>
        /// <param name="session">The session.</param>
        /// <param name="parameterContext">The parameter context.</param>
        /// <param name="token">The token to cancel this operation</param>
        /// <returns><see cref="Task{TResult}"/> performing this operation.</returns>
        public async Task <QueryResult <T> > ExecuteSequenceAsync <T>(
            Session session, ParameterContext parameterContext, CancellationToken token)
        {
            var newParameterContext = new ParameterContext(parameterContext);

            foreach (var(parameter, tuple) in TupleParameterBindings)
            {
                newParameterContext.SetValue(parameter, tuple);
            }
            var recordSetReader =
                await DataSource.GetRecordSetReaderAsync(session, newParameterContext, token).ConfigureAwait(false);

            return(Materializer.Invoke <T>(recordSetReader, session, newParameterContext));
        }
Esempio n. 11
0
        private void EnsureCountIsLoaded()
        {
            if (State.TotalItemCount != null)
            {
                return;
            }

            var parameterContext = new ParameterContext();

            parameterContext.SetValue(ownerParameter, owner);

            var cachedState = GetEntitySetTypeState();

            State.TotalItemCount = Session.Query.Execute(cachedState, cachedState.ItemCountQuery, parameterContext);
        }
Esempio n. 12
0
        // Constructors

        /// <summary>
        /// Initializes a new instance of this class.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="translatedQuery">The translated query.</param>
        /// <param name="outerParameterContext">The parameter context.</param>
        internal DelayedQuery(Session session, TranslatedQuery translatedQuery, ParameterContext outerParameterContext)
        {
            ArgumentValidator.EnsureArgumentNotNull(session, nameof(session));
            ArgumentValidator.EnsureArgumentNotNull(translatedQuery, nameof(translatedQuery));
            ArgumentValidator.EnsureArgumentNotNull(outerParameterContext, nameof(outerParameterContext));

            Session       = session;
            LifetimeToken = session.GetLifetimeToken();

            materializer     = translatedQuery.Materializer;
            parameterContext = new ParameterContext(outerParameterContext);
            foreach (var(parameter, tuple) in translatedQuery.TupleParameterBindings)
            {
                parameterContext.SetValue(parameter, tuple);
            }

            Task = new QueryTask(translatedQuery.DataSource, LifetimeToken, parameterContext);
        }
Esempio n. 13
0
        /// <inheritdoc/>
        public void Lock(LockMode lockMode, LockBehavior lockBehavior)
        {
            var parameterContext = new ParameterContext();

            parameterContext.SetValue(keyParameter, Key.Value);
            object key = new Triplet <TypeInfo, LockMode, LockBehavior>(TypeInfo, lockMode, lockBehavior);
            Func <object, object> generator = tripletObj => {
                var triplet = (Triplet <TypeInfo, LockMode, LockBehavior>)tripletObj;
                var index   = triplet.First.Indexes.PrimaryIndex;
                var query   = index.GetQuery()
                              .Seek(context => context.GetValue(keyParameter))
                              .Lock(() => triplet.Second, () => triplet.Third)
                              .Select();
                return(Session.Compile(query));
            };
            var source = (ExecutableProvider)Session.StorageNode.InternalQueryCache.GetOrAdd(key, generator);

            using var recordSetReader = source.GetRecordSetReader(Session, parameterContext);
            recordSetReader.MoveNext();
        }
        /// <summary>
        /// Gets the references to specified entity.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="association">The association.</param>
        /// <returns>References.</returns>
        public virtual IEnumerable <ReferenceInfo> GetReferencesTo(Entity target, AssociationInfo association)
        {
            if (association.IsPaired)
            {
                return(FindReferences(target, association, true));
            }
            object key = new Pair <object, AssociationInfo>(CachingRegion, association);
            Func <object, object> generator = p => BuildReferencingQuery(((Pair <object, AssociationInfo>)p).Second);
            var pair             = (Pair <CompilableProvider, Parameter <Tuple> >)Session.StorageNode.InternalQueryCache.GetOrAdd(key, generator);
            var recordSet        = pair.First;
            var parameter        = pair.Second;
            var parameterContext = new ParameterContext();

            parameterContext.SetValue(parameter, target.Key.Value);
            ExecutableProvider executableProvider = Session.Compile(recordSet);

            var queryTask = new QueryTask(executableProvider, Session.GetLifetimeToken(), parameterContext);

            Session.RegisterInternalDelayedQuery(queryTask);

            return(GetReferencesToInternal(association, target, recordSet.Header, queryTask));
        }
Esempio n. 15
0
 private void CachedRseQueryTest(int count)
 {
     using (var session = Domain.OpenSession())
         using (session.Activate())
             using (var ts = session.OpenTransaction()) {
                 TestHelper.CollectGarbage();
                 var pKey             = new Parameter <Tuple>("pKey");
                 var rs               = Domain.Model.Types[typeof(Simplest)].Indexes.PrimaryIndex.GetQuery().Seek(context => context.GetValue(pKey));
                 var parameterContext = new ParameterContext();
                 using (warmup ? null : new Measurement("Cached RSE query", count)) {
                     for (int i = 0; i < count; i++)
                     {
                         parameterContext.SetValue(pKey, Tuple.Create((long)(i % instanceCount)));
                         var es = rs.GetRecordSetReader(session, parameterContext).ToEntities <Simplest>(0);
                         foreach (var o in es)
                         {
                             // Doing nothing, just enumerate
                         }
                     }
                 }
                 ts.Complete();
             }
 }