public SqlString Render(IList args, ISessionFactoryImplementor factory)
		{
			// TODO: QueryException if args.Count<2 (not present in H3.2) 
			bool threeArgs = args.Count > 2;
			object pattern = args[0];
			object orgString = args[1];
			object start = threeArgs ? args[2] : null;

			SqlStringBuilder buf = new SqlStringBuilder();
			if (threeArgs)
			{
				buf.Add("(case ");
				RenderPositionInSubstring(buf, pattern, orgString, start);
				buf.Add(" when 0 then 0 else (");
				RenderPositionInSubstring(buf, pattern, orgString, start);
				buf.Add("+(")
				   .AddObject(start)
				   .Add("-1)) end)");
			}
			else
			{
				buf.Add("charindex(")
				.AddObject(pattern)
				.Add(", ")
				.AddObject(orgString)
				.Add(")");
			}
			return buf.ToSqlString();
		}
		protected IQueryableCollection GetQueryableCollection(string entityName, string actualPropertyName,
		                                                      ISessionFactoryImplementor factory)
		{
			IPropertyMapping ownerMapping = (IPropertyMapping) factory.GetEntityPersister(entityName);
			IType type = ownerMapping.ToType(actualPropertyName);
			if (!type.IsCollectionType)
			{
				throw new MappingException(
					"Property path [" + entityName + "." + actualPropertyName + "] does not reference a collection"
					);
			}

			string role = ((CollectionType) type).Role;
			try
			{
				return (IQueryableCollection) factory.GetCollectionPersister(role);
			}
			catch (InvalidCastException cce)
			{
				throw new QueryException("collection role is not queryable: " + role, cce);
			}
			catch (Exception e)
			{
				throw new QueryException("collection role not found: " + role, e);
			}
		}
Example #3
0
		public override bool IsEqual(object x, object y, EntityMode entityMode, ISessionFactoryImplementor factory)
		{
			IEntityPersister persister = factory.GetEntityPersister(associatedEntityName);
			if (!persister.CanExtractIdOutOfEntity)
			{
				return base.IsEqual(x, y, entityMode);
			}

			object xid;
			
			if (x.IsProxy())
			{
				INHibernateProxy proxy = x as INHibernateProxy; 
				xid = proxy.HibernateLazyInitializer.Identifier;
			}
			else
			{
				xid = persister.GetIdentifier(x, entityMode);
			}

			object yid;
			
			if (y.IsProxy())
			{
				INHibernateProxy proxy = y as INHibernateProxy; 
				yid = proxy.HibernateLazyInitializer.Identifier;
			}
			else
			{
				yid = persister.GetIdentifier(y, entityMode);
			}

			return persister.IdentifierType.IsEqual(xid, yid, entityMode, factory);
		}
Example #4
0
 /// <summary>
 /// Applies the template to passed in arguments.
 /// </summary>
 /// <param name="args">args function arguments</param>
 /// <param name="factory">generated SQL function call</param>
 /// <returns></returns>
 public SqlString Render(IList args, ISessionFactoryImplementor factory)
 {
     SqlStringBuilder buf = new SqlStringBuilder();
     foreach (TemplateChunk tc in chunks)
     {
         if (tc.ArgumentIndex != InvalidArgumentIndex)
         {
             int adjustedIndex = tc.ArgumentIndex - 1; // Arg indices are one-based
             object arg = adjustedIndex < args.Count ? args[adjustedIndex] : null;
             // TODO: if (arg == null) QueryException is better ?
             if (arg != null)
             {
                 if (arg is Parameter || arg is SqlString)
                 {
                     buf.AddObject(arg);
                 }
                 else
                 {
                     buf.Add(arg.ToString());
                 }
             }
         }
         else
         {
             buf.Add(tc.Text);
         }
     }
     return buf.ToSqlString();
 }
Example #5
0
        public CriteriaJoinWalker(IOuterJoinLoadable persister,CriteriaQueryTranslator translator,
            ISessionFactoryImplementor factory, CriteriaImpl criteria, string rootEntityName,
            IDictionary<string, IFilter> enabledFilters)
            : base(translator.RootSQLAlias, persister, factory, enabledFilters)
        {
            this.translator = translator;

            querySpaces = translator.GetQuerySpaces();

            if (translator.HasProjection)
            {
                resultTypes = translator.ProjectedTypes;

                InitProjection(
                    translator.GetSelect(enabledFilters),
                    translator.GetWhereCondition(enabledFilters),
                    translator.GetOrderBy(),
                    translator.GetGroupBy().ToString(),
                    LockMode.None
                    );
            }
            else
            {
                resultTypes = new IType[] {TypeFactory.ManyToOne(persister.EntityName)};

                InitAll(translator.GetWhereCondition(enabledFilters), translator.GetOrderBy(), LockMode.None);
            }

            userAliasList.Add(criteria.Alias); //root entity comes *last*
            userAliases = ArrayHelper.ToStringArray(userAliasList);
        }
		public OneToManyPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg, ISessionFactoryImplementor factory)
			: base(collection, cache, cfg, factory)
		{
			_cascadeDeleteEnabled = collection.Key.IsCascadeDeleteEnabled && factory.Dialect.SupportsCascadeDelete;
			_keyIsNullable = collection.Key.IsNullable;
			_keyIsUpdateable = collection.Key.IsUpdateable;
		}
Example #7
0
 public SqlGenerator(ISessionFactoryImplementor sfi, ITreeNodeStream input)
     : this(input)
 {
     parseErrorHandler = new ErrorCounter();
     sessionFactory = sfi;
     writer = new DefaultWriter(this);
 }
		public AbstractEntityJoinWalker(IOuterJoinLoadable persister, ISessionFactoryImplementor factory,
																		IDictionary<string, IFilter> enabledFilters)
			: base(factory, enabledFilters)
		{
			this.persister = persister;
			alias = GenerateRootAlias(persister.EntityName);
		}
		public AbstractEntityJoinWalker(string rootSqlAlias, IOuterJoinLoadable persister, ISessionFactoryImplementor factory,
																		IDictionary<string, IFilter> enabledFilters)
			: base(factory, enabledFilters)
		{
			this.persister = persister;
			alias = rootSqlAlias;
		}
		protected override bool AppliesTo(ISessionFactoryImplementor factory)
		{
			var driver = factory.ConnectionProvider.Driver;
			return driver is OracleDataClientDriver ||
			       driver is OracleLiteDataClientDriver ||
			       driver is OracleManagedDataClientDriver;
		}
		public SubselectOneToManyLoader(IQueryableCollection persister, SqlString subquery, ICollection<EntityKey> entityKeys,
		                                QueryParameters queryParameters,
		                                ISessionFactoryImplementor factory, IDictionary<string, IFilter> enabledFilters)
			: base(persister, BatchSizeForSubselectFetching, factory, enabledFilters)
		{
			keys = new object[entityKeys.Count];
			int i = 0;
			foreach (EntityKey entityKey in entityKeys)
			{
				keys[i++] = entityKey.Identifier;
			}

			// NH Different behavior: to deal with positionslParameter+NamedParameter+ParameterOfFilters
			namedParameters = new Dictionary<string, TypedValue>(queryParameters.NamedParameters);
			parametersSpecifications = queryParameters.ProcessedSqlParameters.ToList();
			var processedRowSelection = queryParameters.ProcessedRowSelection;
			SqlString finalSubquery = subquery;
			if (queryParameters.ProcessedRowSelection != null && !SubselectClauseExtractor.HasOrderBy(queryParameters.ProcessedSql))
			{
				// when the original query has an "ORDER BY" we can't re-apply the pagination.
				// This is a simplification, we should actually check which is the "ORDER BY" clause because when the "ORDER BY" is just for the PK we can re-apply "ORDER BY" and pagination.
				finalSubquery = GetSubSelectWithLimits(subquery, parametersSpecifications, processedRowSelection, namedParameters);
			}
			InitializeFromWalker(persister, finalSubquery, BatchSizeForSubselectFetching, enabledFilters, factory);

			types = queryParameters.PositionalParameterTypes;
			values = queryParameters.PositionalParameterValues;
		}
		public override SqlString ToSqlString( ISessionFactoryImplementor factory, System.Type persistentClass, string alias, IDictionary aliasClasses )
		{
			if( _criteria.Count == 0 )
			{
				return new SqlString( "1=1" );
			}

			//TODO: add default capacity
			SqlStringBuilder sqlBuilder = new SqlStringBuilder();

			sqlBuilder.Add( "(" );

			for( int i = 0; i < _criteria.Count - 1; i++ )
			{
				sqlBuilder.Add(
					( ( ICriterion ) _criteria[ i ] ).ToSqlString( factory, persistentClass, alias, aliasClasses ) );
				sqlBuilder.Add( Op );
			}

			sqlBuilder.Add(
				( ( ICriterion ) _criteria[ _criteria.Count - 1 ] ).ToSqlString( factory, persistentClass, alias, aliasClasses ) );


			sqlBuilder.Add( ")" );

			return sqlBuilder.ToSqlString();
		}
        public override SqlString RenderText(ISessionFactoryImplementor sessionFactory)
        {
            ProcessText();

			IType type = _expectedType ?? _heuristicType;
			return new SqlString(ResolveToLiteralString( type ));
		}
		/// <summary>
		/// Generate small message that can be used in traces and exception messages.
		/// </summary>
		/// <param name="persister">The <see cref="IEntityPersister" /> for the class in question.</param>
		/// <param name="id">The identifier of the object.</param>
		/// <param name="factory">The <see cref="ISessionFactory" />.</param>
		/// <returns>A descriptive <see cref="String" /> in the format of <c>[classname#id]</c></returns>
		public static string InfoString(IEntityPersister persister, object id, ISessionFactoryImplementor factory)
		{
			StringBuilder s = new StringBuilder();
			s.Append('[');
			if (persister == null)
			{
				s.Append("<null Class>");
			}
			else
			{
				s.Append(persister.EntityName);
			}
			s.Append('#');

			if (id == null)
			{
				s.Append("<null>");
			}
			else
			{
				s.Append(id);
			}
			s.Append(']');

			return s.ToString();
		}
		public OneToManyLoader(
			IQueryableCollection oneToManyPersister,
			ISessionFactoryImplementor session,
			IDictionary enabledFilters)
			: this(oneToManyPersister, 1, session, enabledFilters)
		{
		}
Example #16
0
		public NhLinqExpression(Expression expression, ISessionFactoryImplementor sessionFactory)
		{
			_expression = NhPartialEvaluatingExpressionTreeVisitor.EvaluateIndependentSubtrees(expression);

			// We want logging to be as close as possible to the original expression sent from the
			// application. But if we log before partial evaluation, the log won't include e.g.
			// subquery expressions if those are defined by the application in a variable referenced
			// from the main query.
			LinqLogging.LogExpression("Expression (partially evaluated)", _expression);

			_constantToParameterMap = ExpressionParameterVisitor.Visit(_expression, sessionFactory);

			ParameterValuesByName = _constantToParameterMap.Values.ToDictionary(p => p.Name,
																				p => System.Tuple.Create(p.Value, p.Type));

			Key = ExpressionKeyVisitor.Visit(_expression, _constantToParameterMap);

			Type = _expression.Type;

			// Note - re-linq handles return types via the GetOutputDataInfo method, and allows for SingleOrDefault here for the ChoiceResultOperator...
			ReturnType = NhLinqExpressionReturnType.Scalar;

			if (typeof(IQueryable).IsAssignableFrom(Type))
			{
				Type = Type.GetGenericArguments()[0];
				ReturnType = NhLinqExpressionReturnType.Sequence;
			}
		}
Example #17
0
		public SqlCommandImpl(SqlString query, ICollection<IParameterSpecification> specifications, QueryParameters queryParameters, ISessionFactoryImplementor factory)
		{
			this.query = query;
			this.specifications = specifications;
			this.queryParameters = queryParameters;
			this.factory = factory;
		}
		private static void AddImpliedFromToFromNode(IASTNode fromClause, string collectionRole, ISessionFactoryImplementor factory)
		{
			SessionFactoryHelperExtensions _sessionFactoryHelper = new SessionFactoryHelperExtensions(factory);
			IQueryableCollection persister = _sessionFactoryHelper.GetCollectionPersister(collectionRole);
			IType collectionElementType = persister.ElementType;
			if (!collectionElementType.IsEntityType)
			{
				throw new QueryException("collection of values in filter: this");
			}

			string collectionElementEntityName = persister.ElementPersister.EntityName;

			ITreeAdaptor adaptor = new ASTTreeAdaptor();

			IASTNode fromElement = (IASTNode)adaptor.Create(HqlParser.FILTER_ENTITY, collectionElementEntityName);
			IASTNode alias = (IASTNode)adaptor.Create(HqlParser.ALIAS, "this");

			fromClause.AddChild(fromElement);
			fromClause.AddChild(alias);

			// Show the modified AST.
			if (log.IsDebugEnabled)
			{
				log.Debug("AddImpliedFormToFromNode() : Filter - Added 'this' as a from element...");
			}
		}
		public SqlString Render(IList args, ISessionFactoryImplementor factory)
		{
			// TODO: QueryException if args.Count<2 (not present in H3.2) 
			bool threeArgs = args.Count > 2;
			object pattern = args[0];
			object orgString = args[1];
			object start = threeArgs ? args[2] : null;

			SqlStringBuilder buf = new SqlStringBuilder();
			buf.Add("charindex(")
				.AddObject(pattern)
				.Add(", ");
			if (threeArgs)
			{
				buf.Add("right(");
			}
			buf.AddObject(orgString);
			if (threeArgs)
			{
				buf.Add(", char_length(")
					.AddObject(orgString)
					.Add(")-(")
					.AddObject(start)
					.Add("-1))");
			}
			buf.Add(")");
			return buf.ToSqlString();
		}
Example #20
0
		public SqlString Render(IList args, ISessionFactoryImplementor factory)
		{
			//ANSI-SQL92 definition
			//<general set function> ::=
			//<set function type> <leftparen> [ <setquantifier> ] <value expression> <right paren>
			//<set function type> : := AVG | MAX | MIN | SUM | COUNT
			//<setquantifier> ::= DISTINCT | ALL

			if (args.Count < 1 || args.Count > 2)
			{
				throw new QueryException(string.Format("Aggregate {0}(): Not enough parameters (attended from 1 to 2).", name));
			}
			else if ("*".Equals(args[args.Count - 1]) && !acceptAsterisk)
			{
				throw new QueryException(string.Format("Aggregate {0}(): invalid argument '*'.", name));
			}
			SqlStringBuilder cmd = new SqlStringBuilder();
			cmd.Add(name)
				.Add("(");
			if (args.Count > 1)
			{
				object firstArg = args[0];
				if (!StringHelper.EqualsCaseInsensitive("distinct", firstArg.ToString()) &&
				    !StringHelper.EqualsCaseInsensitive("all", firstArg.ToString()))
				{
					throw new QueryException(string.Format("Aggregate {0}(): token unknow {1}.", name, firstArg));
				}
				cmd.AddObject(firstArg).Add(" ");
			}
			cmd.AddObject(args[args.Count - 1])
				.Add(")");
			return cmd.ToSqlString();
		}
Example #21
0
 public AssociationVisitor(ISessionFactoryImplementor sessionFactory)
 {
     _sessionFactory = sessionFactory;
     _metaData = _sessionFactory.GetAllClassMetadata();
     _proxyTypes = _sessionFactory.GetProxyMetaData(_metaData);
     _associationPathsToInclude = new List<string>();
 }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="factory"></param>
		/// <param name="persistentClass"></param>
		/// <param name="alias"></param>
		/// <returns></returns>
		public override SqlString ToSqlString( ISessionFactoryImplementor factory, System.Type persistentClass, string alias, IDictionary aliasClasses )
		{
			//TODO: add default capacity
			SqlStringBuilder sqlBuilder = new SqlStringBuilder();

			string[ ] columnNames = AbstractCriterion.GetColumns( factory, persistentClass, _propertyName, alias, aliasClasses );

			for( int i = 0; i < columnNames.Length; i++ )
			{
				if( i > 0 )
				{
					sqlBuilder.Add( " and " );
				}

				sqlBuilder.Add( columnNames[ i ] )
					.Add( " is null" );
			}

			if( columnNames.Length > 1 )
			{
				sqlBuilder.Insert( 0, "(" );
				sqlBuilder.Add( ")" );
			}

			return sqlBuilder.ToSqlString();
		}
		public SQLQueryReturnProcessor(
			ISQLQueryReturn[] queryReturns,
			ISessionFactoryImplementor factory)
		{
			this.queryReturns = queryReturns;
			this.factory = factory;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="factory"></param>
		/// <param name="persistentClass"></param>
		/// <param name="alias"></param>
		/// <returns></returns>
		public override SqlString ToSqlString( ISessionFactoryImplementor factory, System.Type persistentClass, string alias, IDictionary aliasClasses )
		{
			//TODO: add default capacity
			SqlStringBuilder sqlBuilder = new SqlStringBuilder();

			IType propertyType = AbstractCriterion.GetType( factory, persistentClass, _propertyName, aliasClasses );
			string[ ] columnNames = AbstractCriterion.GetColumns( factory, persistentClass, _propertyName, alias, aliasClasses );
			Parameter[ ] parameters = Parameter.GenerateParameters( factory, columnNames, propertyType );

			if( columnNames.Length != 1 )
			{
				throw new HibernateException( "insensitive like may only be used with single-column properties" );
			}

			if( factory.Dialect is PostgreSQLDialect )
			{
				sqlBuilder.Add( columnNames[ 0 ] );
				sqlBuilder.Add( " ilike " );
			}
			else
			{
				sqlBuilder.Add( factory.Dialect.LowercaseFunction )
					.Add( "(" )
					.Add( columnNames[ 0 ] )
					.Add( ")" )
					.Add( " like " );
			}

			sqlBuilder.Add( parameters[ 0 ] );

			return sqlBuilder.ToSqlString();
		}
Example #25
0
        /// <summary>
        /// Wrapper class to produce an Ado.Net Datatable from any entity, 
        /// and perform SqlBulkCopy operations
        /// </summary>
        public SqlEntityBulkCopy(string sqlCnnString, Type entityType)
        {
            if (Cfg == null)
            {
                //Note: The NHibernate.Cfg.Configuration is meant only as an initialization-time object.
                //Note: NHibernate.ISessionFactory is immutable and does not retain any association back to the Session

                Cfg = new Configuration();
                //Cfg.SetProperty("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
                Cfg.SetProperty("dialect", "NHibernate.Dialect.MsSql2008Dialect");
                Cfg.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
                Cfg.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
                Cfg.SetProperty("connection.connection_string", sqlCnnString);

                //add all the mappings embedded in this assembly
                Cfg.AddAssembly(typeof(SqlEntityBulkCopy).Assembly);

                var sessionFactory = Cfg.BuildSessionFactory();
                SessionFactoryImpl = (ISessionFactoryImplementor)sessionFactory;
            }
            EntityType = entityType;
            //_session = SessionFactoryImpl.OpenSession();
            _metaData = SessionFactoryImpl.GetClassMetadata(EntityType);
            _persistentClass = Cfg.GetClassMapping(EntityType);
            _sqlCnn = new SqlConnection(sqlCnnString);
            _sqlBulkCopy = new SqlBulkCopy(_sqlCnn);

            //Debug.WriteLine("EntityName = " + _metaData.EntityName);
            //Debug.WriteLine("IdentifierPropertyName = " + _metaData.IdentifierPropertyName);
            //Debug.WriteLine("IdentifierType = " + _metaData.IdentifierType);

            BuildDataTable();
            BuildAndMapSqlBulkCopy();
        }
		public BasicCollectionJoinWalker(
			IQueryableCollection collectionPersister,
			int batchSize,
			SqlString subquery,
			ISessionFactoryImplementor factory,
			IDictionary enabledFilters)
			: base(factory, enabledFilters)
		{
			this.collectionPersister = collectionPersister;
			string alias = GenerateRootAlias(collectionPersister.Role);

			WalkCollectionTree(collectionPersister, alias);

			IList allAssociations = new ArrayList();

			ArrayHelper.AddAll(allAssociations, associations);
			allAssociations.Add(new OuterJoinableAssociation(
			                    	collectionPersister.CollectionType,
			                    	null,
			                    	null,
			                    	alias,
			                    	JoinType.LeftOuterJoin,
			                    	Factory,
			                    	enabledFilters
			                    	));
			InitPersisters(allAssociations, LockMode.None);
			InitStatementString(alias, batchSize, subquery);
		}
        public IQueryTranslator[] CreateQueryTranslators(string queryString, string collectionRole, bool shallow, IDictionary<string, IFilter> filters, ISessionFactoryImplementor factory)
		{
            var ast = new HqlParseEngine(queryString, collectionRole != null, factory).Parse();

            return CreateQueryTranslators(ast, queryString, collectionRole, shallow,
                                          filters, factory);
        }
		public AbstractEntityLoader(IOuterJoinLoadable persister, IType uniqueKeyType, ISessionFactoryImplementor factory,
		                            IDictionary<string, IFilter> enabledFilters) : base(factory, enabledFilters)
		{
			this.uniqueKeyType = uniqueKeyType;
			entityName = persister.EntityName;
			this.persister = persister;
		}
		private EntityKey(
			object id,
			object identifierSpace,
			System.Type clazz,
			IType identifierType,
			bool isBatchLoadable,
			ISessionFactoryImplementor factory)
		{
			if (id == null)
			{
				throw new ArgumentNullException("id");
			}

			if (!identifierType.ReturnedClass.IsAssignableFrom(id.GetType()))
			{
				throw new ArgumentException("identifier type mismatch", "id");
			}

			this.identifier = id;
			this.identifierSpace = identifierSpace;
			this.clazz = clazz;
			this.identifierType = identifierType;
			this.isBatchLoadable = isBatchLoadable;
			this.factory = factory;
			this.hashCode = GenerateHashCode();
		}
		public SQLQueryContext(INativeSQLQueryReturn[] queryReturns, ISessionFactoryImplementor factory)
		{
			this.factory = factory;

			// first, break down the returns into maps keyed by alias
			// so that role returns can be more easily resolved to their owners
			foreach (INativeSQLQueryReturn rtn in queryReturns)
			{
				var nonScalarRtn = rtn as NativeSQLQueryNonScalarReturn;
				if (nonScalarRtn != null)
				{
					alias2Return[nonScalarRtn.Alias] = rtn;
					var joinRtn = rtn as NativeSQLQueryJoinReturn;
					if (joinRtn != null)
					{
						alias2OwnerAlias[joinRtn.Alias] = joinRtn.OwnerAlias;
					}
				}
			}

			// Now, process the returns
			foreach (INativeSQLQueryReturn rtn in queryReturns)
			{
				ProcessReturn(rtn);
			}
		}
Example #31
0
 protected override bool AppliesTo(ISessionFactoryImplementor factory)
 {
     return(factory.ConnectionProvider.Driver.SupportsMultipleQueries);
 }
 protected internal AbstractSessionImpl(ISessionFactoryImplementor factory)
 {
     this.factory = factory;
 }
        private object AssembleCacheEntry(CacheEntry entry, object id, IEntityPersister persister, LoadEvent @event)
        {
            object       optionalObject        = @event.InstanceToLoad;
            IEventSource session               = @event.Session;
            ISessionFactoryImplementor factory = session.Factory;

            if (log.IsDebugEnabled)
            {
                log.Debug("assembling entity from second-level cache: " + MessageHelper.InfoString(persister, id, factory));
            }

            IEntityPersister subclassPersister = factory.GetEntityPersister(entry.Subclass);
            object           result            = optionalObject ?? session.Instantiate(subclassPersister, id);

            // make it circular-reference safe
            EntityKey entityKey = session.GenerateEntityKey(id, subclassPersister);

            TwoPhaseLoad.AddUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.None, entry.AreLazyPropertiesUnfetched, entry.Version, session);

            IType[]  types  = subclassPersister.PropertyTypes;
            object[] values = entry.Assemble(result, id, subclassPersister, session.Interceptor, session);             // intializes result by side-effect
            TypeHelper.DeepCopy(values, types, subclassPersister.PropertyUpdateability, values, session);

            object version = Versioning.GetVersion(values, subclassPersister);

            if (log.IsDebugEnabled)
            {
                log.Debug("Cached Version: " + version);
            }

            IPersistenceContext persistenceContext = session.PersistenceContext;
            bool isReadOnly = session.DefaultReadOnly;

            if (persister.IsMutable)
            {
                object proxy = persistenceContext.GetProxy(entityKey);
                if (proxy != null)
                {
                    // this is already a proxy for this impl
                    // only set the status to read-only if the proxy is read-only
                    isReadOnly = ((INHibernateProxy)proxy).HibernateLazyInitializer.ReadOnly;
                }
            }
            else
            {
                isReadOnly = true;
            }

            persistenceContext.AddEntry(
                result,
                isReadOnly ? Status.ReadOnly : Status.Loaded,
                values,
                null,
                id,
                version,
                LockMode.None,
                true,
                subclassPersister,
                false,
                entry.AreLazyPropertiesUnfetched);

            subclassPersister.AfterInitialize(result, entry.AreLazyPropertiesUnfetched, session);
            persistenceContext.InitializeNonLazyCollections();
            // upgrade the lock if necessary:
            //lock(result, lockMode);

            //PostLoad is needed for EJB3
            //TODO: reuse the PostLoadEvent...
            PostLoadEvent postLoadEvent = new PostLoadEvent(session);

            postLoadEvent.Entity    = result;
            postLoadEvent.Id        = id;
            postLoadEvent.Persister = persister;

            IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners;
            for (int i = 0; i < listeners.Length; i++)
            {
                listeners[i].OnPostLoad(postLoadEvent);
            }
            return(result);
        }
Example #34
0
 /// <summary>
 /// Given a (potentially unqualified) class name, locate its persister.
 /// </summary>
 /// <param name="sfi">The session factory implementor.</param>
 /// <param name="className">The (potentially unqualified) class name.</param>
 /// <returns>The defined persister for this class, or null if none found.</returns>
 private static IQueryable FindQueryableUsingImports(ISessionFactoryImplementor sfi, string className)
 {
     return(new SessionFactoryHelper(sfi).FindQueryableUsingImports(className));
 }
Example #35
0
 /// <summary>
 /// Construct a new SessionFactoryHelperExtensions instance.
 /// </summary>
 /// <param name="sfi">The SessionFactory impl to be encapsulated.</param>
 public SessionFactoryHelperExtensions(ISessionFactoryImplementor sfi)
 {
     _sfi   = sfi;
     helper = new SessionFactoryHelper(_sfi);
     _collectionPropertyMappingByRole = new NullableDictionary <string, IPropertyMapping>();
 }
Example #36
0
 public JoinSequence(ISessionFactoryImplementor factory)
 {
     this.factory = factory;
 }
Example #37
0
 protected JoinWalker(ISessionFactoryImplementor factory, IDictionary <string, IFilter> enabledFilters)
 {
     this.factory               = factory;
     this.enabledFilters        = enabledFilters;
     enabledFiltersForManyToOne = FilterHelper.GetEnabledForManyToOne(enabledFilters);
 }
Example #38
0
 public override SqlString Render(IList args, ISessionFactoryImplementor factory)
 {
     return(new SqlString("cast('", Name, "' as ", FunctionReturnType.SqlTypes(factory)[0].ToString(), ")"));
 }
        public SingleTableEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
                                          ISessionFactoryImplementor factory, IMapping mapping)
            : base(persistentClass, cache, factory)
        {
            #region CLASS + TABLE

            joinSpan            = persistentClass.JoinClosureSpan + 1;
            qualifiedTableNames = new string[joinSpan];
            isInverseTable      = new bool[joinSpan];
            isNullableTable     = new bool[joinSpan];
            keyColumnNames      = new string[joinSpan][];
            Table table = persistentClass.RootTable;
            qualifiedTableNames[0] =
                table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
            isInverseTable[0]    = false;
            isNullableTable[0]   = false;
            keyColumnNames[0]    = IdentifierColumnNames;
            cascadeDeleteEnabled = new bool[joinSpan];

            // Custom sql
            customSQLInsert         = new SqlString[joinSpan];
            customSQLUpdate         = new SqlString[joinSpan];
            customSQLDelete         = new SqlString[joinSpan];
            insertCallable          = new bool[joinSpan];
            updateCallable          = new bool[joinSpan];
            deleteCallable          = new bool[joinSpan];
            insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[joinSpan];
            updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[joinSpan];
            deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[joinSpan];

            customSQLInsert[0]         = persistentClass.CustomSQLInsert;
            insertCallable[0]          = customSQLInsert[0] != null && persistentClass.IsCustomInsertCallable;
            insertResultCheckStyles[0] = persistentClass.CustomSQLInsertCheckStyle
                                         ?? ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLInsert[0], insertCallable[0]);
            customSQLUpdate[0]         = persistentClass.CustomSQLUpdate;
            updateCallable[0]          = customSQLUpdate[0] != null && persistentClass.IsCustomUpdateCallable;
            updateResultCheckStyles[0] = persistentClass.CustomSQLUpdateCheckStyle
                                         ?? ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLUpdate[0], updateCallable[0]);
            customSQLDelete[0]         = persistentClass.CustomSQLDelete;
            deleteCallable[0]          = customSQLDelete[0] != null && persistentClass.IsCustomDeleteCallable;
            deleteResultCheckStyles[0] = persistentClass.CustomSQLDeleteCheckStyle
                                         ?? ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLDelete[0], deleteCallable[0]);

            #endregion

            #region JOINS
            int j = 1;
            foreach (Join join in persistentClass.JoinClosureIterator)
            {
                qualifiedTableNames[j]  = join.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
                isInverseTable[j]       = join.IsInverse;
                isNullableTable[j]      = join.IsOptional;
                cascadeDeleteEnabled[j] = join.Key.IsCascadeDeleteEnabled && factory.Dialect.SupportsCascadeDelete;

                customSQLInsert[j]         = join.CustomSQLInsert;
                insertCallable[j]          = customSQLInsert[j] != null && join.IsCustomInsertCallable;
                insertResultCheckStyles[j] = join.CustomSQLInsertCheckStyle
                                             ??
                                             ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLInsert[j], insertCallable[j]);
                customSQLUpdate[j]         = join.CustomSQLUpdate;
                updateCallable[j]          = customSQLUpdate[j] != null && join.IsCustomUpdateCallable;
                updateResultCheckStyles[j] = join.CustomSQLUpdateCheckStyle
                                             ??
                                             ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLUpdate[j], updateCallable[j]);
                customSQLDelete[j]         = join.CustomSQLDelete;
                deleteCallable[j]          = customSQLDelete[j] != null && join.IsCustomDeleteCallable;
                deleteResultCheckStyles[j] = join.CustomSQLDeleteCheckStyle
                                             ??
                                             ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLDelete[j], deleteCallable[j]);

                IEnumerable <Column> enumerableKeyCol = new SafetyEnumerable <Column>(join.Key.ColumnIterator);
                List <string>        kcName           = new List <string>(join.Key.ColumnSpan);
                foreach (Column col in enumerableKeyCol)
                {
                    kcName.Add(col.GetQuotedName(factory.Dialect));
                }

                keyColumnNames[j] = kcName.ToArray();

                j++;
            }

            constraintOrderedTableNames     = new string[qualifiedTableNames.Length];
            constraintOrderedKeyColumnNames = new string[qualifiedTableNames.Length][];
            for (int i = qualifiedTableNames.Length - 1, position = 0; i >= 0; i--, position++)
            {
                constraintOrderedTableNames[position]     = qualifiedTableNames[i];
                constraintOrderedKeyColumnNames[position] = keyColumnNames[i];
            }

            spaces = ArrayHelper.Join(qualifiedTableNames, ArrayHelper.ToStringArray(persistentClass.SynchronizedTables));

            bool lazyAvailable = IsInstrumented(EntityMode.Poco);

            bool            hasDeferred    = false;
            List <string>   subclassTables = new List <string>();
            List <string[]> joinKeyColumns = new List <string[]>();
            List <bool>     isConcretes    = new List <bool>();
            List <bool>     isDeferreds    = new List <bool>();
            List <bool>     isInverses     = new List <bool>();
            List <bool>     isNullables    = new List <bool>();
            List <bool>     isLazies       = new List <bool>();
            subclassTables.Add(qualifiedTableNames[0]);
            joinKeyColumns.Add(IdentifierColumnNames);
            isConcretes.Add(true);
            isDeferreds.Add(false);
            isInverses.Add(false);
            isNullables.Add(false);
            isLazies.Add(false);
            foreach (Join join in persistentClass.SubclassJoinClosureIterator)
            {
                isConcretes.Add(persistentClass.IsClassOrSuperclassJoin(join));
                isDeferreds.Add(join.IsSequentialSelect);
                isInverses.Add(join.IsInverse);
                isNullables.Add(join.IsOptional);
                isLazies.Add(lazyAvailable && join.IsLazy);
                if (join.IsSequentialSelect && !persistentClass.IsClassOrSuperclassJoin(join))
                {
                    hasDeferred = true;
                }
                subclassTables.Add(join.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName));
                IEnumerable <Column> enumerableKeyCol = new SafetyEnumerable <Column>(join.Key.ColumnIterator);
                List <string>        keyCols          = new List <string>(join.Key.ColumnSpan);
                foreach (Column col in enumerableKeyCol)
                {
                    keyCols.Add(col.GetQuotedName(factory.Dialect));
                }

                joinKeyColumns.Add(keyCols.ToArray());
            }

            subclassTableSequentialSelect = isDeferreds.ToArray();
            subclassTableNameClosure      = subclassTables.ToArray();
            subclassTableIsLazyClosure    = isLazies.ToArray();
            subclassTableKeyColumnClosure = joinKeyColumns.ToArray();
            isClassOrSuperclassTable      = isConcretes.ToArray();
            isInverseSubclassTable        = isInverses.ToArray();
            isNullableSubclassTable       = isNullables.ToArray();
            hasSequentialSelects          = hasDeferred;

            #endregion

            #region DISCRIMINATOR

            if (persistentClass.IsPolymorphic)
            {
                IValue discrimValue = persistentClass.Discriminator;
                if (discrimValue == null)
                {
                    throw new MappingException("Discriminator mapping required for single table polymorphic persistence");
                }

                forceDiscriminator = persistentClass.IsForceDiscriminator;
                IEnumerator <ISelectable> iSel = discrimValue.ColumnIterator.GetEnumerator();
                iSel.MoveNext();
                ISelectable selectable = iSel.Current;
                if (discrimValue.HasFormula)
                {
                    Formula formula = (Formula)selectable;
                    discriminatorFormula         = formula.FormulaString;
                    discriminatorFormulaTemplate = formula.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
                    discriminatorColumnName      = null;
                    discriminatorAlias           = Discriminator_Alias;
                }
                else
                {
                    Column column = (Column)selectable;
                    discriminatorColumnName      = column.GetQuotedName(factory.Dialect);
                    discriminatorAlias           = column.GetAlias(factory.Dialect, persistentClass.RootTable);
                    discriminatorFormula         = null;
                    discriminatorFormulaTemplate = null;
                }
                discriminatorType = persistentClass.Discriminator.Type;
                if (persistentClass.IsDiscriminatorValueNull)
                {
                    discriminatorValue      = NullDiscriminator;
                    discriminatorSQLValue   = InFragment.Null;
                    discriminatorInsertable = false;
                }
                else if (persistentClass.IsDiscriminatorValueNotNull)
                {
                    discriminatorValue      = NotNullDiscriminator;
                    discriminatorSQLValue   = InFragment.NotNull;
                    discriminatorInsertable = false;
                }
                else
                {
                    discriminatorInsertable = persistentClass.IsDiscriminatorInsertable && !discrimValue.HasFormula;
                    try
                    {
                        IDiscriminatorType dtype = (IDiscriminatorType)discriminatorType;
                        discriminatorValue    = dtype.StringToObject(persistentClass.DiscriminatorValue);
                        discriminatorSQLValue = dtype.ObjectToSQLString(discriminatorValue, factory.Dialect);
                    }
                    catch (InvalidCastException cce)
                    {
                        throw new MappingException(
                                  string.Format("Illegal discriminator type: {0} of entity {1}", discriminatorType.Name, persistentClass.EntityName), cce);
                    }
                    catch (Exception e)
                    {
                        throw new MappingException("Could not format discriminator value to SQL string of entity " + persistentClass.EntityName, e);
                    }
                }
            }
            else
            {
                forceDiscriminator           = false;
                discriminatorInsertable      = false;
                discriminatorColumnName      = null;
                discriminatorAlias           = null;
                discriminatorType            = null;
                discriminatorValue           = null;
                discriminatorSQLValue        = null;
                discriminatorFormula         = null;
                discriminatorFormulaTemplate = null;
            }

            #endregion

            #region PROPERTIES

            propertyTableNumbers = new int[PropertySpan];
            int i2 = 0;
            foreach (Property prop in persistentClass.PropertyClosureIterator)
            {
                propertyTableNumbers[i2++] = persistentClass.GetJoinNumber(prop);
            }

            List <int> columnJoinNumbers    = new List <int>();
            List <int> formulaJoinedNumbers = new List <int>();
            List <int> propertyJoinNumbers  = new List <int>();
            foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
            {
                int join = persistentClass.GetJoinNumber(prop);
                propertyJoinNumbers.Add(join);

                //propertyTableNumbersByName.put( prop.getName(), join );
                propertyTableNumbersByNameAndSubclass[prop.PersistentClass.EntityName + '.' + prop.Name] = join;
                foreach (ISelectable thing in prop.ColumnIterator)
                {
                    if (thing.IsFormula)
                    {
                        formulaJoinedNumbers.Add(join);
                    }
                    else
                    {
                        columnJoinNumbers.Add(join);
                    }
                }
            }

            subclassColumnTableNumberClosure   = columnJoinNumbers.ToArray();
            subclassFormulaTableNumberClosure  = formulaJoinedNumbers.ToArray();
            subclassPropertyTableNumberClosure = propertyJoinNumbers.ToArray();

            int subclassSpan = persistentClass.SubclassSpan + 1;
            subclassClosure    = new string[subclassSpan];
            subclassClosure[0] = EntityName;
            if (persistentClass.IsPolymorphic)
            {
                subclassesByDiscriminatorValue[discriminatorValue] = EntityName;
            }

            #endregion

            #region SUBCLASSES
            if (persistentClass.IsPolymorphic)
            {
                int k = 1;
                foreach (Subclass sc in persistentClass.SubclassIterator)
                {
                    subclassClosure[k++] = sc.EntityName;
                    if (sc.IsDiscriminatorValueNull)
                    {
                        subclassesByDiscriminatorValue[NullDiscriminator] = sc.EntityName;
                    }
                    else if (sc.IsDiscriminatorValueNotNull)
                    {
                        subclassesByDiscriminatorValue[NotNullDiscriminator] = sc.EntityName;
                    }
                    else
                    {
                        if (discriminatorType == null)
                        {
                            throw new MappingException("Not available discriminator type of entity " + persistentClass.EntityName);
                        }
                        try
                        {
                            IDiscriminatorType dtype = (IDiscriminatorType)discriminatorType;
                            subclassesByDiscriminatorValue[dtype.StringToObject(sc.DiscriminatorValue)] = sc.EntityName;
                        }
                        catch (InvalidCastException cce)
                        {
                            throw new MappingException(
                                      string.Format("Illegal discriminator type: {0} of entity {1}", discriminatorType.Name, persistentClass.EntityName), cce);
                        }
                        catch (Exception e)
                        {
                            throw new MappingException("Error parsing discriminator value of entity " + persistentClass.EntityName, e);
                        }
                    }
                }
            }

            #endregion

            InitLockers();

            InitSubclassPropertyAliasesMap(persistentClass);

            PostConstruct(mapping);
        }
Example #40
0
 public override SqlString Render(IList args, ISessionFactoryImplementor factory)
 {
     return(new SqlString(Name));
 }
 // Constructor signature required for dynamic invocation code.
 public AsyncLocalSessionContext(ISessionFactoryImplementor factory)
 {
 }
 public DebugSessionFactory(ISessionFactory actualFactory)
 {
     ActualFactory = (ISessionFactoryImplementor)actualFactory;
 }
 public BasicCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg, ISessionFactoryImplementor factory)
     : base(collection, cache, cfg, factory)
 {
 }
Example #44
0
 public QueryPlanCache(ISessionFactoryImplementor factory)
 {
     this.factory = factory;
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="alias"></param>
 /// <param name="columns"></param>
 /// <param name="condition"></param>
 /// <param name="conditionType"></param>
 /// <param name="factory"></param>
 public abstract void AddCondition(string alias, string[] columns, string condition, IType conditionType, ISessionFactoryImplementor factory);
Example #46
0
 protected virtual void BuildSessionFactory()
 {
     sessions           = (ISessionFactoryImplementor)cfg.BuildSessionFactory();
     connectionProvider = sessions.ConnectionProvider as DebugConnectionProvider;
 }
Example #47
0
 protected internal AbstractSessionImpl(ISessionFactoryImplementor factory, Guid sessionId)
     : this(factory)
 {
     this.sessionId = sessionId;
 }
 protected override bool AppliesTo(ISessionFactoryImplementor factory)
 => base.AppliesTo(factory) && factory.ConnectionProvider.Driver.SupportsEnlistmentWhenAutoEnlistmentIsDisabled;
 public override object DeepCopy(object value, ISessionFactoryImplementor factory)
 {
     return(userType.DeepCopy(value));
 }
 // Evict collections from the factory-level cache
 private Task EvictCachedCollectionsAsync(IEntityPersister persister, object id, ISessionFactoryImplementor factory, CancellationToken cancellationToken)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(Task.FromCanceled <object>(cancellationToken));
     }
     return(EvictCachedCollectionsAsync(persister.PropertyTypes, id, factory, cancellationToken));
 }
        internal static IDictionary <ConstantExpression, NamedParameter> Visit(ref Expression expression, ISessionFactoryImplementor sessionFactory)
        {
            var visitor = new ExpressionParameterVisitor(sessionFactory);

            expression = visitor.VisitExpression(expression);

            return(visitor._parameters);
        }
 public override string ToLoggableString(object value, ISessionFactoryImplementor factory)
 {
     return(value == null ? "null" : value.ToString());
 }
 public ExpressionParameterVisitor(ISessionFactoryImplementor sessionFactory)
 {
     _sessionFactory = sessionFactory;
 }
Example #54
0
 public NativeSQLQueryPlan(NativeSQLQuerySpecification specification, ISessionFactoryImplementor factory)
 {
     sourceQuery = specification.QueryString;
     customQuery = new SQLCustomQuery(specification.SqlQueryReturns, specification.QueryString, specification.QuerySpaces, factory);
 }
 public LazySessionContext(ISessionFactoryImplementor factory)
 {
     this.factory = factory;
 }
 public static IDictionary <ConstantExpression, NamedParameter> Visit(Expression expression, ISessionFactoryImplementor sessionFactory)
 {
     return(Visit(ref expression, sessionFactory));
 }
Example #57
0
 protected override bool AppliesTo(ISessionFactoryImplementor factory)
 {
     return(factory.ConnectionProvider.Driver is SqlClientDriver);
 }
Example #58
0
        /// <summary>
        /// Perform the second step of 2-phase load. Fully initialize the entity instance.
        /// After processing a JDBC result set, we "resolve" all the associations
        /// between the entities which were instantiated and had their state
        /// "hydrated" into an array
        /// </summary>
        internal static async Task InitializeEntityAsync(object entity, bool readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent,
                                                         Action <IEntityPersister, CachePutData> cacheBatchingHandler, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            //TODO: Should this be an InitializeEntityEventListener??? (watch out for performance!)

            bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled;
            var  stopWath     = new Stopwatch();

            if (statsEnabled)
            {
                stopWath.Start();
            }

            IPersistenceContext persistenceContext = session.PersistenceContext;
            EntityEntry         entityEntry        = persistenceContext.GetEntry(entity);

            if (entityEntry == null)
            {
                throw new AssertionFailure("possible non-threadsafe access to the session");
            }
            IEntityPersister persister = entityEntry.Persister;
            object           id        = entityEntry.Id;

            object[] hydratedState = entityEntry.LoadedState;

            if (log.IsDebugEnabled())
            {
                log.Debug("resolving associations for {0}", MessageHelper.InfoString(persister, id, session.Factory));
            }

            IType[] types = persister.PropertyTypes;
            var     collectionToResolveIndexes = new List <int>(hydratedState.Length);

            for (int i = 0; i < hydratedState.Length; i++)
            {
                object value = hydratedState[i];
                if (!Equals(LazyPropertyInitializer.UnfetchedProperty, value) && !(Equals(BackrefPropertyAccessor.Unknown, value)))
                {
                    if (types[i].IsCollectionType)
                    {
                        // Resolve them last, because they may depend on other properties if they use a property-ref
                        collectionToResolveIndexes.Add(i);
                        continue;
                    }

                    hydratedState[i] = await(types[i].ResolveIdentifierAsync(value, session, entity, cancellationToken)).ConfigureAwait(false);
                }
            }

            foreach (var i in collectionToResolveIndexes)
            {
                hydratedState[i] = await(types[i].ResolveIdentifierAsync(hydratedState[i], session, entity, cancellationToken)).ConfigureAwait(false);
            }

            //Must occur after resolving identifiers!
            if (session.IsEventSource)
            {
                preLoadEvent.Entity    = entity;
                preLoadEvent.State     = hydratedState;
                preLoadEvent.Id        = id;
                preLoadEvent.Persister = persister;
                IPreLoadEventListener[] listeners = session.Listeners.PreLoadEventListeners;
                for (int i = 0; i < listeners.Length; i++)
                {
                    await(listeners[i].OnPreLoadAsync(preLoadEvent, cancellationToken)).ConfigureAwait(false);
                }
            }

            persister.SetPropertyValues(entity, hydratedState);

            ISessionFactoryImplementor factory = session.Factory;

            if (persister.HasCache && session.CacheMode.HasFlag(CacheMode.Put))
            {
                if (log.IsDebugEnabled())
                {
                    log.Debug("adding entity to second-level cache: {0}", MessageHelper.InfoString(persister, id, session.Factory));
                }

                object     version = Versioning.GetVersion(hydratedState, persister);
                CacheEntry entry   =
                    await(CacheEntry.CreateAsync(hydratedState, persister, entityEntry.LoadedWithLazyPropertiesUnfetched, version, session, entity, cancellationToken)).ConfigureAwait(false);
                CacheKey cacheKey = session.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName);

                if (cacheBatchingHandler != null && persister.IsBatchLoadable)
                {
                    cacheBatchingHandler(
                        persister,
                        new CachePutData(
                            cacheKey,
                            persister.CacheEntryStructure.Structure(entry),
                            version,
                            persister.IsVersioned ? persister.VersionType.Comparator : null,
                            UseMinimalPuts(session, entityEntry)));
                }
                else
                {
                    bool put =
                        await(persister.Cache.PutAsync(cacheKey, persister.CacheEntryStructure.Structure(entry), session.Timestamp, version,
                                                       persister.IsVersioned ? persister.VersionType.Comparator : null,
                                                       UseMinimalPuts(session, entityEntry), cancellationToken)).ConfigureAwait(false);

                    if (put && factory.Statistics.IsStatisticsEnabled)
                    {
                        factory.StatisticsImplementor.SecondLevelCachePut(persister.Cache.RegionName);
                    }
                }
            }

            bool isReallyReadOnly = readOnly;

            if (!persister.IsMutable)
            {
                isReallyReadOnly = true;
            }
            else
            {
                object proxy = persistenceContext.GetProxy(entityEntry.EntityKey);
                if (proxy != null)
                {
                    // there is already a proxy for this impl
                    // only set the status to read-only if the proxy is read-only
                    isReallyReadOnly = ((INHibernateProxy)proxy).HibernateLazyInitializer.ReadOnly;
                }
            }

            if (isReallyReadOnly)
            {
                //no need to take a snapshot - this is a
                //performance optimization, but not really
                //important, except for entities with huge
                //mutable property values
                persistenceContext.SetEntryStatus(entityEntry, Status.ReadOnly);
            }
            else
            {
                //take a snapshot
                TypeHelper.DeepCopy(hydratedState, persister.PropertyTypes, persister.PropertyUpdateability, hydratedState, session);
                persistenceContext.SetEntryStatus(entityEntry, Status.Loaded);
            }

            persister.AfterInitialize(entity, entityEntry.LoadedWithLazyPropertiesUnfetched, session);

            if (session.IsEventSource)
            {
                postLoadEvent.Entity    = entity;
                postLoadEvent.Id        = id;
                postLoadEvent.Persister = persister;
                IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners;
                for (int i = 0; i < listeners.Length; i++)
                {
                    listeners[i].OnPostLoad(postLoadEvent);
                }
            }

            if (log.IsDebugEnabled())
            {
                log.Debug("done materializing entity {0}", MessageHelper.InfoString(persister, id, session.Factory));
            }

            if (statsEnabled)
            {
                stopWath.Stop();
                factory.StatisticsImplementor.LoadEntity(persister.EntityName, stopWath.Elapsed);
            }
        }
Example #59
0
        public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplementor sessionFactory)
        {
            this.sessionFactory = sessionFactory;


            name       = persistentClass.EntityName;
            rootName   = persistentClass.RootClazz.EntityName;
            entityType = TypeFactory.ManyToOne(name);
            type       = persistentClass.MappedClass;
            rootType   = persistentClass.RootClazz.MappedClass;
            rootTypeAssemblyQualifiedName = rootType == null ? null : rootType.AssemblyQualifiedName;

            identifierProperty = PropertyFactory.BuildIdentifierProperty(persistentClass,
                                                                         sessionFactory.GetIdentifierGenerator(rootName));

            versioned = persistentClass.IsVersioned;

            bool lazyAvailable = persistentClass.HasPocoRepresentation &&
                                 FieldInterceptionHelper.IsInstrumented(persistentClass.MappedClass);
            bool hasLazy = false;

            propertySpan = persistentClass.PropertyClosureSpan;
            properties   = new StandardProperty[propertySpan];
            List <int> naturalIdNumbers = new List <int>();

            propertyNames                = new string[propertySpan];
            propertyTypes                = new IType[propertySpan];
            propertyUpdateability        = new bool[propertySpan];
            propertyInsertability        = new bool[propertySpan];
            insertInclusions             = new ValueInclusion[propertySpan];
            updateInclusions             = new ValueInclusion[propertySpan];
            nonlazyPropertyUpdateability = new bool[propertySpan];
            propertyCheckability         = new bool[propertySpan];
            propertyNullability          = new bool[propertySpan];
            propertyVersionability       = new bool[propertySpan];
            propertyLaziness             = new bool[propertySpan];
            cascadeStyles                = new CascadeStyle[propertySpan];

            int  i = 0;
            int  tempVersionProperty               = NoVersionIndex;
            bool foundCascade                      = false;
            bool foundCollection                   = false;
            bool foundMutable                      = false;
            bool foundInsertGeneratedValue         = false;
            bool foundUpdateGeneratedValue         = false;
            bool foundNonIdentifierPropertyNamedId = false;

            HasPocoRepresentation = persistentClass.HasPocoRepresentation;

            // NH: WARNING if we have to disable lazy/unproxy properties we have to do it in the whole process.
            lazy           = persistentClass.IsLazy && (!persistentClass.HasPocoRepresentation || !ReflectHelper.IsFinalClass(persistentClass.ProxyInterface));
            lazyAvailable &= lazy;             // <== Disable lazy properties if the class is marked with lazy=false

            bool hadLazyProperties   = false;
            bool hadNoProxyRelations = false;

            foreach (Mapping.Property prop in persistentClass.PropertyClosureIterator)
            {
                if (prop.IsLazy)
                {
                    hadLazyProperties = true;
                }
                if (prop.UnwrapProxy)
                {
                    hadNoProxyRelations = true;
                }

                // NH: A lazy property is a simple property marked with lazy=true
                bool islazyProperty = prop.IsLazy && lazyAvailable && (!prop.IsEntityRelation || prop.UnwrapProxy);
                // NH: A Relation (in this case many-to-one or one-to-one) marked as "no-proxy"
                var isUnwrapProxy = prop.UnwrapProxy && lazyAvailable;

                if (islazyProperty || isUnwrapProxy)
                {
                    // NH: verify property proxiability
                    var getter = prop.GetGetter(persistentClass.MappedClass);
                    if (getter.Method == null || getter.Method.IsDefined(typeof(CompilerGeneratedAttribute), false) == false)
                    {
                        log.ErrorFormat("Lazy or no-proxy property {0}.{1} is not an auto property, which may result in uninitialized property access", persistentClass.EntityName, prop.Name);
                    }
                }

                if (prop == persistentClass.Version)
                {
                    tempVersionProperty = i;
                    properties[i]       = PropertyFactory.BuildVersionProperty(prop, islazyProperty);
                }
                else
                {
                    properties[i] = PropertyFactory.BuildStandardProperty(prop, islazyProperty);
                }

                if (prop.IsNaturalIdentifier)
                {
                    naturalIdNumbers.Add(i);
                }

                if ("id".Equals(prop.Name))
                {
                    foundNonIdentifierPropertyNamedId = true;
                }

                if (islazyProperty)
                {
                    hasLazy = true;
                }
                if (isUnwrapProxy)
                {
                    hasUnwrapProxyForProperties = true;
                }

                propertyLaziness[i] = islazyProperty;

                propertyNames[i]                = properties[i].Name;
                propertyTypes[i]                = properties[i].Type;
                propertyNullability[i]          = properties[i].IsNullable;
                propertyUpdateability[i]        = properties[i].IsUpdateable;
                propertyInsertability[i]        = properties[i].IsInsertable;
                insertInclusions[i]             = DetermineInsertValueGenerationType(prop, properties[i]);
                updateInclusions[i]             = DetermineUpdateValueGenerationType(prop, properties[i]);
                propertyVersionability[i]       = properties[i].IsVersionable;
                nonlazyPropertyUpdateability[i] = properties[i].IsUpdateable && !islazyProperty;
                propertyCheckability[i]         = propertyUpdateability[i]
                                                  ||
                                                  (propertyTypes[i].IsAssociationType &&
                                                   ((IAssociationType)propertyTypes[i]).IsAlwaysDirtyChecked);

                cascadeStyles[i] = properties[i].CascadeStyle;

                if (properties[i].IsLazy)
                {
                    hasLazy = true;
                }

                if (properties[i].CascadeStyle != CascadeStyle.None)
                {
                    foundCascade = true;
                }

                if (IndicatesCollection(properties[i].Type))
                {
                    foundCollection = true;
                }

                if (propertyTypes[i].IsMutable && propertyCheckability[i])
                {
                    foundMutable = true;
                }

                if (insertInclusions[i] != ValueInclusion.None)
                {
                    foundInsertGeneratedValue = true;
                }

                if (updateInclusions[i] != ValueInclusion.None)
                {
                    foundUpdateGeneratedValue = true;
                }

                MapPropertyToIndex(prop, i);
                i++;
            }

            if (naturalIdNumbers.Count == 0)
            {
                naturalIdPropertyNumbers = null;
            }
            else
            {
                naturalIdPropertyNumbers = naturalIdNumbers.ToArray();
            }

            hasCascades = foundCascade;
            hasInsertGeneratedValues        = foundInsertGeneratedValue;
            hasUpdateGeneratedValues        = foundUpdateGeneratedValue;
            hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId;

            versionPropertyIndex = tempVersionProperty;
            hasLazyProperties    = hasLazy;

            if (hadLazyProperties && !hasLazy)
            {
                log.WarnFormat("Disabled lazy property fetching for {0} because it does not support lazy at the entity level", name);
            }
            if (hasLazy)
            {
                log.Info("lazy property fetching available for: " + name);
            }

            if (hadNoProxyRelations && !hasUnwrapProxyForProperties)
            {
                log.WarnFormat("Disabled ghost property fetching for {0} because it does not support lazy at the entity level", name);
            }
            if (hasUnwrapProxyForProperties)
            {
                log.Info("no-proxy property fetching available for: " + name);
            }

            mutable = persistentClass.IsMutable;

            if (!persistentClass.IsAbstract.HasValue)
            {
                // legacy behavior (with no abstract attribute specified)
                isAbstract = persistentClass.HasPocoRepresentation && ReflectHelper.IsAbstractClass(persistentClass.MappedClass);
            }
            else
            {
                isAbstract = persistentClass.IsAbstract.Value;
                if (!isAbstract && persistentClass.HasPocoRepresentation &&
                    ReflectHelper.IsAbstractClass(persistentClass.MappedClass))
                {
                    //Modified by OneGeo: Concating the type without the null
                    log.Warn("entity [" + (type == null? persistentClass.EntityName : type.FullName)
                             + "] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names");
                }
            }
            selectBeforeUpdate = persistentClass.SelectBeforeUpdate;
            dynamicUpdate      = persistentClass.DynamicUpdate;
            dynamicInsert      = persistentClass.DynamicInsert;

            polymorphic          = persistentClass.IsPolymorphic;
            explicitPolymorphism = persistentClass.IsExplicitPolymorphism;
            inherited            = persistentClass.IsInherited;
            superclass           = inherited ? persistentClass.Superclass.EntityName : null;
            superclassType       = inherited ? persistentClass.Superclass.MappedClass : null;
            hasSubclasses        = persistentClass.HasSubclasses;

            optimisticLockMode = persistentClass.OptimisticLockMode;
            if (optimisticLockMode > Versioning.OptimisticLock.Version && !dynamicUpdate)
            {
                //Modified by OneGeo: Concating the type without the null
                throw new MappingException("optimistic-lock setting requires dynamic-update=\"true\": " + (type == null ? persistentClass.EntityName : type.FullName));
            }

            hasCollections       = foundCollection;
            hasMutableProperties = foundMutable;

            foreach (Subclass obj in persistentClass.SubclassIterator)
            {
                subclassEntityNames.Add(obj.EntityName);
            }
            subclassEntityNames.Add(name);

            EntityMode = persistentClass.HasPocoRepresentation ? EntityMode.Poco : EntityMode.Map;

            var entityTuplizerFactory = new EntityTuplizerFactory();
            var tuplizerClassName     = persistentClass.GetTuplizerImplClassName(EntityMode);

            Tuplizer = tuplizerClassName == null
                                ? entityTuplizerFactory.BuildDefaultEntityTuplizer(EntityMode, this, persistentClass)
                                : entityTuplizerFactory.BuildEntityTuplizer(tuplizerClassName, this, persistentClass);
        }
 public static IUniqueEntityLoader CreateBatchingEntityLoader(IOuterJoinLoadable persister, int maxBatchSize,
                                                              LockMode lockMode, ISessionFactoryImplementor factory,
                                                              IDictionary <string, IFilter> enabledFilters)
 {
     if (maxBatchSize > 1)
     {
         int[]    batchSizesToCreate = ArrayHelper.GetBatchSizes(maxBatchSize);
         Loader[] loadersToCreate    = new Loader[batchSizesToCreate.Length];
         for (int i = 0; i < batchSizesToCreate.Length; i++)
         {
             loadersToCreate[i] = new EntityLoader(persister, batchSizesToCreate[i], lockMode, factory, enabledFilters);
         }
         return(new BatchingEntityLoader(persister, batchSizesToCreate, loadersToCreate));
     }
     else
     {
         return(new EntityLoader(persister, lockMode, factory, enabledFilters));
     }
 }