public static Lucene.Net.Search.Query FilterQueryByClasses(IESI.ISet<System.Type> classesAndSubclasses, Lucene.Net.Search.Query luceneQuery)
        {
            // A query filter is more practical than a manual class filtering post query (esp on scrollable resultsets)
            // it also probably minimise the memory footprint
            if (classesAndSubclasses == null)
            {
                return luceneQuery;
            }

            BooleanQuery classFilter = new BooleanQuery();

            // annihilate the scoring impact of DocumentBuilder.CLASS_FIELDNAME
            classFilter.SetBoost(0);
            foreach (System.Type clazz in classesAndSubclasses)
            {
                Term t = new Term(DocumentBuilder.CLASS_FIELDNAME, TypeHelper.LuceneTypeName(clazz));
                TermQuery termQuery = new TermQuery(t);
                classFilter.Add(termQuery, BooleanClause.Occur.SHOULD);
            }

            BooleanQuery filteredQuery = new BooleanQuery();
            filteredQuery.Add(luceneQuery, BooleanClause.Occur.MUST);
            filteredQuery.Add(classFilter, BooleanClause.Occur.MUST);
            return filteredQuery;
        }
		/// <summary>
		/// Create an action that will evict collection and entity regions based on queryspaces (table names).  
		/// </summary>
		public BulkOperationCleanupAction(ISessionImplementor session, IESI.ISet<string> querySpaces)
		{
			//from H3.2 TODO: cache the autodetected information and pass it in instead.
			this.session = session;

			IESI.ISet<string> tmpSpaces = new IESI.HashedSet<string>(querySpaces);
			ISessionFactoryImplementor factory = session.Factory;
			IDictionary<string, IClassMetadata> acmd = factory.GetAllClassMetadata();
			foreach (KeyValuePair<string, IClassMetadata> entry in acmd)
			{
				string entityName = entry.Key;
				IEntityPersister persister = factory.GetEntityPersister(entityName);
				string[] entitySpaces = persister.QuerySpaces;

				if (AffectedEntity(querySpaces, entitySpaces))
				{
					if (persister.HasCache)
					{
						affectedEntityNames.Add(persister.EntityName);
					}
					IESI.ISet<string> roles = session.Factory.GetCollectionRolesByEntityParticipant(persister.EntityName);
					if (roles != null)
					{
						affectedCollectionRoles.AddAll(roles);
					}
					for (int y = 0; y < entitySpaces.Length; y++)
					{
						tmpSpaces.Add(entitySpaces[y]);
					}
				}
			}
			spaces = new List<string>(tmpSpaces);
		}
        public bool IsUpToDate(IESI.ISet<string> spaces, long timestamp /* H2.1 has Long here */)
		{
			foreach (string space in spaces)
			{
				object lastUpdate = updateTimestamps.Get(space);
				if (lastUpdate == null)
				{
					//the last update timestamp was lost from the cache
					//(or there were no updates since startup!)

					//NOTE: commented out, since users found the "safe" behavior
					//      counter-intuitive when testing, and we couldn't deal
					//      with all the forum posts :-(
					//updateTimestamps.put( space, new Long( updateTimestamps.nextTimestamp() ) );
					//result = false; // safer

					//OR: put a timestamp there, to avoid subsequent expensive
					//    lookups to a distributed cache - this is no good, since
					//    it is non-threadsafe (could hammer effect of an actual
					//    invalidation), and because this is not the way our
					//    preferred distributed caches work (they work by
					//    replication)
					//updateTimestamps.put( space, new Long(Long.MIN_VALUE) );
				}
				else
				{
					if ((long) lastUpdate >= timestamp)
					{
						return false;
					}
				}
			}
			return true;
		}
		protected internal AbstractFieldInterceptor(ISessionImplementor session, IESI.ISet<string> uninitializedFields, IESI.ISet<string> unwrapProxyFieldNames, string entityName, System.Type mappedClass)
		{
			this.session = session;
			this.uninitializedFields = uninitializedFields;
			this.unwrapProxyFieldNames = unwrapProxyFieldNames ?? new IESI.HashedSet<string>();
			this.entityName = entityName;
			this.mappedClass = mappedClass;
		}
        public static IndexSearcher BuildSearcher(ISearchFactoryImplementor searchFactory,
                                             out IESI.ISet<System.Type> classesAndSubclasses,
                                             params System.Type[] classes)
        {
            IDictionary<System.Type, DocumentBuilder> builders = searchFactory.DocumentBuilders;
            IESI.ISet<IDirectoryProvider> directories = new IESI.HashedSet<IDirectoryProvider>();
            if (classes == null || classes.Length == 0)
            {
                // no class means all classes
                foreach (DocumentBuilder builder in builders.Values)
                {
                    foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards())
                    {
                        directories.Add(provider);
                    }
                }

                // Give them back an empty set
                classesAndSubclasses = null;
            }
            else
            {
                var involvedClasses = new IESI.HashedSet<System.Type>();
                involvedClasses.AddAll(classes);
                foreach (System.Type clazz in classes)
                {
                    DocumentBuilder builder;
                    builders.TryGetValue(clazz, out builder);
                    if (builder != null)
                    {
                        involvedClasses.AddAll(builder.MappedSubclasses);
                    }
                }

                foreach (System.Type clazz in involvedClasses)
                {
                    DocumentBuilder builder;
                    builders.TryGetValue(clazz, out builder);

                    // TODO should we rather choose a polymorphic path and allow non mapped entities
                    if (builder == null)
                    {
                        throw new HibernateException("Not a mapped entity: " + clazz);
                    }

                    foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards())
                    {
                        directories.Add(provider);
                    }
                }

                classesAndSubclasses = involvedClasses;
            }

            IDirectoryProvider[] directoryProviders = new List<IDirectoryProvider>(directories).ToArray();
            return new IndexSearcher(searchFactory.ReaderProvider.OpenReader(directoryProviders));
        }
		public SubselectFetch(string alias, ILoadable loadable, QueryParameters queryParameters,
                              IESI.ISet<EntityKey> resultingEntityKeys)
		{
			this.resultingEntityKeys = resultingEntityKeys;
			this.queryParameters = queryParameters;
			this.loadable = loadable;
			this.alias = alias;

			queryString = queryParameters.ProcessedSql.GetSubselectString();
		}
		public static IFieldInterceptor InjectFieldInterceptor(object entity, string entityName, 
			System.Type mappedClass,
			IESI.ISet<string> uninitializedFieldNames, 
			IESI.ISet<string> unwrapProxyFieldNames,
			ISessionImplementor session)
		{
			var fieldInterceptorAccessor = entity as IFieldInterceptorAccessor;
			if (fieldInterceptorAccessor != null)
			{
				var fieldInterceptorImpl = new DefaultFieldInterceptor(session, uninitializedFieldNames, unwrapProxyFieldNames, entityName, mappedClass);
				fieldInterceptorAccessor.FieldInterceptor = fieldInterceptorImpl;
				return fieldInterceptorImpl;
			}
			return null;
		}
		private bool AffectedEntity(IESI.ISet<string> querySpaces, string[] entitySpaces)
		{
			if (querySpaces == null || (querySpaces.Count == 0))
			{
				return true;
			}

			for (int i = 0; i < entitySpaces.Length; i++)
			{
				if (querySpaces.Contains(entitySpaces[i]))
				{
					return true;
				}
			}
			return false;
		}
		public IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
		                                     IESI.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 virtual void PostInstantiate(string entityName, System.Type persistentClass, IESI.ISet<System.Type> interfaces,
																				MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod,
																				IAbstractComponentType componentIdType)
		{
			EntityName = entityName;
			PersistentClass = persistentClass;
			Interfaces = new System.Type[interfaces.Count];

			if (interfaces.Count > 0)
			{
				interfaces.CopyTo(Interfaces, 0);
			}

			GetIdentifierMethod = getIdentifierMethod;
			SetIdentifierMethod = setIdentifierMethod;
			ComponentIdType = componentIdType;
		}
Esempio n. 11
0
		private IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters,
                                              IESI.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;
		}
Esempio n. 12
0
        private IList ListUsingQueryCache(ISessionImplementor session, QueryParameters queryParameters, IESI.ISet<string> querySpaces, IType[] resultTypes)
		{
			IQueryCache queryCache = _factory.GetQueryCache(queryParameters.CacheRegion);

			ISet filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);
			QueryKey key = new QueryKey(Factory, SqlString, queryParameters, filterKeys);

			IList result = GetResultFromQueryCache(session, queryParameters, querySpaces, resultTypes, queryCache, key);

			if (result == null)
			{
				result = DoList(session, queryParameters);
				PutResultInQueryCache(session, queryParameters, resultTypes, queryCache, key, result);
			}

			return GetResultList(result, queryParameters.ResultTransformer);
		}
Esempio n. 13
0
		/// <summary>
		/// Return the query results, using the query cache, called
		/// by subclasses that implement cacheable queries
		/// </summary>
		/// <param name="session"></param>
		/// <param name="queryParameters"></param>
		/// <param name="querySpaces"></param>
		/// <param name="resultTypes"></param>
		/// <returns></returns>
        protected IList List(ISessionImplementor session, QueryParameters queryParameters, IESI.ISet<string> querySpaces, IType[] resultTypes)
		{
			bool cacheable = _factory.Settings.IsQueryCacheEnabled && queryParameters.Cacheable;

			if (cacheable)
			{
				return ListUsingQueryCache(session, queryParameters, querySpaces, resultTypes);
			}
			return ListIgnoreQueryCache(session, queryParameters);
		}
		protected AbstractAuxiliaryDatabaseObject(IESI.HashedSet<string> dialectScopes)
		{
			this.dialectScopes = dialectScopes;
		}
Esempio n. 15
0
		/// <summary>
		/// Should we join this association?
		/// </summary>
		protected bool IsJoinable(JoinType joinType, IESI.ISet<AssociationKey> visitedAssociationKeys, string lhsTable,
			string[] lhsColumnNames, IAssociationType type, int depth)
		{
			if (joinType < JoinType.InnerJoin) return false;
			if (joinType == JoinType.InnerJoin) return true;

			int maxFetchDepth = Factory.Settings.MaximumFetchDepth;
			bool tooDeep = maxFetchDepth >= 0 && depth >= maxFetchDepth;

			return !tooDeep && !IsDuplicateAssociation(lhsTable, lhsColumnNames, type);
		}
		public DefaultFieldInterceptor(ISessionImplementor session, IESI.ISet<string> uninitializedFields, IESI.ISet<string> unwrapProxyFieldNames, string entityName, System.Type mappedClass)
			: base(session, uninitializedFields, unwrapProxyFieldNames, entityName, mappedClass)
		{
		}
        public void PostInitialize(IESI.ISet<System.Type> indexedClasses)
        {
            // this method does not requires synchronization
            Type plainClass = rootClassMapping.MappedClass;
            IESI.ISet<Type> tempMappedSubclasses = new IESI.HashedSet<System.Type>();

            // together with the caller this creates a o(2), but I think it's still faster than create the up hierarchy for each class
            foreach (Type currentClass in indexedClasses)
            {
                if (plainClass.IsAssignableFrom(currentClass))
                {
                    tempMappedSubclasses.Add(currentClass);
                }
            }

            mappedSubclasses = tempMappedSubclasses;
        }
Esempio n. 18
0
		private void CheckColumnDuplication(IESI.ISet<string> distinctColumns, IEnumerable<ISelectable> columns)
		{
			foreach (ISelectable s in columns)
			{
				if(!s.IsFormula)
				{
					Column col = (Column)s;
					if (!distinctColumns.Add(col.Name))
					{
						throw new MappingException(string.Format("Repeated column in mapping for collection: {0} column: {1}", Role, col.Name));
					}					
				}
			}
		}
        private void CollectAnalyzers(
            DocumentMapping @class, Analyzer parentAnalyzer, bool isRoot, string prefix, IESI.ISet<System.Type> processedClasses
        )
        {
            foreach (var bridge in @class.ClassBridges)
            {
                var bridgeAnalyzer = bridge.Analyzer ?? parentAnalyzer;
                if (bridgeAnalyzer == null)
                {
                    throw new NotSupportedException("Analyzer should not be undefined");
                }

                analyzer.AddScopedAnalyzer(prefix + bridge.Name, bridgeAnalyzer);
            }

            if (isRoot && @class.DocumentId != null)
            {
                idMapping = @class.DocumentId;
            }

            foreach (var field in @class.Fields)
            {
                CollectAnalyzer(field, parentAnalyzer, prefix);
            }

            foreach (var embedded in @class.Embedded)
            {
                CollectAnalyzers(
                    embedded.Class, parentAnalyzer, false, prefix + embedded.Prefix, processedClasses
                );
            }
        }
		public SimpleAuxiliaryDatabaseObject(String sqlCreateString, String sqlDropString, IESI.HashedSet<string> dialectScopes)
			: base(dialectScopes)
		{
			this.sqlCreateString = sqlCreateString;
			this.sqlDropString = sqlDropString;
		}
Esempio n. 21
0
		/// <summary> 
		/// Check whether the given tables/query-spaces are to be executed against
		/// given the currently queued actions. 
		/// </summary>
		/// <param name="tables">The table/query-spaces to check. </param>
		/// <returns> True if we contain pending actions against any of the given tables; false otherwise.</returns>
		public virtual bool AreTablesToBeUpdated(IESI.ISet<string> tables)
		{
			return 
				AreTablesToUpdated(updates, tables) 
				|| AreTablesToUpdated(insertions, tables) 
				|| AreTablesToUpdated(deletions, tables) 
				|| AreTablesToUpdated(collectionUpdates, tables) 
				|| AreTablesToUpdated(collectionCreations, tables) 
				|| AreTablesToUpdated(collectionRemovals, tables);
		}
		protected internal void CheckColumnDuplication(IESI.ISet<string> distinctColumns, IEnumerable<ISelectable> columns)
		{
			foreach (ISelectable columnOrFormula in columns)
			{
				if (!columnOrFormula.IsFormula)
				{
					Column col = (Column)columnOrFormula;
					if (!distinctColumns.Add(col.Name))
					{
						// TODO: Check for column duplication
						//throw new MappingException("Repeated column in mapping for entity: " + EntityName + " column: " + col.Name + 
						//  "(should be mapped with insert=\"false\" update=\"false\")");
					}
				}
			}
		}
		protected internal void CheckPropertyColumnDuplication(IESI.ISet<string> distinctColumns, IEnumerable<Property> properties)
		{
			foreach (Property prop in properties)
			{
				Component component = prop.Value as Component;
				if (component != null)
				{
					CheckPropertyColumnDuplication(distinctColumns, component.PropertyIterator);
				}
				else
				{
					if (prop.IsUpdateable || prop.IsInsertable)
						CheckColumnDuplication(distinctColumns, prop.ColumnIterator);
				}
			}

		}