private static bool TryGetEntityPersister(
            string currentEntityName,
            System.Type convertedType,
            ISessionFactoryImplementor sessionFactory,
            out IEntityPersister persister)
        {
            var currentEntityPersister = sessionFactory.TryGetEntityPersister(currentEntityName);

            if (currentEntityPersister == null)
            {
                // When dealing with a polymorphic query it is not important which entity name we pick
                // as they all need to have the same mapped types for members of the type that is queried.
                // If one of the entites has a different type mapped (e.g. enum mapped as string instead of numeric),
                // the query will fail to execute as currently the ParameterMetadata is bound to IQueryPlan and not to IQueryTranslator
                // (e.g. s.Query<IEntity>().Where(a => a.MyEnum == MyEnum.Option)).
                currentEntityName = sessionFactory.GetImplementors(currentEntityName).FirstOrDefault();
                if (currentEntityName == null)
                {
                    persister = null;
                    return(false);
                }

                currentEntityPersister = sessionFactory.GetEntityPersister(currentEntityName);
            }

            return(TryGetEntityPersister(currentEntityPersister, convertedType, sessionFactory, out persister));
        }
Example #2
0
        private void CreateCriteriaLoaders()
        {
            //a criteria can use more than a single query (polymorphic queries), need to have a
            //way to correlate a loader to a result index
            int criteriaIndex = 0;

            foreach (CriteriaImpl criteria in criteriaQueries)
            {
                string[] implementors = factory.GetImplementors(criteria.EntityOrClassName);
                int      size         = implementors.Length;

                ISet <string> spaces = new HashSet <string>();

                for (int i = 0; i < size; i++)
                {
                    CriteriaLoader loader = new CriteriaLoader(
                        session.GetOuterJoinLoadable(implementors[i]),
                        factory,
                        criteria,
                        implementors[i],
                        session.EnabledFilters
                        );
                    loaders.Add(loader);
                    loaderCriteriaMap.Add(criteriaIndex);
                    spaces.UnionWith(loader.QuerySpaces);
                }
                criteriaIndex += 1;
            }
        }
Example #3
0
        protected virtual IEntityPersister GetEntityPersister(ISessionFactoryImplementor factory, string entityName)
        {
            // Check for an exact match.
            IEntityPersister persister = factory.TryGetEntityPersister(entityName);

            if (persister != null)
            {
                return(persister);
            }

            // Couldn't find persister through exact name, try finding a single implementing class.
            string[] implementors = factory.GetImplementors(entityName);
            if (implementors.Length > 1)
            {
                var messageBuilder = new StringBuilder(512);
                messageBuilder.AppendLine(string.Format("Ambiguous persister for {0} implemented by more than one hierarchy: ",
                                                        entityName));
                Array.ForEach(implementors, s => messageBuilder.AppendLine(s));

                throw new HibernateException(messageBuilder.ToString());
            }
            if (implementors.Length == 0)
            {
                return(null);
            }
            return(factory.GetEntityPersister(implementors[0]));
        }
Example #4
0
        public static string GenerateSQL(ICriteria criteria)
        {
            var criteriaImpl = (CriteriaImpl)criteria;
            ISessionImplementor        session = criteriaImpl.Session;
            ISessionFactoryImplementor factory = session.Factory;

            var translator =
                new CriteriaQueryTranslator(
                    factory,
                    criteriaImpl,
                    criteriaImpl.EntityOrClassName,
                    CriteriaQueryTranslator.RootSqlAlias);

            String[] implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);

            var walker = new CriteriaJoinWalker(
                (IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]),
                translator,
                factory,
                criteriaImpl,
                criteriaImpl.EntityOrClassName,
                session.EnabledFilters);

            return(walker.SqlString.ToString());
        }
Example #5
0
        private void CreateCriteriaLoaders()
        {
            //a criteria can use more than a single query (polymorphic queries), need to have a
            //way to correlate a loader to a result index
            int criteriaIndex = 0;

            foreach (CriteriaImpl criteria in criteriaQueries)
            {
                string[] implementors = factory.GetImplementors(criteria.EntityOrClassName);
                int      size         = implementors.Length;

                CriteriaLoader[] tmpLoaders = new CriteriaLoader[size];
                ISet <string>    spaces     = new HashedSet <string>();

                for (int i = 0; i < size; i++)
                {
                    CriteriaLoader loader = new CriteriaLoader(
                        session.GetOuterJoinLoadable(implementors[i]),
                        factory,
                        criteria,
                        implementors[i],
                        session.EnabledFilters
                        );
                    tmpLoaders[i] = loader;
                    loaderToResultIndex[loader] = criteriaIndex;
                    spaces.AddAll(tmpLoaders[i].QuerySpaces);
                }
                loaders.AddRange(tmpLoaders);
                criteriaIndex += 1;
            }
        }
        private IEntityPersister ResolvePersister(string entityName)
        {
            // Check for an exact match.

            var persister = _sessionFactory.TryGetEntityPersister(entityName);

            if (persister != null)
            {
                return(persister);
            }

            // Couldn't find persister through exact name, try finding a single implementing class.

            string[] implementors = _sessionFactory.GetImplementors(entityName);

            if (implementors.Length > 1)
            {
                throw new ODataException(String.Format(ErrorMessages.ODataRequest_AmbiguousEntityName, entityName));
            }
            else if (implementors.Length == 0)
            {
                return(null);
            }
            else
            {
                return(_sessionFactory.GetEntityPersister(implementors[0]));
            }
        }
        public Dictionary <IASTNode, IASTNode[]> Process(IASTNode tree)
        {
            foreach (var querySource in new QuerySourceDetector(tree).LocateQuerySources())
            {
                var      className    = GetClassName(querySource);
                string[] implementors = _sfi.GetImplementors(className);
                AddImplementorsToMap(querySource, className, implementors);
            }

            return(_map);
        }
Example #8
0
        private void AddImplementorsToMap(IASTNode querySource, string className)
        {
            var implementors = _sfi.GetImplementors(className);

            if (implementors.Length == 1 && implementors[0] == className)
            {
                // No need to change things
                return;
            }

            _map.Add(querySource,
                     implementors.Select(implementor => MakeIdent(querySource, implementor)).ToArray());
        }
		public string[] ConcreteQueries(string query, ISessionFactoryImplementor factory)
		{
			// TODO H3.2 check if the QuerySplitter can do the work (this method is not present in H3.2)

			//scan the query string for class names appearing in the from clause and replace 
			//with all persistent implementors of the class/interface, returning multiple 
			//query strings (make sure we don't pick up a class in the select clause!) 

			//TODO: this is one of the ugliest and most fragile pieces of code in Hibernate...
			string[] tokens = StringHelper.Split(ParserHelper.Whitespace + "(),", query, true);
			if (tokens.Length == 0)
			{
				return new String[] {query};
			} // just especially for the trivial collection filter 

			var placeholders = new List<object>();
			var replacements = new List<object>();
			StringBuilder templateQuery = new StringBuilder(40);
			int count = 0;
			string last = null;
			int nextIndex = 0;
			string next = null;
			templateQuery.Append(tokens[0]);
			for (int i = 1; i < tokens.Length; i++)
			{
				//update last non-whitespace token, if necessary
				if (!ParserHelper.IsWhitespace(tokens[i - 1]))
				{
					last = tokens[i - 1].ToLowerInvariant();
				}

				string token = tokens[i];
				if (!ParserHelper.IsWhitespace(token) || last == null)
				{
					// scan for the next non-whitespace token
					if (nextIndex <= i)
					{
						for (nextIndex = i + 1; nextIndex < tokens.Length; nextIndex++)
						{
							next = tokens[nextIndex].ToLowerInvariant();
							if (!ParserHelper.IsWhitespace(next))
							{
								break;
							}
						}
					}

					//if ( Character.isUpperCase( token.charAt( token.lastIndexOf(".") + 1 ) ) ) {
					// added the checks for last!=null and next==null because an ISet can not contain 
					// a null key in .net - it is valid for a null key to be in a java.util.Set
					if (
						((last != null && beforeClassTokens.Contains(last)) && (next == null || !notAfterClassTokens.Contains(next))) ||
						PathExpressionParser.EntityClass.Equals(last))
					{
						System.Type clazz = Helper.GetImportedClass(token);
						if (clazz != null)
						{
							string[] implementors = factory.GetImplementors(clazz.FullName);
							string placeholder = "$clazz" + count++ + "$";

							if (implementors != null)
							{
								placeholders.Add(placeholder);
								replacements.Add(implementors);
							}
							token = placeholder; //Note this!!
						}
					}
				}
				templateQuery.Append(token);
			}
			string[] results =
				StringHelper.Multiply(templateQuery.ToString(), placeholders.GetEnumerator(), replacements.GetEnumerator());
			if (results.Length == 0)
			{
				log.Warn("no persistent classes found for query class: " + query);
			}
			return results;
		}
 public bool IsEntity(System.Type type)
 {
     return(_sessionFactory.GetImplementors(type.FullName).Any());
 }
Example #11
0
        /// <summary>
        /// Handle Hibernate "implicit" polymorphism, by translating the query string into
        /// several "concrete" queries against mapped classes.
        /// </summary>
        /// <param name="query"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        /// <exception cref="NHibernate.MappingException"/>
        public static string[] ConcreteQueries(string query, ISessionFactoryImplementor factory)
        {
            //scan the query string for class names appearing in the from clause and replace
            //with all persistent implementors of the class/interface, returning multiple
            //query strings (make sure we don't pick up a class in the select clause!)

            //TODO: this is one of the ugliest and most fragile pieces of code in Hibernate....

            SessionFactoryHelper helper = new SessionFactoryHelper(factory);

            string[] tokens = StringHelper.Split(StringHelper.WhiteSpace + "(),", query, true);
            if (tokens.Length == 0)
            {
                return(new String[] { query });              // just especially for the trivial collection filter
            }
            ArrayList     placeholders  = new ArrayList();
            ArrayList     replacements  = new ArrayList();
            StringBuilder templateQuery = new StringBuilder(40);
            int           count         = 0;
            string        last          = null;
            int           nextIndex     = 0;
            string        next          = null;

            templateQuery.Append(tokens[0]);
            bool isSelectClause = StringHelper.EqualsCaseInsensitive("select", tokens[0]);

            for (int i = 1; i < tokens.Length; i++)
            {
                //update last non-whitespace token, if necessary
                if (!ParserHelper.IsWhitespace(tokens[i - 1]))
                {
                    last = tokens[i - 1].ToLowerInvariant();
                }

                // select-range is terminated by declaration of "from"
                isSelectClause = !StringHelper.EqualsCaseInsensitive("from", tokens[i]);

                string token = tokens[i];
                if (!ParserHelper.IsWhitespace(token) || last == null)
                {
                    //scan for next non-whitespace token
                    if (nextIndex <= i)
                    {
                        for (nextIndex = i + 1; nextIndex < tokens.Length; nextIndex++)
                        {
                            next = tokens[nextIndex].ToLowerInvariant();
                            if (!ParserHelper.IsWhitespace(next))
                            {
                                break;
                            }
                        }
                    }

                    // TODO H3.2 Different behavior
                    // NHb: This block is not an exactly port from H3.2 but a port from previous implementation of QueryTranslator
                    if (((last != null && beforeClassTokens.Contains(last)) &&
                         (next == null || !notAfterClassTokens.Contains(next))) ||
                        PathExpressionParser.EntityClass.Equals(last))
                    {
                        System.Type clazz = helper.GetImportedClass(token);
                        if (clazz != null)
                        {
                            string[] implementors = factory.GetImplementors(clazz.FullName);
                            string   placeholder  = "$clazz" + count++ + "$";

                            if (implementors != null)
                            {
                                placeholders.Add(placeholder);
                                replacements.Add(implementors);
                            }
                            token = placeholder;                             //Note this!!
                        }
                    }
                }
                templateQuery.Append(token);
            }
            string[] results =
                StringHelper.Multiply(templateQuery.ToString(), placeholders.GetEnumerator(), replacements.GetEnumerator());
            if (results.Length == 0)
            {
                log.Warn("no persistent classes found for query class: " + query);
            }
            return(results);
        }
Example #12
0
		protected virtual IEntityPersister GetEntityPersister(ISessionFactoryImplementor factory, string entityName)
		{
			// Check for an exact match.
			IEntityPersister persister = factory.TryGetEntityPersister(entityName);
			if (persister != null)
			{
				return persister;
			}

			// Couldn't find persister through exact name, try finding a single implementing class.
			string[] implementors = factory.GetImplementors(entityName);
			if (implementors.Length > 1)
			{
				var messageBuilder = new StringBuilder(512);
				messageBuilder.AppendLine(string.Format("Ambiguous persister for {0} implemented by more than one hierarchy: ",
				                                        entityName));
				Array.ForEach(implementors, s=> messageBuilder.AppendLine(s));

				throw new HibernateException(messageBuilder.ToString());
			}
			if (implementors.Length == 0)
			{
				return null;
			}
			return factory.GetEntityPersister(implementors[0]);
		}
Example #13
0
		/// <summary>
		/// Handle Hibernate "implicit" polymorphism, by translating the query string into 
		/// several "concrete" queries against mapped classes.
		/// </summary>
		/// <param name="query"></param>
		/// <param name="factory"></param>
		/// <returns></returns>
		/// <exception cref="NHibernate.MappingException"/>
		public static string[] ConcreteQueries(string query, ISessionFactoryImplementor factory)
		{
			//scan the query string for class names appearing in the from clause and replace
			//with all persistent implementors of the class/interface, returning multiple
			//query strings (make sure we don't pick up a class in the select clause!)

			//TODO: this is one of the ugliest and most fragile pieces of code in Hibernate....

			SessionFactoryHelper helper = new SessionFactoryHelper(factory);

			string[] tokens = StringHelper.Split(StringHelper.WhiteSpace + "(),", query, true);
			if (tokens.Length == 0)
			{
				return new String[] {query}; // just especially for the trivial collection filter
			}
			ArrayList placeholders = new ArrayList();
			ArrayList replacements = new ArrayList();
			StringBuilder templateQuery = new StringBuilder(40);
			int count = 0;
			string last = null;
			int nextIndex = 0;
			string next = null;

			templateQuery.Append(tokens[0]);
			bool isSelectClause = StringHelper.EqualsCaseInsensitive("select", tokens[0]);

			for (int i = 1; i < tokens.Length; i++)
			{
				//update last non-whitespace token, if necessary
				if (!ParserHelper.IsWhitespace(tokens[i - 1]))
				{
					last = tokens[i - 1].ToLowerInvariant();
				}

				// select-range is terminated by declaration of "from"
				isSelectClause = !StringHelper.EqualsCaseInsensitive("from", tokens[i]);

				string token = tokens[i];
				if (!ParserHelper.IsWhitespace(token) || last == null)
				{
					//scan for next non-whitespace token
					if (nextIndex <= i)
					{
						for (nextIndex = i + 1; nextIndex < tokens.Length; nextIndex++)
						{
							next = tokens[nextIndex].ToLowerInvariant();
							if (!ParserHelper.IsWhitespace(next))
							{
								break;
							}
						}
					}

					// TODO H3.2 Different behavior
					// NHb: This block is not an exactly port from H3.2 but a port from previous implementation of QueryTranslator
					if (((last != null && beforeClassTokens.Contains(last)) &&
					     (next == null || !notAfterClassTokens.Contains(next))) ||
					    PathExpressionParser.EntityClass.Equals(last))
					{
						System.Type clazz = helper.GetImportedClass(token);
						if (clazz != null)
						{
							string[] implementors = factory.GetImplementors(clazz.FullName);
							string placeholder = "$clazz" + count++ + "$";

							if (implementors != null)
							{
								placeholders.Add(placeholder);
								replacements.Add(implementors);
							}
							token = placeholder; //Note this!!
						}
					}
				}
				templateQuery.Append(token);
			}
			string[] results =
				StringHelper.Multiply(templateQuery.ToString(), placeholders.GetEnumerator(), replacements.GetEnumerator());
			if (results.Length == 0)
			{
				log.Warn("no persistent classes found for query class: " + query);
			}
			return results;
		}