示例#1
0
        /// <summary>
        /// Retrieve multiple query results from the cache.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="keys">The query keys.</param>
        /// <param name="queryParameters">The array of query parameters matching <paramref name="keys"/>.</param>
        /// <param name="returnTypes">The array of query result row types matching <paramref name="keys"/>.</param>
        /// <param name="spaces">The array of query spaces matching <paramref name="keys"/>.</param>
        /// <param name="session">The session for which the queries are executed.</param>
        /// <returns>The cached query results, matching each key of <paramref name="keys"/> respectively. For each
        /// missed key, it will contain a <see langword="null" />.</returns>
        public static IList[] GetMany(
            this IQueryCache queryCache,
            QueryKey[] keys,
            QueryParameters[] queryParameters,
            ICacheAssembler[][] returnTypes,
            ISet <string>[] spaces,
            ISessionImplementor session)
        {
            if (queryCache is IBatchableQueryCache batchableQueryCache)
            {
                return(batchableQueryCache.GetMany(
                           keys,
                           queryParameters,
                           returnTypes,
                           spaces,
                           session));
            }

            var results = new IList[keys.Length];

            for (var i = 0; i < keys.Length; i++)
            {
                results[i] = queryCache.Get(keys[i], queryParameters[i], returnTypes[i], spaces[i], session);
            }

            return(results);
        }
示例#2
0
        /// <summary>
        /// Put query results in the cache.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="key">The query key.</param>
        /// <param name="queryParameters">The query parameters.</param>
        /// <param name="returnTypes">The query result row types.</param>
        /// <param name="result">The query result.</param>
        /// <param name="session">The session for which the query was executed.</param>
        /// <returns><see langword="true" /> if the result has been cached, <see langword="false" />
        /// otherwise.</returns>
        public static bool Put(
            this IQueryCache queryCache,
            QueryKey key,
            QueryParameters queryParameters,
            ICacheAssembler[] returnTypes,
            IList result,
            ISessionImplementor session)
        {
            if (queryCache is IBatchableQueryCache batchableQueryCache)
            {
                return(batchableQueryCache.Put(
                           key, queryParameters,
                           returnTypes,
                           result, session));
            }

#pragma warning disable 618
            return(queryCache.Put(
#pragma warning restore 618
                       key,
                       returnTypes,
                       result,
                       queryParameters.NaturalKeyLookup,
                       session));
        }
示例#3
0
        /// <summary>
        /// Attempt to cache objects, after loading them from the database.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="keys">The query keys.</param>
        /// <param name="queryParameters">The array of query parameters matching <paramref name="keys"/>.</param>
        /// <param name="returnTypes">The array of query result row types matching <paramref name="keys"/>.</param>
        /// <param name="results">The array of query results matching <paramref name="keys"/>.</param>
        /// <param name="session">The session for which the queries were executed.</param>
        /// <returns>An array of boolean indicating if each query was successfully cached.</returns>
        /// <exception cref="CacheException"></exception>
        public static bool[] PutMany(
            this IQueryCache queryCache,
            QueryKey[] keys,
            QueryParameters[] queryParameters,
            ICacheAssembler[][] returnTypes,
            IList[] results,
            ISessionImplementor session)
        {
            if (queryCache is IBatchableQueryCache batchableQueryCache)
            {
                return(batchableQueryCache.PutMany(
                           keys,
                           queryParameters,
                           returnTypes,
                           results,
                           session));
            }

            var puts = new bool[keys.Length];

            for (var i = 0; i < keys.Length; i++)
            {
                puts[i] = queryCache.Put(keys[i], queryParameters[i], returnTypes[i], results[i], session);
            }

            return(puts);
        }
示例#4
0
        /// <summary>
        /// Attempt to cache objects, after loading them from the database.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="keys">The query keys.</param>
        /// <param name="queryParameters">The array of query parameters matching <paramref name="keys"/>.</param>
        /// <param name="returnTypes">The array of query result row types matching <paramref name="keys"/>.</param>
        /// <param name="results">The array of query results matching <paramref name="keys"/>.</param>
        /// <param name="session">The session for which the queries were executed.</param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns>An array of boolean indicating if each query was successfully cached.</returns>
        /// <exception cref="CacheException"></exception>
        public static async Task <bool[]> PutManyAsync(
            this IQueryCache queryCache,
            QueryKey[] keys,
            QueryParameters[] queryParameters,
            ICacheAssembler[][] returnTypes,
            IList[] results,
            ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (queryCache is IBatchableQueryCache batchableQueryCache)
            {
                return(await(batchableQueryCache.PutManyAsync(
                                 keys,
                                 queryParameters,
                                 returnTypes,
                                 results,
                                 session, cancellationToken)).ConfigureAwait(false));
            }

            var puts = new bool[keys.Length];

            for (var i = 0; i < keys.Length; i++)
            {
                puts[i] = await(queryCache.PutAsync(keys[i], queryParameters[i], returnTypes[i], results[i], session, cancellationToken)).ConfigureAwait(false);
            }

            return(puts);
        }
示例#5
0
 public void initTests()
 {
     if (testCache == null)
     {
         testCache = new QueryCache();
     }
 }
示例#6
0
 public bool TryGetIfUseCache(string tableName, out IQueryCache cache)
 {
     if (IsUseCache)
     {
         if (!_caches.TryGetValue(tableName, out cache))
         {
             lock (_lockGetCacheContainer)
             {
                 if (!_caches.TryGetValue(tableName, out cache))
                 {
                     cache = _queryCacheCreator.Create(tableName);
                     if (cache == null)
                     {
                         throw new ArgumentException($"The type [{_queryCacheCreator.GetType().Name}] to create a {nameof(IQueryCacheCreator)} instance can not be null");
                     }
                     _caches[tableName] = cache;
                 }
             }
         }
         return(true);
     }
     else
     {
         cache = null;
         return(false);
     }
 }
        private async Task <IList> ListUsingQueryCacheAsync(HashSet <string> querySpaces, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

            ISet <FilterKey> filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters);

            List <IType[]> resultTypesList = new List <IType[]>();

            int[] maxRows   = new int[loaders.Count];
            int[] firstRows = new int[loaders.Count];
            for (int i = 0; i < loaders.Count; i++)
            {
                resultTypesList.Add(loaders[i].ResultTypes);
                firstRows[i] = parameters[i].RowSelection.FirstRow;
                maxRows[i]   = parameters[i].RowSelection.MaxRows;
            }

            MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);
            QueryParameters combinedParameters      = CreateCombinedQueryParameters();
            QueryKey        key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys, null)
                                  .SetFirstRows(firstRows)
                                  .SetMaxRows(maxRows);

            IList result =
                await(assembler.GetResultFromQueryCacheAsync(session,
                                                             combinedParameters,
                                                             querySpaces,
                                                             queryCache,
                                                             key, cancellationToken)).ConfigureAwait(false);

            if (factory.Statistics.IsStatisticsEnabled)
            {
                if (result == null)
                {
                    factory.StatisticsImplementor.QueryCacheMiss(key.ToString(), queryCache.RegionName);
                }
                else
                {
                    factory.StatisticsImplementor.QueryCacheHit(key.ToString(), queryCache.RegionName);
                }
            }

            if (result == null)
            {
                log.Debug("Cache miss for multi criteria query");
                IList list = await(DoListAsync(cancellationToken)).ConfigureAwait(false);
                result = list;
                if (session.CacheMode.HasFlag(CacheMode.Put))
                {
                    bool put = await(queryCache.PutAsync(key, new ICacheAssembler[] { assembler }, new object[] { list }, combinedParameters.NaturalKeyLookup, session, cancellationToken)).ConfigureAwait(false);
                    if (put && factory.Statistics.IsStatisticsEnabled)
                    {
                        factory.StatisticsImplementor.QueryCachePut(key.ToString(), queryCache.RegionName);
                    }
                }
            }

            return(GetResultList(result));
        }
示例#8
0
 public async Task <T> ExecuteAsync(IQueryCache <T> cache)
 {
     if (enableCache_)
     {
         return(await cache.QueryAsync(query_));
     }
     else
     {
         return(await cache.QueryIgnoreCacheAsync(query_));
     }
 }
示例#9
0
        /// <summary>
        /// Get query results from the cache.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="key">The query key.</param>
        /// <param name="queryParameters">The query parameters.</param>
        /// <param name="returnTypes">The query result row types.</param>
        /// <param name="spaces">The query spaces.</param>
        /// <param name="session">The session for which the query is executed.</param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns>The query results, if cached.</returns>
        public static async Task <IList> GetAsync(
            this IQueryCache queryCache,
            QueryKey key,
            QueryParameters queryParameters,
            ICacheAssembler[] returnTypes,
            ISet <string> spaces,
            ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (queryCache is IBatchableQueryCache batchableQueryCache)
            {
                return(await(batchableQueryCache.GetAsync(
                                 key,
                                 queryParameters,
                                 returnTypes,
                                 spaces,
                                 session, cancellationToken)).ConfigureAwait(false));
            }

            if (!_hasWarnForObsoleteQueryCache)
            {
                _hasWarnForObsoleteQueryCache = true;
                Log.Warn("{0} is obsolete, it should implement {1}", queryCache, nameof(IBatchableQueryCache));
            }

            var persistenceContext = session.PersistenceContext;

            var defaultReadOnlyOrig = persistenceContext.DefaultReadOnly;

            if (queryParameters.IsReadOnlyInitialized)
            {
                persistenceContext.DefaultReadOnly = queryParameters.ReadOnly;
            }
            else
            {
                queryParameters.ReadOnly = persistenceContext.DefaultReadOnly;
            }

            try
            {
#pragma warning disable 618
                return(await(queryCache.GetAsync(
#pragma warning restore 618
                                 key,
                                 returnTypes,
                                 queryParameters.NaturalKeyLookup,
                                 spaces,
                                 session, cancellationToken)).ConfigureAwait(false));
            }
            finally
            {
                persistenceContext.DefaultReadOnly = defaultReadOnlyOrig;
            }
        }
示例#10
0
 public Resolver(IDnsTransport transport, IQueryCache cache = null, IWhoisTransport wtransport = null, ITLDHandler tldHandler = null, ISpfChecker checker = null, int retrys = 3, int timeout = 60)
 {
     Transport      = transport;
     SpfChecker     = (checker ?? new SpfChecker());
     Retries        = retrys;
     TimeOut        = timeout;
     UseRecursion   = useRecursion;
     Cache          = (cache ?? new QueryCache());
     WhoisTransport = (wtransport ?? new WhoisTcpTransport());
     TldHandler     = (tldHandler ?? new TldHandler());
 }
        public IQueryCache GetQueryCache()
        {
            lock (lockobj)
            {
                if (_cache == null)
                {
                    _cache = new StandardQueryCache();
                }

                return(_cache);
            }
        }
示例#12
0
        /// <summary>
        /// Get query results from the cache.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="key">The query key.</param>
        /// <param name="queryParameters">The query parameters.</param>
        /// <param name="returnTypes">The query result row types.</param>
        /// <param name="spaces">The query spaces.</param>
        /// <param name="session">The session for which the query is executed.</param>
        /// <returns>The query results, if cached.</returns>
        public static IList Get(
            this IQueryCache queryCache,
            QueryKey key,
            QueryParameters queryParameters,
            ICacheAssembler[] returnTypes,
            ISet <string> spaces,
            ISessionImplementor session)
        {
            if (queryCache is IBatchableQueryCache batchableQueryCache)
            {
                return(batchableQueryCache.Get(
                           key,
                           queryParameters,
                           returnTypes,
                           spaces,
                           session));
            }

            if (!_hasWarnForObsoleteQueryCache)
            {
                _hasWarnForObsoleteQueryCache = true;
                Log.Warn("{0} is obsolete, it should implement {1}", queryCache, nameof(IBatchableQueryCache));
            }

            var persistenceContext = session.PersistenceContext;

            var defaultReadOnlyOrig = persistenceContext.DefaultReadOnly;

            if (queryParameters.IsReadOnlyInitialized)
            {
                persistenceContext.DefaultReadOnly = queryParameters.ReadOnly;
            }
            else
            {
                queryParameters.ReadOnly = persistenceContext.DefaultReadOnly;
            }

            try
            {
#pragma warning disable 618
                return(queryCache.Get(
#pragma warning restore 618
                           key,
                           returnTypes,
                           queryParameters.NaturalKeyLookup,
                           spaces,
                           session));
            }
            finally
            {
                persistenceContext.DefaultReadOnly = defaultReadOnlyOrig;
            }
        }
        public void ConverterQueryCacheTests()
        {
            IQueryCache cache = InstantiateCache();
            IConverter  cDown = new ConvertDown();
            IConverter  cUp   = new ConvertUp();

            IQueryCache convCache = ConverterCollections.GetQueryCache(cache, cUp, cDown, cUp, cDown);

            Assert.IsNotNull(convCache);
            for (int i = 0; i < 5; i++)
            {
                convCache.Add(i, i + 1);
            }
            Assert.AreEqual(convCache.Count, 5);

            IFilter filter = new EqualsFilter(IdentityExtractor.Instance, cDown.Convert("4"));

            object[] keys = convCache.GetKeys(filter);
            Assert.IsNotNull(keys);
            Assert.AreEqual(keys.Length, 1);
            Assert.AreEqual(keys[0], "3");

            filter = new GreaterEqualsFilter(IdentityExtractor.Instance, "2");
            object[] values = convCache.GetValues(filter);
            Assert.IsNotNull(values);
            Assert.AreEqual(values.Length, 4);
            values = convCache.GetValues(filter, Comparer.DefaultInvariant);
            Assert.IsNotNull(values);
            Assert.AreEqual(values.Length, 4);
            Assert.AreEqual(values[0], "2");

            object[] entries = convCache.GetEntries(filter);
            Assert.IsNotNull(entries);
            Assert.AreEqual(entries.Length, 4);
            entries = convCache.GetEntries(filter, new KeyExtractor(IdentityExtractor.Instance));
            Assert.IsNotNull(entries);
            Assert.AreEqual(entries.Length, 4);
            Assert.IsInstanceOf(typeof(ICacheEntry), entries[0]);
            ICacheEntry e = entries[0] as ICacheEntry;

            Assert.IsNotNull(e);
            Assert.AreEqual(e.Key, "1");
            Assert.AreEqual(e.Value, "2");

            Assert.IsInstanceOf(typeof(ConverterCollections.ConverterQueryCache), convCache);
            ConverterCollections.ConverterQueryCache cqc = convCache as ConverterCollections.ConverterQueryCache;
            Assert.IsNotNull(cqc);
            Assert.AreEqual(cqc.QueryCache, cache);
        }
示例#14
0
 public void EvictQueries(string cacheRegion)
 {
     if (cacheRegion == null)
     {
         throw new ArgumentNullException("cacheRegion", "use the zero-argument form to evict the default query cache");
     }
     else if (queryCaches != null)
     {
         IQueryCache currentQueryCache = ( IQueryCache )queryCaches[cacheRegion];
         if (currentQueryCache != null)
         {
             currentQueryCache.Clear();
         }
     }
 }
 public IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
                                      ISet <string> querySpaces, IQueryCache queryCache, QueryKey key)
 {
     if (!queryParameters.ForceCacheRefresh)
     {
         IList list =
             queryCache.Get(key, new ICacheAssembler[] { this }, queryParameters.NaturalKeyLookup, querySpaces, session);
         //we had to wrap the query results in another list in order to save all
         //the queries in the same bucket, now we need to do it the other way around.
         if (list != null)
         {
             list = (IList)list[0];
         }
         return(list);
     }
     return(null);
 }
		public IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
											 ISet<string> querySpaces, IQueryCache queryCache, QueryKey key)
		{
			if (!queryParameters.ForceCacheRefresh)
			{
				IList list =
					queryCache.Get(key, new ICacheAssembler[] {this}, queryParameters.NaturalKeyLookup, querySpaces, session);
				//we had to wrap the query results in another list in order to save all
				//the queries in the same bucket, now we need to do it the other way around.
				if (list != null)
				{
					list = (IList) list[0];
				}
				return list;
			}
			return null;
		}
示例#17
0
        private async Task <IList> ListUsingQueryCacheAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

            ISet <FilterKey> filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters);

            ISet <string>  querySpaces     = new HashSet <string>();
            List <IType[]> resultTypesList = new List <IType[]>(Translators.Count);

            for (int i = 0; i < Translators.Count; i++)
            {
                ITranslator queryTranslator = Translators[i];
                querySpaces.UnionWith(queryTranslator.QuerySpaces);
                resultTypesList.Add(queryTranslator.ReturnTypes);
            }
            int[] firstRows = new int[Parameters.Count];
            int[] maxRows   = new int[Parameters.Count];
            for (int i = 0; i < Parameters.Count; i++)
            {
                RowSelection rowSelection = Parameters[i].RowSelection;
                firstRows[i] = rowSelection.FirstRow;
                maxRows[i]   = rowSelection.MaxRows;
            }

            MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);

            QueryKey key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys, null)
                           .SetFirstRows(firstRows)
                           .SetMaxRows(maxRows);

            IList result = await(assembler.GetResultFromQueryCacheAsync(session, combinedParameters, querySpaces, queryCache, key, cancellationToken)).ConfigureAwait(false);

            if (result == null)
            {
                log.Debug("Cache miss for multi query");
                var list = await(DoListAsync(cancellationToken)).ConfigureAwait(false);
                await(queryCache.PutAsync(key, new ICacheAssembler[] { assembler }, new object[] { list }, false, session, cancellationToken)).ConfigureAwait(false);
                result = list;
            }

            return(GetResultList(result));
        }
示例#18
0
        private IList ListUsingQueryCache()
        {
            IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

            ISet <FilterKey> filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);

            ISet <string>  querySpaces     = new HashedSet <string>();
            List <IType[]> resultTypesList = new List <IType[]>(Translators.Count);

            for (int i = 0; i < Translators.Count; i++)
            {
                ITranslator queryTranslator = Translators[i];
                querySpaces.AddAll(queryTranslator.QuerySpaces);
                resultTypesList.Add(queryTranslator.ReturnTypes);
            }
            int[] firstRows = new int[Parameters.Count];
            int[] maxRows   = new int[Parameters.Count];
            for (int i = 0; i < Parameters.Count; i++)
            {
                RowSelection rowSelection = Parameters[i].RowSelection;
                firstRows[i] = rowSelection.FirstRow;
                maxRows[i]   = rowSelection.MaxRows;
            }

            MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);

            QueryKey key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys)
                           .SetFirstRows(firstRows)
                           .SetMaxRows(maxRows);

            IList result = assembler.GetResultFromQueryCache(session, combinedParameters, querySpaces, queryCache, key);

            if (result == null)
            {
                log.Debug("Cache miss for multi query");
                var list = DoList();
                queryCache.Put(key, new ICacheAssembler[] { assembler }, new object[] { list }, false, session);
                result = list;
            }

            return(GetResultList(result));
        }
示例#19
0
        private IList ListUsingQueryCache()
        {
            IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

            ISet <FilterKey> filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);

            ISet <string>  querySpaces     = new HashSet <string>();
            List <IType[]> resultTypesList = new List <IType[]>();

            int[] maxRows   = new int[loaders.Count];
            int[] firstRows = new int[loaders.Count];
            for (int i = 0; i < loaders.Count; i++)
            {
                querySpaces.UnionWith(loaders[i].QuerySpaces);
                resultTypesList.Add(loaders[i].ResultTypes);
                firstRows[i] = parameters[i].RowSelection.FirstRow;
                maxRows[i]   = parameters[i].RowSelection.MaxRows;
            }

            MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);
            QueryParameters combinedParameters      = CreateCombinedQueryParameters();
            QueryKey        key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys, null)
                                  .SetFirstRows(firstRows)
                                  .SetMaxRows(maxRows);

            IList result =
                assembler.GetResultFromQueryCache(session,
                                                  combinedParameters,
                                                  querySpaces,
                                                  queryCache,
                                                  key);

            if (result == null)
            {
                log.Debug("Cache miss for multi criteria query");
                IList list = DoList();
                queryCache.Put(key, new ICacheAssembler[] { assembler }, new object[] { list }, combinedParameters.NaturalKeyLookup, session);
                result = list;
            }

            return(GetResultList(result));
        }
        public IQueryCache GetQueryCache(string cacheRegion)
        {
            if (cacheRegion == null)
            {
                return(QueryCache);
            }
            if (!settings.IsQueryCacheEnabled)
            {
                return(null);
            }

            return(queryCaches.GetOrAdd(
                       cacheRegion,
                       cr =>
            {
                IQueryCache currentQueryCache = settings.QueryCacheFactory.GetQueryCache(cacheRegion, updateTimestampsCache, settings, properties);
                allCacheRegions[currentQueryCache.RegionName] = currentQueryCache.Cache;
                return currentQueryCache;
            }));
        }
示例#21
0
        public IQueryCache GetQueryCache(string cacheRegion)
        {
            if (cacheRegion == null)
            {
                return(QueryCache);
            }

            IQueryCache currentQueryCache = ( IQueryCache )queryCaches[cacheRegion];

            if (currentQueryCache == null)
            {
                currentQueryCache = settings.QueryCacheFactory.GetQueryCache(
                    cacheRegion,
                    settings.CacheProvider,
                    updateTimestampsCache,
                    properties
                    );
                queryCaches[cacheRegion] = currentQueryCache;
            }
            return(currentQueryCache);
        }
示例#22
0
        protected Layer(String layerName,
                        IStyle style,
                        IProvider dataSource,
                        IGeometryFactory geometryFactory,
                        ILayer parent)
            : base(parent)
        {
            if (layerName == null)
            {
                throw new ArgumentNullException("layerName");
            }
            if (dataSource == null)
            {
                throw new ArgumentNullException("dataSource");
            }

            _layerName = layerName;
            _parent    = parent;

            if (parent != null)
            {
                _asyncQuery = parent.AsyncQuery;
                _geoFactory = geometryFactory;
                dataSource  = parent.DataSource as IAsyncProvider ??
                              CreateAsyncProvider(parent.DataSource);
                CoordinateTransformation = parent.CoordinateTransformation;
                _loadedRegion            = parent.LoadedRegion;
                style = parent.Style;
            }

            IAsyncProvider asyncProvider = dataSource as IAsyncProvider;

            _dataSource = asyncProvider ?? CreateAsyncProvider(dataSource);

            _style = style;
            // TODO: inject the cache type or instance...
            _cache = new NullQueryCache();
        }
示例#23
0
        /// <summary>
        /// Put query results in the cache.
        /// </summary>
        /// <param name="queryCache">The cache.</param>
        /// <param name="key">The query key.</param>
        /// <param name="queryParameters">The query parameters.</param>
        /// <param name="returnTypes">The query result row types.</param>
        /// <param name="result">The query result.</param>
        /// <param name="session">The session for which the query was executed.</param>
        /// <param name="cancellationToken">A cancellation token that can be used to cancel the work</param>
        /// <returns><see langword="true" /> if the result has been cached, <see langword="false" />
        /// otherwise.</returns>
        public static Task <bool> PutAsync(
            this IQueryCache queryCache,
            QueryKey key,
            QueryParameters queryParameters,
            ICacheAssembler[] returnTypes,
            IList result,
            ISessionImplementor session, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled <bool>(cancellationToken));
            }
            try
            {
                if (queryCache is IBatchableQueryCache batchableQueryCache)
                {
                    return(batchableQueryCache.PutAsync(
                               key, queryParameters,
                               returnTypes,
                               result, session, cancellationToken));
                }

#pragma warning disable 618
                return(queryCache.PutAsync(
#pragma warning restore 618
                           key,
                           returnTypes,
                           result,
                           queryParameters.NaturalKeyLookup,
                           session, cancellationToken));
            }
            catch (Exception ex)
            {
                return(Task.FromException <bool>(ex));
            }
        }
示例#24
0
 public AddAsyncQueryExecutor(IQueryCache <AddQuery, AsyncLazy <int> > cache, TimeSpan delayTime) : base(cache)
 {
     m_delayTime = delayTime;
 }
		public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings)
		{
			log.Info("building session factory");

			this.properties = cfg.Properties;
			this.interceptor = cfg.Interceptor;
			this.settings = settings;
			this.sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);

			if (log.IsDebugEnabled)
			{
				log.Debug("instantiating session factory with properties: "
				          + CollectionPrinter.ToString(properties));
			}

			settings.CacheProvider.Start(properties);

			// Generators:
			identifierGenerators = new Hashtable();
			foreach (PersistentClass model in cfg.ClassMappings)
			{
				if (!model.IsInherited)
				{
					// TODO H3:
					IIdentifierGenerator generator = model.Identifier.CreateIdentifierGenerator(
						settings.Dialect);
					//					IIdentifierGenerator generator = model.Identifier.CreateIdentifierGenerator(
					//						settings.Dialect,
					//						settings.DefaultCatalogName,
					//						settings.DefaultSchemaName,
					//						(RootClass) model
					//						);
					identifierGenerators[model.MappedClass] = generator;
				}
			}


			// Persisters:

			IDictionary caches = new Hashtable();
			classPersisters = new Hashtable();
			classPersistersByName = new Hashtable();
			IDictionary classMeta = new Hashtable();

			foreach (PersistentClass model in cfg.ClassMappings)
			{
				string cacheRegion = model.RootClazz.CacheRegionName;
				ICacheConcurrencyStrategy cache = (ICacheConcurrencyStrategy) caches[cacheRegion];
				if (cache == null)
				{
					cache =
						CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
					if (cache != null)
					{
						caches.Add(cacheRegion, cache);
						allCacheRegions.Add(cache.RegionName, cache.Cache);
					}
				}
				IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
				classPersisters[model.MappedClass] = cp;

				// Adds the "Namespace.ClassName" (FullClassname) as a lookup to get to the Persiter.
				// Most of the internals of NHibernate use this method to get to the Persister since
				// Model.Name is used in so many places.  It would be nice to fix it up to be Model.TypeName
				// instead of just FullClassname
				classPersistersByName[model.Name] = cp;

				// Add in the AssemblyQualifiedName (includes version) as a lookup to get to the Persister.  
				// In HQL the Imports are used to get from the Classname to the Persister.  The
				// Imports provide the ability to jump from the Classname to the AssemblyQualifiedName.
				classPersistersByName[model.MappedClass.AssemblyQualifiedName] = cp;

				classMeta[model.MappedClass] = cp.ClassMetadata;
			}
			classMetadata = new Hashtable(classMeta);

			collectionPersisters = new Hashtable();
			foreach (Mapping.Collection map in cfg.CollectionMappings)
			{
				ICacheConcurrencyStrategy cache =
					CacheFactory.CreateCache(map.CacheConcurrencyStrategy, map.CacheRegionName, map.Owner.IsMutable, settings,
					                         properties);
				if (cache != null)
					allCacheRegions[cache.RegionName] = cache.Cache;

				collectionPersisters[map.Role] = PersisterFactory
					.CreateCollectionPersister(map, cache, this)
					.CollectionMetadata;
			}
			collectionMetadata = new Hashtable(collectionPersisters);

			//TODO:
			// For databinding:
			//templates = XMLDatabinder.GetOutputStyleSheetTemplates( properties );


			// serialization info
			name = settings.SessionFactoryName;
			try
			{
				uuid = (string) UuidGenerator.Generate(null, null);
			}
			catch (Exception)
			{
				throw new AssertionFailure("could not generate UUID");
			}

			SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

			// Named queries:
			// TODO: precompile and cache named queries

			namedQueries = new Hashtable(cfg.NamedQueries);
			namedSqlQueries = new Hashtable(cfg.NamedSQLQueries);
			sqlResultSetMappings = new Hashtable(cfg.SqlResultSetMappings);
			filters = new Hashtable(cfg.FilterDefinitions);

			imports = new Hashtable(cfg.Imports);

			// after *all* persisters and named queries are registered
			foreach (IEntityPersister persister in classPersisters.Values)
			{
				persister.PostInstantiate();
			}

			foreach (ICollectionPersister persister in collectionPersisters.Values)
			{
				persister.PostInstantiate();
			}

			log.Debug("Instantiated session factory");

			if (settings.IsAutoCreateSchema)
			{
				new SchemaExport(cfg).Create(false, true);
			}

			/*
			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate( cfg ).Execute( false, true );
			}
			*/

			if (settings.IsAutoDropSchema)
			{
				schemaExport = new SchemaExport(cfg);
			}

			// Obtaining TransactionManager - not ported from H2.1

			currentSessionContext = BuildCurrentSessionContext();

			if (settings.IsQueryCacheEnabled)
			{
				updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
				queryCache = settings.QueryCacheFactory
					.GetQueryCache(null, updateTimestampsCache, settings, properties);
				queryCaches = Hashtable.Synchronized(new Hashtable());
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}
		}
示例#26
0
 public RequestHandler(IRepository repository, IQueryCache cache)
 {
     _repository = repository;
     _cache      = cache;
 }
示例#27
0
 public QueryRunner(IDependencyResolver resolver, IQueryCache queryCache)
 {
     _resolver   = resolver;
     _queryCache = queryCache;
 }
 public async Task <IList> GetResultFromQueryCacheAsync(ISessionImplementor session, QueryParameters queryParameters,
                                                        ISet <string> querySpaces, IQueryCache queryCache, QueryKey key, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     if (!queryParameters.ForceCacheRefresh)
     {
         IList list =
             await(queryCache.GetAsync(key, new ICacheAssembler[] { this }, queryParameters.NaturalKeyLookup, querySpaces, session, cancellationToken)).ConfigureAwait(false);
         //we had to wrap the query results in another list in order to save all
         //the queries in the same bucket, now we need to do it the other way around.
         if (list != null)
         {
             list = (IList)list[0];
         }
         return(list);
     }
     return(null);
 }
 /// <summary>
 /// Constructs an AggregateQueryClientSideExecutor
 /// </summary>
 /// <param name="childAsyncQueryExecutor">query executor to execute child queries</param>
 /// <param name="queryCache">The query cache to be used</param>
 public AggregateAsyncQueryClientSideExecutor(AsyncQueryExecutor <TQuery, TResult> childAsyncQueryExecutor, IQueryCache <AggregateQuery, AsyncLazy <List <TResult> > > queryCache)
     : base(queryCache)
 {
     _mChildAsyncQueryExecutor = childAsyncQueryExecutor;
 }
示例#30
0
		private IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
											  ISet<string> querySpaces, IType[] resultTypes, IQueryCache queryCache,
											  QueryKey key)
		{
			IList result = null;

			if ((!queryParameters.ForceCacheRefresh) && (session.CacheMode & CacheMode.Get) == CacheMode.Get)
			{
				IPersistenceContext persistenceContext = session.PersistenceContext;

				bool defaultReadOnlyOrig = persistenceContext.DefaultReadOnly;

				if (queryParameters.IsReadOnlyInitialized)
					persistenceContext.DefaultReadOnly = queryParameters.ReadOnly;
				else
					queryParameters.ReadOnly = persistenceContext.DefaultReadOnly;

				try
				{
					result = queryCache.Get(key, resultTypes, queryParameters.NaturalKeyLookup, querySpaces, session);
					if (_factory.Statistics.IsStatisticsEnabled)
					{
						if (result == null)
						{
							_factory.StatisticsImplementor.QueryCacheMiss(QueryIdentifier, queryCache.RegionName);
						}
						else
						{
							_factory.StatisticsImplementor.QueryCacheHit(QueryIdentifier, queryCache.RegionName);
						}
					}
				}
				finally
				{
					persistenceContext.DefaultReadOnly = defaultReadOnlyOrig;
				}
			}
			return result;
		}
示例#31
0
 protected WebApiQueryExecutorBase(WebApiClient webApiClient, IQueryCache <TQuery, AsyncLazy <TResult> > queryCache, string apiPath) : base(queryCache)
 {
     m_webApiClient = webApiClient;
     m_apiPath      = apiPath;
 }
示例#32
0
 /// <summary>
 /// Protected constructor of the query executor
 /// </summary>
 /// <param name="queryCache"></param>
 protected SyncQueryExecutor(IQueryCache <TQuery, Lazy <TResult> > queryCache)
 {
     m_queryTaskCache = queryCache;
 }
示例#33
0
		private IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
		                                      ISet<string> querySpaces, IType[] resultTypes, IQueryCache queryCache,
		                                      QueryKey key)
		{
			IList result = null;
			if ((!queryParameters.ForceCacheRefresh) && (session.CacheMode & CacheMode.Get) == CacheMode.Get)
			{
				result = queryCache.Get(key, resultTypes, queryParameters.NaturalKeyLookup, querySpaces, session);
				if (factory.Statistics.IsStatisticsEnabled)
				{
					if (result == null)
					{
						factory.StatisticsImplementor.QueryCacheMiss(QueryIdentifier, queryCache.RegionName);
					}
					else
					{
						factory.StatisticsImplementor.QueryCacheHit(QueryIdentifier, queryCache.RegionName);
					}
				}
			}
			return result;
		}
示例#34
0
		public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
		{
			Init();
			log.Info("building session factory");

			properties = new Dictionary<string, string>(cfg.Properties);
			interceptor = cfg.Interceptor;
			this.settings = settings;
			sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
			eventListeners = listeners;
			filters = new Dictionary<string, FilterDefinition>(cfg.FilterDefinitions);
			if (log.IsDebugEnabled)
			{
				log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
			}

			if (log.IsDebugEnabled)
			{
				log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
			}

			try
			{
				if (settings.IsKeywordsImportEnabled)
				{
					SchemaMetadataUpdater.Update(this);
				}
				if (settings.IsAutoQuoteEnabled)
				{
					SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
				}
			}
			catch (NotSupportedException)
			{
				// Ignore if the Dialect does not provide DataBaseSchema 
			}

			#region Caches
			settings.CacheProvider.Start(properties);
			#endregion

			#region Generators
			identifierGenerators = new Dictionary<string, IIdentifierGenerator>();
			foreach (PersistentClass model in cfg.ClassMappings)
			{
				if (!model.IsInherited)
				{
					IIdentifierGenerator generator =
						model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
						                                           settings.DefaultSchemaName, (RootClass) model);

					identifierGenerators[model.EntityName] = generator;
				}
			}
			#endregion

			#region Persisters

			Dictionary<string, ICacheConcurrencyStrategy> caches = new Dictionary<string, ICacheConcurrencyStrategy>();
			entityPersisters = new Dictionary<string, IEntityPersister>();
			implementorToEntityName = new Dictionary<System.Type, string>();

			Dictionary<string, IClassMetadata> classMeta = new Dictionary<string, IClassMetadata>();

			foreach (PersistentClass model in cfg.ClassMappings)
			{
				model.PrepareTemporaryTables(mapping, settings.Dialect);
				string cacheRegion = model.RootClazz.CacheRegionName;
				ICacheConcurrencyStrategy cache;
				if (!caches.TryGetValue(cacheRegion, out cache))
				{
					cache =
						CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
					if (cache != null)
					{
						caches.Add(cacheRegion, cache);
						allCacheRegions.Add(cache.RegionName, cache.Cache);
					}
				}
				IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
				entityPersisters[model.EntityName] = cp;
				classMeta[model.EntityName] = cp.ClassMetadata;

				if (model.HasPocoRepresentation)
				{
					implementorToEntityName[model.MappedClass] = model.EntityName;
				}
			}
			classMetadata = new UnmodifiableDictionary<string, IClassMetadata>(classMeta);

			Dictionary<string, ISet<string>> tmpEntityToCollectionRoleMap = new Dictionary<string, ISet<string>>();
			collectionPersisters = new Dictionary<string, ICollectionPersister>();
			foreach (Mapping.Collection model in cfg.CollectionMappings)
			{
				ICacheConcurrencyStrategy cache =
					CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
					                         properties);
				if (cache != null)
				{
					allCacheRegions[cache.RegionName] = cache.Cache;
				}
				ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
				collectionPersisters[model.Role] = persister;
				IType indexType = persister.IndexType;
				if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
				{
					string entityName = ((IAssociationType) indexType).GetAssociatedEntityName(this);
					ISet<string> roles;
					if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
					{
						roles = new HashedSet<string>();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
				IType elementType = persister.ElementType;
				if (elementType.IsAssociationType && !elementType.IsAnyType)
				{
					string entityName = ((IAssociationType) elementType).GetAssociatedEntityName(this);
					ISet<string> roles;
					if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
					{
						roles = new HashedSet<string>();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
			}
			Dictionary<string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary<string, ICollectionMetadata>(collectionPersisters.Count);
			foreach (KeyValuePair<string, ICollectionPersister> collectionPersister in collectionPersisters)
			{
				tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
			}
			collectionMetadata = new UnmodifiableDictionary<string, ICollectionMetadata>(tmpcollectionMetadata);
			collectionRolesByEntityParticipant = new UnmodifiableDictionary<string, ISet<string>>(tmpEntityToCollectionRoleMap);
			#endregion

			#region Named Queries
			namedQueries = new Dictionary<string, NamedQueryDefinition>(cfg.NamedQueries);
			namedSqlQueries = new Dictionary<string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
			sqlResultSetMappings = new Dictionary<string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
			#endregion

			imports = new Dictionary<string, string>(cfg.Imports);

			#region after *all* persisters and named queries are registered
			foreach (IEntityPersister persister in entityPersisters.Values)
			{
				persister.PostInstantiate();
			}
			foreach (ICollectionPersister persister in collectionPersisters.Values)
			{
				persister.PostInstantiate();
			}
			#endregion

			#region Serialization info

			name = settings.SessionFactoryName;
			try
			{
				uuid = (string) UuidGenerator.Generate(null, null);
			}
			catch (Exception)
			{
				throw new AssertionFailure("Could not generate UUID");
			}

			SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

			#endregion

			log.Debug("Instantiated session factory");

			#region Schema management
			if (settings.IsAutoCreateSchema)
			{
				new SchemaExport(cfg).Create(false, true);
			}

			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate(cfg).Execute(false, true);
			}
			if (settings.IsAutoValidateSchema)
			{
				 new SchemaValidator(cfg, settings).Validate();
			}
			if (settings.IsAutoDropSchema)
			{
				schemaExport = new SchemaExport(cfg);
			}
			#endregion

			#region Obtaining TransactionManager
			// not ported yet
			#endregion

			currentSessionContext = BuildCurrentSessionContext();

			if (settings.IsQueryCacheEnabled)
			{
				updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
				queryCache = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
				queryCaches = new ThreadSafeDictionary<string, IQueryCache>(new Dictionary<string, IQueryCache>());
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}

			#region Checking for named queries
			if (settings.IsNamedQueryStartupCheckingEnabled)
			{
				IDictionary<string, HibernateException> errors = CheckNamedQueries();
				if (errors.Count > 0)
				{
					StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
					foreach (KeyValuePair<string, HibernateException> pair in errors)
					{
						failingQueries.Append('{').Append(pair.Key).Append('}');
						log.Error("Error in named query: " + pair.Key, pair.Value);
					}
					throw new HibernateException(failingQueries.ToString());
				}
			}
			#endregion

			Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

			// EntityNotFoundDelegate
			IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
			if (enfd == null)
			{
				enfd = new DefaultEntityNotFoundDelegate();
			}
			entityNotFoundDelegate = enfd;
		}
示例#35
0
		public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
		{
			Init();
			log.Info("building session factory");

			properties = cfg.Properties;
			interceptor = cfg.Interceptor;
			this.settings = settings;
			sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
			eventListeners = listeners;

			if (log.IsDebugEnabled)
			{
				log.Debug("instantiating session factory with properties: "
				          + CollectionPrinter.ToString(properties));
			}

			settings.CacheProvider.Start(properties);

			// Generators:
			identifierGenerators = new Hashtable();
			foreach (PersistentClass model in cfg.ClassMappings)
			{
				if (!model.IsInherited)
				{
					IIdentifierGenerator generator =
						model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
						                                           settings.DefaultSchemaName, (RootClass) model);

					identifierGenerators[model.MappedClass] = generator;
				}
			}


			// Persisters:

			IDictionary caches = new Hashtable();
			classPersisters = new Hashtable();
			classPersistersByName = new Hashtable();
			IDictionary classMeta = new Hashtable();

			foreach (PersistentClass model in cfg.ClassMappings)
			{
				string cacheRegion = model.RootClazz.CacheRegionName;
				ICacheConcurrencyStrategy cache = (ICacheConcurrencyStrategy) caches[cacheRegion];
				if (cache == null)
				{
					cache =
						CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
					if (cache != null)
					{
						caches.Add(cacheRegion, cache);
						allCacheRegions.Add(cache.RegionName, cache.Cache);
					}
				}
				IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
				classPersisters[model.MappedClass] = cp;

				// Adds the "Namespace.ClassName" (FullClassname) as a lookup to get to the Persiter.
				// Most of the internals of NHibernate use this method to get to the Persister since
				// Model.Name is used in so many places.  It would be nice to fix it up to be Model.TypeName
				// instead of just FullClassname
				classPersistersByName[model.EntityName] = cp;

				// Add in the AssemblyQualifiedName (includes version) as a lookup to get to the Persister.  
				// In HQL the Imports are used to get from the Classname to the Persister.  The
				// Imports provide the ability to jump from the Classname to the AssemblyQualifiedName.
				classPersistersByName[model.MappedClass.AssemblyQualifiedName] = cp;

				classMeta[model.MappedClass] = cp.ClassMetadata;
			}
			classMetadata = new Hashtable(classMeta);
			IDictionary tmpEntityToCollectionRoleMap= new Hashtable();
			collectionPersisters = new Hashtable();
			foreach (Mapping.Collection map in cfg.CollectionMappings)
			{
				ICacheConcurrencyStrategy cache =
					CacheFactory.CreateCache(map.CacheConcurrencyStrategy, map.CacheRegionName, map.Owner.IsMutable, settings,
					                         properties);
				if (cache != null)
					allCacheRegions[cache.RegionName] = cache.Cache;

				collectionPersisters[map.Role] =
					PersisterFactory.CreateCollectionPersister(cfg, map, cache, this).CollectionMetadata;
				ICollectionPersister persister = collectionPersisters[map.Role] as ICollectionPersister;
				IType indexType = persister.IndexType;
				if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
				{
					string entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
					ISet roles = tmpEntityToCollectionRoleMap[entityName] as ISet;
					if (roles == null)
					{
						roles = new HashedSet();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
				IType elementType = persister.ElementType;
				if (elementType.IsAssociationType && !elementType.IsAnyType)
				{
					string entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
					ISet roles = tmpEntityToCollectionRoleMap[entityName] as ISet;
					if (roles == null)
					{
						roles = new HashedSet();
						tmpEntityToCollectionRoleMap[entityName] = roles;
					}
					roles.Add(persister.Role);
				}
			}
			collectionMetadata = new Hashtable(collectionPersisters);
			collectionRolesByEntityParticipant = new Hashtable(tmpEntityToCollectionRoleMap);
			//TODO:
			// For databinding:
			//templates = XMLDatabinder.GetOutputStyleSheetTemplates( properties );


			// serialization info
			name = settings.SessionFactoryName;
			try
			{
				uuid = (string) UuidGenerator.Generate(null, null);
			}
			catch (Exception)
			{
				throw new AssertionFailure("could not generate UUID");
			}

			SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

			// Named queries:
			// TODO: precompile and cache named queries

			namedQueries = new Dictionary<string, NamedQueryDefinition>(cfg.NamedQueries);
			namedSqlQueries = new Dictionary<string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
			sqlResultSetMappings = new Dictionary<string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
			filters = new Dictionary<string, FilterDefinition>(cfg.FilterDefinitions);

			imports = new Dictionary<string, string>(cfg.Imports);

			// after *all* persisters and named queries are registered
			foreach (IEntityPersister persister in classPersisters.Values)
			{
				persister.PostInstantiate();
			}

			foreach (ICollectionPersister persister in collectionPersisters.Values)
			{
				persister.PostInstantiate();
			}

			log.Debug("Instantiated session factory");

			if (settings.IsAutoCreateSchema)
			{
				new SchemaExport(cfg).Create(false, true);
			}

			/*
			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate( cfg ).Execute( false, true );
			}
			*/

			if (settings.IsAutoDropSchema)
			{
				schemaExport = new SchemaExport(cfg);
			}

			// Obtaining TransactionManager - not ported from H2.1

			currentSessionContext = BuildCurrentSessionContext();

			if (settings.IsQueryCacheEnabled)
			{
				updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
				queryCache = settings.QueryCacheFactory
					.GetQueryCache(null, updateTimestampsCache, settings, properties);
				queryCaches = Hashtable.Synchronized(new Hashtable());
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}

			//checking for named queries
			if (settings.IsNamedQueryStartupCheckingEnabled)
			{
				IDictionary<string, HibernateException> errors = CheckNamedQueries();
				if (errors.Count > 0)
				{
					StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
					foreach (KeyValuePair<string, HibernateException> pair in errors)
					{
						failingQueries.Append('{').Append(pair.Key).Append('}');
						log.Error("Error in named query: " + pair.Key, pair.Value);
					}
					throw new HibernateException(failingQueries.ToString());
				}
			}

			Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

			// EntityNotFoundDelegate
			IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
			if (enfd == null)
			{
				enfd = new DefaultEntityNotFoundDelegate();
			}
			entityNotFoundDelegate = enfd;
		}
示例#36
0
        public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
        {
            Init();
            log.Info("building session factory");

            properties          = new Dictionary <string, string>(cfg.Properties);
            interceptor         = cfg.Interceptor;
            this.settings       = settings;
            sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
            eventListeners      = listeners;
            filters             = new Dictionary <string, FilterDefinition>(cfg.FilterDefinitions);
            if (log.IsDebugEnabled)
            {
                log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
            }

            try
            {
                if (settings.IsKeywordsImportEnabled)
                {
                    SchemaMetadataUpdater.Update(this);
                }
                if (settings.IsAutoQuoteEnabled)
                {
                    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
                }
            }
            catch (NotSupportedException)
            {
                // Ignore if the Dialect does not provide DataBaseSchema
            }

            #region Caches
            settings.CacheProvider.Start(properties);
            #endregion

            #region Generators
            identifierGenerators = new Dictionary <string, IIdentifierGenerator>();
            foreach (PersistentClass model in cfg.ClassMappings)
            {
                if (!model.IsInherited)
                {
                    IIdentifierGenerator generator =
                        model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
                                                                   settings.DefaultSchemaName, (RootClass)model);

                    identifierGenerators[model.EntityName] = generator;
                }
            }
            #endregion

            #region Persisters

            Dictionary <string, ICacheConcurrencyStrategy> caches = new Dictionary <string, ICacheConcurrencyStrategy>();
            entityPersisters        = new Dictionary <string, IEntityPersister>();
            implementorToEntityName = new Dictionary <System.Type, string>();

            Dictionary <string, IClassMetadata> classMeta = new Dictionary <string, IClassMetadata>();

            foreach (PersistentClass model in cfg.ClassMappings)
            {
                model.PrepareTemporaryTables(mapping, settings.Dialect);
                string cacheRegion = model.RootClazz.CacheRegionName;
                ICacheConcurrencyStrategy cache;
                if (!caches.TryGetValue(cacheRegion, out cache))
                {
                    cache =
                        CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
                    if (cache != null)
                    {
                        caches.Add(cacheRegion, cache);
                        allCacheRegions.Add(cache.RegionName, cache.Cache);
                    }
                }
                IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
                entityPersisters[model.EntityName] = cp;
                classMeta[model.EntityName]        = cp.ClassMetadata;

                if (model.HasPocoRepresentation)
                {
                    implementorToEntityName[model.MappedClass] = model.EntityName;
                }
            }
            classMetadata = new UnmodifiableDictionary <string, IClassMetadata>(classMeta);

            Dictionary <string, ISet <string> > tmpEntityToCollectionRoleMap = new Dictionary <string, ISet <string> >();
            collectionPersisters = new Dictionary <string, ICollectionPersister>();
            foreach (Mapping.Collection model in cfg.CollectionMappings)
            {
                ICacheConcurrencyStrategy cache =
                    CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
                                             properties);
                if (cache != null)
                {
                    allCacheRegions[cache.RegionName] = cache.Cache;
                }
                ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
                collectionPersisters[model.Role] = persister;
                IType indexType = persister.IndexType;
                if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
                IType elementType = persister.ElementType;
                if (elementType.IsAssociationType && !elementType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
            }
            Dictionary <string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary <string, ICollectionMetadata>(collectionPersisters.Count);
            foreach (KeyValuePair <string, ICollectionPersister> collectionPersister in collectionPersisters)
            {
                tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
            }
            collectionMetadata = new UnmodifiableDictionary <string, ICollectionMetadata>(tmpcollectionMetadata);
            collectionRolesByEntityParticipant = new UnmodifiableDictionary <string, ISet <string> >(tmpEntityToCollectionRoleMap);
            #endregion

            #region Named Queries
            namedQueries         = new Dictionary <string, NamedQueryDefinition>(cfg.NamedQueries);
            namedSqlQueries      = new Dictionary <string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
            sqlResultSetMappings = new Dictionary <string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
            #endregion

            imports = new Dictionary <string, string>(cfg.Imports);

            #region after *all* persisters and named queries are registered
            foreach (IEntityPersister persister in entityPersisters.Values)
            {
                persister.PostInstantiate();
            }
            foreach (ICollectionPersister persister in collectionPersisters.Values)
            {
                persister.PostInstantiate();
            }
            #endregion

            #region Serialization info

            name = settings.SessionFactoryName;
            try
            {
                uuid = (string)UuidGenerator.Generate(null, null);
            }
            catch (Exception)
            {
                throw new AssertionFailure("Could not generate UUID");
            }

            SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

            #endregion

            log.Debug("Instantiated session factory");

            #region Schema management
            if (settings.IsAutoCreateSchema)
            {
                new SchemaExport(cfg).Create(false, true);
            }

            if (settings.IsAutoUpdateSchema)
            {
                new SchemaUpdate(cfg).Execute(false, true);
            }
            if (settings.IsAutoValidateSchema)
            {
                new SchemaValidator(cfg, settings).Validate();
            }
            if (settings.IsAutoDropSchema)
            {
                schemaExport = new SchemaExport(cfg);
            }
            #endregion

            #region Obtaining TransactionManager
            // not ported yet
            #endregion

            currentSessionContext = BuildCurrentSessionContext();

            if (settings.IsQueryCacheEnabled)
            {
                updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
                queryCache            = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
                queryCaches           = new ThreadSafeDictionary <string, IQueryCache>(new Dictionary <string, IQueryCache>());
            }
            else
            {
                updateTimestampsCache = null;
                queryCache            = null;
                queryCaches           = null;
            }

            #region Checking for named queries
            if (settings.IsNamedQueryStartupCheckingEnabled)
            {
                IDictionary <string, HibernateException> errors = CheckNamedQueries();
                if (errors.Count > 0)
                {
                    StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
                    foreach (KeyValuePair <string, HibernateException> pair in errors)
                    {
                        failingQueries.Append('{').Append(pair.Key).Append('}');
                        log.Error("Error in named query: " + pair.Key, pair.Value);
                    }
                    throw new HibernateException(failingQueries.ToString());
                }
            }
            #endregion

            Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

            // EntityNotFoundDelegate
            IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
            if (enfd == null)
            {
                enfd = new DefaultEntityNotFoundDelegate();
            }
            entityNotFoundDelegate = enfd;
        }
示例#37
0
		private static IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
		                                             ISet querySpaces, IType[] resultTypes, IQueryCache queryCache,
		                                             QueryKey key)
		{
			if (!queryParameters.ForceCacheRefresh)
			{
				return queryCache.Get(key, resultTypes, querySpaces, session);
			}
			return null;
		}
示例#38
0
		private void PutResultInQueryCache(ISessionImplementor session, QueryParameters queryParameters, IType[] resultTypes,
		                                   IQueryCache queryCache, QueryKey key, IList result)
		{
			if ((session.CacheMode & CacheMode.Put) == CacheMode.Put)
			{
				bool put = queryCache.Put(key, resultTypes, result, queryParameters.NaturalKeyLookup, session);
				if (put && factory.Statistics.IsStatisticsEnabled)
				{
					factory.StatisticsImplementor.QueryCachePut(QueryIdentifier, queryCache.RegionName);
				}
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="cfg"></param>
		/// <param name="settings"></param>
		public SessionFactoryImpl( Configuration cfg, Settings settings )
		{
			log.Info( "building session factory" );

			this.properties = cfg.Properties;
			this.interceptor = cfg.Interceptor;
			this.settings = settings;

			if( log.IsDebugEnabled )
			{
				log.Debug( "instantiating session factory with properties: "
					+ CollectionPrinter.ToString( properties ) );
			}

			// Persisters:

			classPersisters = new Hashtable();
			classPersistersByName = new Hashtable();
			IDictionary classMeta = new Hashtable();

			foreach( PersistentClass model in cfg.ClassMappings )
			{
				IClassPersister cp = PersisterFactory.CreateClassPersister( model, this );
				classPersisters[ model.MappedClass ] = cp;

				// Adds the "Namespace.ClassName" (FullClassname) as a lookup to get to the Persiter.
				// Most of the internals of NHibernate use this method to get to the Persister since
				// Model.Name is used in so many places.  It would be nice to fix it up to be Model.TypeName
				// instead of just FullClassname
				classPersistersByName[ model.Name ] = cp;

				// Add in the AssemblyQualifiedName (includes version) as a lookup to get to the Persister.  
				// In HQL the Imports are used to get from the Classname to the Persister.  The
				// Imports provide the ability to jump from the Classname to the AssemblyQualifiedName.
				classPersistersByName[ model.MappedClass.AssemblyQualifiedName ] = cp;

				classMeta[ model.MappedClass ] = cp.ClassMetadata;
			}
			classMetadata = new Hashtable( classMeta );

			collectionPersisters = new Hashtable();
			foreach( Mapping.Collection map in cfg.CollectionMappings )
			{
				collectionPersisters[ map.Role ] = PersisterFactory
					.CreateCollectionPersister( map, this )
					.CollectionMetadata;
			}
			collectionMetadata = new Hashtable( collectionPersisters );

			// after *all* persisters are registered
			foreach( IClassPersister persister in classPersisters.Values )
			{
				// TODO: H2.1 doesn't pass this to PostInstantiate
				persister.PostInstantiate( this );
			}

			//TODO:
			// For databinding:
			//templates = XMLDatabinder.GetOutputStyleSheetTemplates( properties );


			// serialization info
			name = settings.SessionFactoryName;
			try
			{
				uuid = ( string ) UuidGenerator.Generate( null, null );
			}
			catch( Exception )
			{
				throw new AssertionFailure( "could not generate UUID" );
			}

			SessionFactoryObjectFactory.AddInstance( uuid, name, this, properties );

			// Named queries:
			// TODO: precompile and cache named queries

			namedQueries = new Hashtable( cfg.NamedQueries );
			namedSqlQueries = new Hashtable( cfg.NamedSQLQueries.Count );
			foreach( DictionaryEntry de in cfg.NamedSQLQueries )
			{
				NamedSQLQuery nsq = ( NamedSQLQuery ) de.Value;
				namedSqlQueries[ de.Key ] = new InternalNamedSQLQuery( nsq.QueryString, nsq.ReturnAliases, nsq.ReturnClasses, nsq.SynchronizedTables );
			}

			imports = new Hashtable( cfg.Imports );

			log.Debug( "Instantiated session factory" );

			if( settings.IsAutoCreateSchema )
			{
				new SchemaExport( cfg ).Create( false, true );
			}

			/*
			if ( settings.IsAutoUpdateSchema )
			{
				new SchemaUpdate( cfg ).Execute( false, true );
			}
			*/

			if( settings.IsAutoDropSchema )
			{
				schemaExport = new SchemaExport( cfg );
			}

			// Obtaining TransactionManager - not ported from H2.1

			if( settings.IsQueryCacheEnabled )
			{
				updateTimestampsCache = new UpdateTimestampsCache( settings.CacheProvider, properties );
				queryCache = settings.QueryCacheFactory
					.GetQueryCache( null, settings.CacheProvider, updateTimestampsCache, properties );
				queryCaches = Hashtable.Synchronized( new Hashtable() );
			}
			else
			{
				updateTimestampsCache = null;
				queryCache = null;
				queryCaches = null;
			}
		}