public override PropertyDescriptorCollection GetProperties()
 {
     if (_properties == null)
     {
         bool hasEntityAttributes = false;
         _properties = base.GetProperties();
         var list = new List<PropertyDescriptor>();
         foreach (PropertyDescriptor descriptor in _properties)
         {
             List<Attribute> attrs = GetEntityMemberAttributes(descriptor).ToList();
             if (_metaDataAttributes.ContainsKey(descriptor.Name))
                 attrs.AddRange(_metaDataAttributes[descriptor.Name]);
             if (attrs.Any())
             {
                 hasEntityAttributes = true;
                 list.Add(new PropertyDescriptorWrapper(descriptor, attrs.ToArray()));
             }
             else
             {
                 list.Add(descriptor);
             }
         }
         if (hasEntityAttributes)
             _properties = new PropertyDescriptorCollection(list.ToArray(), true);
     }
     return _properties;
 }
        public string[] GenerateSchemaDropScriptAuxiliaryDatabaseObjects(Func<IAuxiliaryDatabaseObject, bool> predicate)
        {
            Dialect dialect = Dialect.GetDialect(Properties);
            string defaultCatalog = PropertiesHelper.GetString("default_catalog", Properties, null);
            string defaultSchema = PropertiesHelper.GetString("default_schema", Properties, null);
            List<string> list = new List<string>();
            foreach (IAuxiliaryDatabaseObject obj2 in auxiliaryDatabaseObjects.Where(predicate))
            {
                if (obj2.AppliesToDialect(dialect))
                {
                    list.Add(obj2.SqlDropString(dialect,defaultCatalog, defaultSchema));
                }
            }

            return list.ToArray();
        }
		/// <summary>
		/// Constructs the NormalizedEntityPerister for the PersistentClass.
		/// </summary>
		/// <param name="persistentClass">The PersistentClass to create the EntityPersister for.</param>
		/// <param name="cache">The configured <see cref="ICacheConcurrencyStrategy" />.</param>
		/// <param name="factory">The SessionFactory that this EntityPersister will be stored in.</param>
		/// <param name="mapping">The mapping used to retrieve type information.</param>
		public JoinedSubclassEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
											 ISessionFactoryImplementor factory, IMapping mapping)
			: base(persistentClass, cache, factory)
		{
			#region DISCRIMINATOR

			if (persistentClass.IsPolymorphic)
			{
				try
				{
					discriminatorValue = persistentClass.SubclassId;
					discriminatorSQLString = discriminatorValue.ToString();
				}
				catch (Exception e)
				{
					throw new MappingException("Could not format discriminator value to SQL string", e);
				}
			}
			else
			{
				discriminatorValue = null;
				discriminatorSQLString = null;
			}

			if (OptimisticLockMode > Versioning.OptimisticLock.Version)
				throw new MappingException(string.Format("optimistic-lock=all|dirty not supported for joined-subclass mappings [{0}]", EntityName));

			#endregion

			#region MULTITABLES
			int idColumnSpan = IdentifierColumnSpan;

			List<string> tables = new List<string>();
			List<string[]> keyColumns = new List<string[]>();
			List<bool> cascadeDeletes = new List<bool>();
			IEnumerator<IKeyValue> kiter = persistentClass.KeyClosureIterator.GetEnumerator();
			foreach (Table tab in persistentClass.TableClosureIterator)
			{
				kiter.MoveNext();
				IKeyValue key = kiter.Current;
				string tabname = tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				tables.Add(tabname);

				List<string> keyCols = new List<string>(idColumnSpan);
				IEnumerable<Column> enumerableKCols = new SafetyEnumerable<Column>(key.ColumnIterator);
				foreach (Column kcol in enumerableKCols)
					keyCols.Add(kcol.GetQuotedName(factory.Dialect));

				keyColumns.Add(keyCols.ToArray());
				cascadeDeletes.Add(key.IsCascadeDeleteEnabled && factory.Dialect.SupportsCascadeDelete);				
			}
			naturalOrderTableNames = tables.ToArray();
			naturalOrderTableKeyColumns = keyColumns.ToArray();
			naturalOrderCascadeDeleteEnabled = cascadeDeletes.ToArray();

			List<string> subtables = new List<string>();
			List<bool> isConcretes = new List<bool>();
			keyColumns = new List<string[]>();
			foreach (Table tab in persistentClass.SubclassTableClosureIterator)
			{
				isConcretes.Add(persistentClass.IsClassOrSuperclassTable(tab));
				string tabname = tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				subtables.Add(tabname);
				List<string> key = new List<string>(idColumnSpan);
				foreach (Column column in tab.PrimaryKey.ColumnIterator)
					key.Add(column.GetQuotedName(factory.Dialect));

				keyColumns.Add(key.ToArray());				
			}
			subclassTableNameClosure = subtables.ToArray();
			subclassTableKeyColumnClosure = keyColumns.ToArray();
			isClassOrSuperclassTable = isConcretes.ToArray();

			constraintOrderedTableNames = new string[subclassTableNameClosure.Length];
			constraintOrderedKeyColumnNames = new string[subclassTableNameClosure.Length][];
			int currentPosition = 0;
			for (int i = subclassTableNameClosure.Length - 1; i >= 0; i--, currentPosition++)
			{
				constraintOrderedTableNames[currentPosition] = subclassTableNameClosure[i];
				constraintOrderedKeyColumnNames[currentPosition] = subclassTableKeyColumnClosure[i];
			}

			tableSpan = naturalOrderTableNames.Length;
			tableNames = Reverse(naturalOrderTableNames);
			tableKeyColumns = Reverse(naturalOrderTableKeyColumns);
			Reverse(subclassTableNameClosure, tableSpan);
			Reverse(subclassTableKeyColumnClosure, tableSpan);

			spaces = ArrayHelper.Join(tableNames, persistentClass.SynchronizedTables.ToArray());

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

			PersistentClass pc = persistentClass;
			int jk = tableSpan - 1;
			while (pc != null)
			{
				customSQLInsert[jk] = pc.CustomSQLInsert;
				insertCallable[jk] = customSQLInsert[jk] != null && pc.IsCustomInsertCallable;
				insertResultCheckStyles[jk] = pc.CustomSQLInsertCheckStyle
											  ??
											  ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLInsert[jk], insertCallable[jk]);
				customSQLUpdate[jk] = pc.CustomSQLUpdate;
				updateCallable[jk] = customSQLUpdate[jk] != null && pc.IsCustomUpdateCallable;
				updateResultCheckStyles[jk] = pc.CustomSQLUpdateCheckStyle
											  ??
											  ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLUpdate[jk], updateCallable[jk]);
				customSQLDelete[jk] = pc.CustomSQLDelete;
				deleteCallable[jk] = customSQLDelete[jk] != null && pc.IsCustomDeleteCallable;
				deleteResultCheckStyles[jk] = pc.CustomSQLDeleteCheckStyle
											  ??
											  ExecuteUpdateResultCheckStyle.DetermineDefault(customSQLDelete[jk], deleteCallable[jk]);
				jk--;
				pc = pc.Superclass;
			}
			if (jk != -1)
			{
				throw new AssertionFailure("Tablespan does not match height of joined-subclass hierarchy.");
			}

			#endregion

			#region PROPERTIES

			int hydrateSpan = PropertySpan;
			naturalOrderPropertyTableNumbers = new int[hydrateSpan];
			propertyTableNumbers = new int[hydrateSpan];
			int i2 = 0;
			foreach (Property prop in persistentClass.PropertyClosureIterator)
			{
				string tabname = prop.Value.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				propertyTableNumbers[i2] = GetTableId(tabname, tableNames);
				naturalOrderPropertyTableNumbers[i2] = GetTableId(tabname, naturalOrderTableNames);
				i2++;
			}

			// subclass closure properties
			List<int> columnTableNumbers = new List<int>();
			List<int> formulaTableNumbers = new List<int>();
			List<int> propTableNumbers = new List<int>();
			foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
			{
				Table tab = prop.Value.Table;
				string tabname = tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
				int tabnum = GetTableId(tabname, subclassTableNameClosure);
				propTableNumbers.Add(tabnum);

				foreach (ISelectable thing in prop.ColumnIterator)
				{
					if (thing.IsFormula)
						formulaTableNumbers.Add(tabnum);
					else
						columnTableNumbers.Add(tabnum);
				}
			}

			subclassColumnTableNumberClosure = columnTableNumbers.ToArray();
			subclassPropertyTableNumberClosure = propTableNumbers.ToArray();
			subclassFormulaTableNumberClosure = formulaTableNumbers.ToArray();
			#endregion

			#region SUBCLASSES

			int subclassSpan = persistentClass.SubclassSpan + 1;
			subclassClosure = new string[subclassSpan];
			subclassClosure[subclassSpan - 1] = EntityName;
			if (persistentClass.IsPolymorphic)
			{
				subclassesByDiscriminatorValue[discriminatorValue] = EntityName;
				discriminatorValues = new string[subclassSpan];
				discriminatorValues[subclassSpan - 1] = discriminatorSQLString;
				notNullColumnTableNumbers = new int[subclassSpan];
				int id =
					GetTableId(
						persistentClass.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName,
															   factory.Settings.DefaultSchemaName), subclassTableNameClosure);
				notNullColumnTableNumbers[subclassSpan - 1] = id;
				notNullColumnNames = new string[subclassSpan];
				notNullColumnNames[subclassSpan - 1] = subclassTableKeyColumnClosure[id][0]; 
				//( (Column) model.getTable().getPrimaryKey().getColumnIterator().next() ).getName();
			}
			else
			{
				discriminatorValues = null;
				notNullColumnTableNumbers = null;
				notNullColumnNames = null;
			}

			int k2 = 0;
			foreach (Subclass sc in persistentClass.SubclassIterator)
			{
				subclassClosure[k2] = sc.EntityName;
				try
				{
					if (persistentClass.IsPolymorphic)
					{
						// we now use subclass ids that are consistent across all
						// persisters for a class hierarchy, so that the use of 
						// "foo.class = Bar" works in HQL
						int subclassId = sc.SubclassId; //new Integer(k+1);
						subclassesByDiscriminatorValue[subclassId] = sc.EntityName;
						discriminatorValues[k2] = subclassId.ToString();
						int id =
							GetTableId(
								sc.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName,
														  factory.Settings.DefaultSchemaName), subclassTableNameClosure);
						notNullColumnTableNumbers[k2] = id;
						notNullColumnNames[k2] = subclassTableKeyColumnClosure[id][0]; 
						//( (Column) sc.getTable().getPrimaryKey().getColumnIterator().next() ).getName();
					}
				}
				catch (Exception e)
				{
					throw new MappingException("Error parsing discriminator value", e);
				}
				k2++;				
			}

			#endregion

			InitLockers();

			InitSubclassPropertyAliasesMap(persistentClass);

			PostConstruct(mapping);
		}
示例#4
0
		/// <summary>
		/// Return the names of all persistent (mapped) classes that extend or implement the
		/// given class or interface, accounting for implicit/explicit polymorphism settings
		/// and excluding mapped subclasses/joined-subclasses of other classes in the result.
		/// </summary>
		public string[] GetImplementors(string entityOrClassName)
		{
			string[] knownMap;
			if(entityNameImplementorsMap.TryGetValue(entityOrClassName,out knownMap))
			{
				return knownMap;
			}
			System.Type clazz = null;

			// NH Different implementation for performance: a class without at least a namespace sure can't be found by reflection
			if (entityOrClassName.IndexOf('.') > 0)
			{
				IEntityPersister checkPersister;
				// NH Different implementation: we have better performance checking, first of all, if we know the class
				// and take the System.Type directly from the persister (className have high probability to be entityName at least using Criteria or Linq)
				if (entityPersisters.TryGetValue(entityOrClassName, out checkPersister))
				{
					if(!checkPersister.EntityMetamodel.HasPocoRepresentation)
					{
						// we found the persister but it is a dynamic entity without class
						knownMap = new[] { entityOrClassName };
						entityNameImplementorsMap[entityOrClassName] = knownMap;
						return knownMap;
					}
					// NH : take care with this because we are forcing the Poco EntityMode
					clazz = checkPersister.GetMappedClass(EntityMode.Poco);
				}

				if (clazz == null)
				{
					try
					{
						clazz = ReflectHelper.ClassForFullNameOrNull(entityOrClassName);
					}
					catch (Exception)
					{
						clazz = null;
					}
				}
			}

			if (clazz == null)
			{
				// try to get the class from imported names
				string importedName = GetImportedClassName(entityOrClassName);
				if (importedName != null)
				{
					clazz = System.Type.GetType(importedName, false);
				}
			}

			if (clazz == null)
			{
				knownMap = new[] { entityOrClassName };
				entityNameImplementorsMap[entityOrClassName] = knownMap;
				return knownMap; //for a dynamic-class
			}

			var results = new List<string>();
			foreach (var q in entityPersisters.Values.OfType<IQueryable>())
			{
				string registeredEntityName = q.EntityName;
				// NH: as entity-name we are using the FullName but in HQL we allow just the Name, the class is mapped even when its FullName match the entity-name
				bool isMappedClass = entityOrClassName.Equals(registeredEntityName) || clazz.FullName.Equals(registeredEntityName);
				if (q.IsExplicitPolymorphism)
				{
					if (isMappedClass)
					{
						knownMap = new[] { registeredEntityName };
						entityNameImplementorsMap[entityOrClassName] = knownMap;
						return knownMap; // NOTE EARLY EXIT
					}
				}
				else
				{
					if (isMappedClass)
					{
						results.Add(registeredEntityName);
					}
					else
					{
						if (IsMatchingImplementor(entityOrClassName, clazz, q))
						{
							bool assignableSuperclass;
							if (q.IsInherited)
							{
								System.Type mappedSuperclass = GetEntityPersister(q.MappedSuperclass).GetMappedClass(EntityMode.Poco);
								assignableSuperclass = clazz.IsAssignableFrom(mappedSuperclass);
							}
							else
							{
								assignableSuperclass = false;
							}
							if (!assignableSuperclass)
							{
								results.Add(registeredEntityName);
							}
						}
					}
				}
			}
			knownMap = results.ToArray();
			entityNameImplementorsMap[entityOrClassName] = knownMap;
			return knownMap;
		}
		public UnionSubclassEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache, 
			ISessionFactoryImplementor factory, IMapping mapping):base(persistentClass, cache, factory)
		{
			if (IdentifierGenerator is IdentityGenerator)
			{
				throw new MappingException("Cannot use identity column key generation with <union-subclass> mapping for: " + EntityName);
			}

			// TABLE

			tableName =
				persistentClass.Table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName,
				                                       factory.Settings.DefaultSchemaName);

			#region Custom SQL

			SqlString sql;
			bool callable;
			ExecuteUpdateResultCheckStyle checkStyle;

			sql = persistentClass.CustomSQLInsert;
			callable = sql != null && persistentClass.IsCustomInsertCallable;
			checkStyle = sql == null
			             	? ExecuteUpdateResultCheckStyle.Count
			             	: (persistentClass.CustomSQLInsertCheckStyle
			             	   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
			customSQLInsert = new SqlString[] { sql };
			insertCallable = new bool[] { callable };
			insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

			sql = persistentClass.CustomSQLUpdate;
			callable = sql != null && persistentClass.IsCustomUpdateCallable;
			checkStyle = sql == null
			             	? ExecuteUpdateResultCheckStyle.Count
			             	: (persistentClass.CustomSQLUpdateCheckStyle
			             	   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
			customSQLUpdate = new SqlString[] { sql };
			updateCallable = new bool[] { callable };
			updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

			sql = persistentClass.CustomSQLDelete;
			callable = sql != null && persistentClass.IsCustomDeleteCallable;
			checkStyle = sql == null
			             	? ExecuteUpdateResultCheckStyle.Count
			             	: (persistentClass.CustomSQLDeleteCheckStyle
			             	   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
			customSQLDelete = new SqlString[] { sql };
			deleteCallable = new bool[] { callable };
			deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

			#endregion

			discriminatorValue = persistentClass.SubclassId;
			discriminatorSQLValue = persistentClass.SubclassId.ToString();

			#region PROPERTIES

			int subclassSpan = persistentClass.SubclassSpan + 1;
			subclassClosure = new string[subclassSpan];
			subclassClosure[0] = EntityName;

			#endregion

			#region SUBCLASSES

			subclassByDiscriminatorValue[persistentClass.SubclassId] = persistentClass.EntityName;
			if (persistentClass.IsPolymorphic)
			{
				int k = 1;
				foreach (Subclass sc in persistentClass.SubclassIterator)
				{
					subclassClosure[k++] = sc.EntityName;
					subclassByDiscriminatorValue[sc.SubclassId] = sc.EntityName;
				}
			}

			#endregion

			#region SPACES
			//TODO: i'm not sure, but perhaps we should exclude abstract denormalized tables?

			int spacesSize = 1 + persistentClass.SynchronizedTables.Count;
			spaces = new string[spacesSize];
			spaces[0] = tableName;
			IEnumerator<string> iSyncTab = persistentClass.SynchronizedTables.GetEnumerator();
			for (int i = 1; i < spacesSize; i++)
			{
				iSyncTab.MoveNext();
				spaces[i] = iSyncTab.Current;
			}

			HashedSet<string> subclassTables = new HashedSet<string>();
			foreach (Table table in persistentClass.SubclassTableClosureIterator)
			{
				subclassTables.Add(
					table.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName));
			}
			subclassSpaces = new string[subclassTables.Count];
			subclassTables.CopyTo(subclassSpaces, 0);

			subquery = GenerateSubquery(persistentClass, mapping);

			if (IsMultiTable)
			{
				int idColumnSpan = IdentifierColumnSpan;
				List<string> tableNames = new List<string>();
				List<string[]> keyColumns = new List<string[]>();
				if (!IsAbstract)
				{
					tableNames.Add(tableName);
					keyColumns.Add(IdentifierColumnNames);
				}
				foreach (Table tab in persistentClass.SubclassTableClosureIterator)
				{
					if (!tab.IsAbstractUnionTable)
					{
						string _tableName =
							tab.GetQualifiedName(factory.Dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);
						tableNames.Add(_tableName);

						List<string> key = new List<string>(idColumnSpan);
						foreach (Column column in tab.PrimaryKey.ColumnIterator)
							key.Add(column.GetQuotedName(factory.Dialect));

						keyColumns.Add(key.ToArray());
					}					
				}

				constraintOrderedTableNames = tableNames.ToArray();
				constraintOrderedKeyColumnNames = keyColumns.ToArray();
			}
			else
			{
				constraintOrderedTableNames = new string[] { tableName };
				constraintOrderedKeyColumnNames = new string[][] { IdentifierColumnNames };
			}
			#endregion

			InitLockers();

			InitSubclassPropertyAliasesMap(persistentClass);

			PostConstruct(mapping);
		}
		protected internal virtual SqlString GenerateLazySelectString()
		{
			if (!entityMetamodel.HasLazyProperties)
				return null;

			HashedSet<int> tableNumbers = new HashedSet<int>();
			List<int> columnNumbers = new List<int>();
			List<int> formulaNumbers = new List<int>();
			for (int i = 0; i < lazyPropertyNames.Length; i++)
			{
				// all this only really needs to consider properties
				// of this class, not its subclasses, but since we
				// are reusing code used for sequential selects, we
				// use the subclass closure
				int propertyNumber = GetSubclassPropertyIndex(lazyPropertyNames[i]);

				int tableNumber = GetSubclassPropertyTableNumber(propertyNumber);
				tableNumbers.Add(tableNumber);

				int[] colNumbers = subclassPropertyColumnNumberClosure[propertyNumber];
				for (int j = 0; j < colNumbers.Length; j++)
				{
					if (colNumbers[j] != -1)
					{
						columnNumbers.Add(colNumbers[j]);
					}
				}
				int[] formNumbers = subclassPropertyFormulaNumberClosure[propertyNumber];
				for (int j = 0; j < formNumbers.Length; j++)
				{
					if (formNumbers[j] != -1)
					{
						formulaNumbers.Add(formNumbers[j]);
					}
				}
			}

			if (columnNumbers.Count == 0 && formulaNumbers.Count == 0)
			{
				// only one-to-one is lazy fetched
				return null;
			}

			return RenderSelect(tableNumbers.ToArray(), columnNumbers.ToArray(), formulaNumbers.ToArray());
		}
		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);
		}
		/// <summary>
		/// Return the names of all persistent (mapped) classes that extend or implement the
		/// given class or interface, accounting for implicit/explicit polymorphism settings
		/// and excluding mapped subclasses/joined-subclasses of other classes in the result.
		/// </summary>
		public string[] GetImplementors(string className)
		{
			System.Type clazz = null;

			// NH Different implementation for performance: a class without at least a namespace sure can't be found by reflection
			if (className.IndexOf('.') > 0)
			{
				IEntityPersister checkPersister;
				// NH Different implementation: we have better performance checking, first of all, if we know the class
				// and take the System.Type directly from the persister (className have high probability to be entityName)
				if (entityPersisters.TryGetValue(className, out checkPersister))
				{
					if(!checkPersister.EntityMetamodel.HasPocoRepresentation)
					{
						// we found the persister but it is a dynamic entity without class
						return new[] { className };
					}
					// NH : take care with this because we are forcing the Poco EntityMode
					clazz = checkPersister.GetMappedClass(EntityMode.Poco);
				}

				if (clazz == null)
				{
					try
					{
						clazz = ReflectHelper.ClassForFullName(className);
					}
					catch (Exception)
					{
						clazz = null;
					}
				}
			}

			if (clazz == null)
			{
				return new[] {className}; //for a dynamic-class
			}

			List<string> results = new List<string>();
			foreach (IEntityPersister p in entityPersisters.Values)
			{
				IQueryable q = p as IQueryable;
				if (q != null)
				{
					string testClassName = q.EntityName;
					bool isMappedClass = className.Equals(testClassName);
					if (q.IsExplicitPolymorphism)
					{
						if (isMappedClass)
						{
							return new string[] {testClassName}; // NOTE EARLY EXIT
						}
					}
					else
					{
						if (isMappedClass)
						{
							results.Add(testClassName);
						}
						else
						{
							System.Type mappedClass = q.GetMappedClass(EntityMode.Poco);
							if (mappedClass != null && clazz.IsAssignableFrom(mappedClass))
							{
								bool assignableSuperclass;
								if (q.IsInherited)
								{
									System.Type mappedSuperclass = GetEntityPersister(q.MappedSuperclass).GetMappedClass(EntityMode.Poco);
									assignableSuperclass = clazz.IsAssignableFrom(mappedSuperclass);
								}
								else
								{
									assignableSuperclass = false;
								}
								if (!assignableSuperclass)
								{
									results.Add(testClassName);
								}
							}
						}
					}
				}
			}
			return results.ToArray();
		}
示例#9
0
		/// <summary>
		/// Generate DDL for creating tables
		/// </summary>
		/// <param name="dialect"></param>
		public string[] GenerateSchemaCreationScript(Dialect.Dialect dialect)
		{
			SecondPassCompile();

			string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
			string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);

			List<string> script = new List<string>();

			foreach (Table table in TableMappings)
			{
				if (table.IsPhysicalTable)
				{
					script.Add(table.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
					script.AddRange(table.SqlCommentStrings(dialect, defaultCatalog, defaultSchema));
				}
			}

			foreach (Table table in TableMappings)
			{
				if (table.IsPhysicalTable)
				{
					if (!dialect.SupportsUniqueConstraintInCreateAlterTable)
					{
						foreach (UniqueKey uk in table.UniqueKeyIterator)
						{
							string constraintString = uk.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema);
							if (constraintString != null)
								script.Add(constraintString);
						}
					}

					foreach (Index index in table.IndexIterator)
						script.Add(index.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));

					if (dialect.HasAlterTable)
					{
						foreach (ForeignKey fk in table.ForeignKeyIterator)
						{
							if (fk.HasPhysicalConstraint)
								script.Add(fk.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
						}
					}
				}
			}

			IEnumerable<IPersistentIdentifierGenerator> pIDg = IterateGenerators(dialect);
			foreach (IPersistentIdentifierGenerator idGen in pIDg)
				script.AddRange(idGen.SqlCreateStrings(dialect));

			foreach (IAuxiliaryDatabaseObject auxDbObj in auxiliaryDatabaseObjects)
			{
				if (auxDbObj.AppliesToDialect(dialect))
				{
					script.Add(auxDbObj.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
				}
			}

			return script.ToArray();
		}
示例#10
0
		/// <summary>
		/// Generate DDL for dropping tables
		/// </summary>
		/// <seealso cref="NHibernate.Tool.hbm2ddl.SchemaExport" />
		public string[] GenerateDropSchemaScript(Dialect.Dialect dialect)
		{
			SecondPassCompile();

			string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
			string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);

			List<string> script = new List<string>();

			// drop them in reverse order in case db needs it done that way...
			for (int i = auxiliaryDatabaseObjects.Count - 1; i >= 0; i--)
			{
				IAuxiliaryDatabaseObject auxDbObj = auxiliaryDatabaseObjects[i];
				if (auxDbObj.AppliesToDialect(dialect))
				{
					script.Add(auxDbObj.SqlDropString(dialect, defaultCatalog, defaultSchema));
				}
			}

			if (dialect.DropConstraints)
			{
				foreach (Table table in TableMappings)
				{
					if (table.IsPhysicalTable)
					{
						foreach (ForeignKey fk in table.ForeignKeyIterator)
						{
							if (fk.HasPhysicalConstraint)
								script.Add(fk.SqlDropString(dialect, defaultCatalog, defaultSchema));
						}
					}
				}
			}

			foreach (Table table in TableMappings)
			{
				if (table.IsPhysicalTable)
					script.Add(table.SqlDropString(dialect, defaultCatalog, defaultSchema));
			}

			IEnumerable<IPersistentIdentifierGenerator> pIDg = IterateGenerators(dialect);
			foreach (IPersistentIdentifierGenerator idGen in pIDg)
			{
				string dropString = idGen.SqlDropString(dialect);
				if (dropString != null)
					script.Add(dropString);
			}

			return script.ToArray();
		}
        private InvalidValue[] GetInvalidValues(object entity, ISet circularityState)
        {
            if (entity == null || circularityState.Contains(entity))
            {
                return EMPTY_INVALID_VALUE_ARRAY; //Avoid circularity
            }
            else
            {
                circularityState.Add(entity);
            }

            if (!entityType.IsInstanceOfType(entity))
            {
                throw new ArgumentException("not an instance of: " + entity.GetType());
            }

            List<InvalidValue> results = new List<InvalidValue>();

            //Entity Validation
            foreach (IValidator validator in entityValidators)
            {
                var constraintContext = new ConstraintValidatorContext(null,defaultInterpolator.GetAttributeMessage(validator));
                if (!validator.IsValid(entity, constraintContext))
                {
                    new InvalidMessageTransformer(constraintContext, results, entityType, null, entity, entity, validator, defaultInterpolator, userInterpolator).Transform();
                }
            }

            results.AddRange(MembersValidation(entity, null));

            //Child validation
            for (int i = 0; i < childGetters.Count; i++)
            {
                MemberInfo member = childGetters[i];

                if (NHibernateUtil.IsPropertyInitialized(entity, member.Name))
                {
                    object value = TypeUtils.GetMemberValue(entity, member);

                    if (value != null && NHibernateUtil.IsInitialized(value))
                    {
                        MakeChildValidation(value, entity, member, circularityState, results);
                    }
                }
            }
            return results.ToArray();
        }
        /// <summary>
        /// Apply constraints of a particular property value of a entity type and return all the failures.
        /// The InvalidValue objects returns return null for InvalidValue#Entity and InvalidValue#RootEntity.
        /// Note: this is not recursive.
        /// </summary>
        /// <param name="propertyName">Name of the property or field to validate</param>
        /// <param name="value">Real value to validate. Is not an entity instance.</param>
        /// <returns></returns>
        public InvalidValue[] GetPotentialInvalidValues(string propertyName, object value)
        {
            List<InvalidValue> results = new List<InvalidValue>();

            int getterFound = 0;
            for (int i = 0; i < memberValidators.Count; i++)
            {
                MemberInfo getter = memberGetters[i];
                if (getter.Name.Equals(propertyName))
                {
                    getterFound++;
                    IValidator validator = memberValidators[i];

                    var constraintContext = new ConstraintValidatorContext(propertyName, defaultInterpolator.GetAttributeMessage(validator));

                    if (!validator.IsValid(value, null))
                        new InvalidMessageTransformer(constraintContext, results, entityType, propertyName, value, null, validator, defaultInterpolator, userInterpolator).Transform();

                }
            }

            if (getterFound == 0 && TypeUtils.GetPropertyOrField(entityType, propertyName) == null)
            {
                throw new TargetException(
                    string.Format("The property or field '{0}' was not found in class {1}", propertyName, entityType.FullName));
            }

            return results.ToArray();
        }
        private static IDictionary<string, string>[] GetDirectoryProperties(Configuration cfg, string directoryProviderName)
        {
            IDictionary<string, string> props = cfg.Properties;
            string indexName = LUCENE_PREFIX + directoryProviderName;
            IDictionary<string, string> defaultProperties = new Dictionary<string, string>();
            List<IDictionary<string, string>> indexSpecificProps = new List<IDictionary<string, string>>();
            IDictionary<string, string> indexSpecificDefaultProps = new Dictionary<string, string>();

            foreach (KeyValuePair<string, string> entry in props)
            {
                string key = entry.Key;
                if (key.StartsWith(LUCENE_DEFAULT))
                {
                    defaultProperties[key.Substring(LUCENE_DEFAULT.Length)] = entry.Value;
                }
                else if (key.StartsWith(indexName))
                {
                    string suffixedKey = key.Substring(indexName.Length + 1);
                    int nextDoc = suffixedKey.IndexOf('.');
                    int index = -1;
                    if (nextDoc != -1)
                    {
                        string potentialNbr = suffixedKey.Substring(0, nextDoc);
                        if (!int.TryParse(potentialNbr, out index))
                        {
                            index = -1;
                        }
                    }

                    if (index != -1)
                    {
                        indexSpecificDefaultProps[suffixedKey] = entry.Value;
                    }
                    else
                    {
                        string finalKeyName = suffixedKey.Substring(nextDoc + 1);

                        // Ignore sharding strategy properties
                        if (!finalKeyName.StartsWith(SHARDING_STRATEGY))
                        {
                            EnsureListSize(indexSpecificProps, index + 1);
                            IDictionary<string, string> propertiesForIndex = indexSpecificProps[index];
                            if (propertiesForIndex == null)
                            {
                                propertiesForIndex = new Dictionary<string, string>();
                                indexSpecificProps[index] = propertiesForIndex;
                            }

                            propertiesForIndex[finalKeyName] = entry.Value;
                        }
                    }
                }
            }

            int nbrOfShards = -1;
            if (indexSpecificDefaultProps.ContainsKey(NBR_OF_SHARDS))
            {
                string nbrOfShardsString = indexSpecificDefaultProps[NBR_OF_SHARDS];
                if (!string.IsNullOrEmpty(nbrOfShardsString))
                {
                    if (!int.TryParse(nbrOfShardsString, out nbrOfShards))
                    {
                        throw new SearchException(indexName + "." + NBR_OF_SHARDS + " is not a number");
                    }
                }
            }

            // Original java doesn't copy properties from the defaults!
            foreach (KeyValuePair<string, string> prop in defaultProperties)
            {
                if (!indexSpecificDefaultProps.ContainsKey(prop.Key))
                {
                    indexSpecificDefaultProps.Add(prop);
                }
            }

            if (nbrOfShards <= 0 && indexSpecificDefaultProps.Count == 0)
            {
                // No Shard (A sharded subindex has to have at least one property)
                return new IDictionary<string, string>[] { indexSpecificDefaultProps };
            }

            // Sharded
            nbrOfShards = nbrOfShards > indexSpecificDefaultProps.Count ? nbrOfShards : indexSpecificDefaultProps.Count;
            EnsureListSize(indexSpecificProps, nbrOfShards);

            for (int index = 0; index < nbrOfShards; index++)
            {
                if (indexSpecificProps[index] == null)
                {
                    indexSpecificProps[index] = new Dictionary<string, string>(indexSpecificDefaultProps);
                }

                // Original java doesn't copy properties from the defaults!
                foreach (KeyValuePair<string, string> prop in indexSpecificDefaultProps)
                {
                    if (!indexSpecificProps[index].ContainsKey(prop.Key))
                    {
                        indexSpecificProps[index].Add(prop);
                    }
                }
            }

            return indexSpecificProps.ToArray();
        }
        protected virtual IEnumerable<Attribute> GetEntityMemberAttributes(PropertyDescriptor propertyDescriptor)
        {
            if (_classMetadata == null)
                return null;
            var attributes = new List<Attribute>();

            //KeyAttributes
            if (_classMetadata.Identifier != null)
            {
                foreach (Column id in _identifierCols)
                {
                    if (id.Name == propertyDescriptor.Name)
                    {
                        if (propertyDescriptor.Attributes[typeof(KeyAttribute)] == null)
                        {
                            attributes.Add(new KeyAttribute());
                        }
                        if (propertyDescriptor.Attributes[typeof(EditableAttribute)] == null)
                        {
                            //An identifier is not editable, sometimes anyway it allow an initial value
                            var editable = new EditableAttribute(false);
                            if (id.Value is SimpleValue)
                                editable.AllowInitialValue =
                                    "assigned".Equals(((SimpleValue)id.Value).IdentifierGeneratorStrategy,
                                                      StringComparison.InvariantCultureIgnoreCase);
                            attributes.Add(editable);
                        }
                        break;
                    }
                }
            }
            Property member = _classMetadata.PropertyIterator.FirstOrDefault(x => x.Name == propertyDescriptor.Name);
            if (member == null)             //If ther's no mapping in nhibernate... 
                return attributes;
            //Required
            if ((!member.IsNullable) &&
                (propertyDescriptor.PropertyType.IsValueType &&
                 (propertyDescriptor.Attributes[typeof(RequiredAttribute)] == null)))
            {

                attributes.Add(new RequiredAttribute());
            }
            //Association
            if (member.Type.IsAssociationType &&
                (propertyDescriptor.Attributes[typeof(AssociationAttribute)] == null))
            {
                string name;
                string thisKey = "";
                string otherkey = "";
                if (member.Type.IsCollectionType)
                {
                    name = propertyDescriptor.ComponentType.FullName + "_" + member.Name;

                    if (member.Type.ReturnedClass.GetGenericArguments().Length != 1)
                    {
                        throw new Exception(
                            String.Format(
                                "The property {0} is not a generic collection as expected (like IList<T>)...",
                                member.Name));
                    }
                    Type targetClassType = member.Type.ReturnedClass.GetGenericArguments()[0];

                    foreach (Column col in _identifierCols)
                    {
                        thisKey += (thisKey != "" ? ", " : "") + col.Name;

                        //*****Naming convention****
                        //Here I'm assuming that the name of each field in the type that holds the foreign key observe
                        //the following structure: 

                        string field = member.Name.Replace(Inflector.Pluralize(targetClassType.Name), "") +
                            propertyDescriptor.ComponentType.Name + "_" + col.Name;

                        otherkey += (otherkey != "" ? ", " : "") + field;

                        if (targetClassType.GetProperties(BindingFlags.Public | BindingFlags.Instance).SingleOrDefault(x => x.Name == field) == null)
                            throw new Exception(String.Format("The class {0} doesn't contain a Property named {1}",
                                                targetClassType.Name, field));
                    }

                }
                else //Member is a class type
                {
                    //Key could be composite, cycle every identifier on "the other side"
                    PersistentClass otherMappingClass = _nhibernateConfiguration.GetClassMapping(member.Type.ReturnedClass);
                    foreach (Column col in otherMappingClass.Key.ColumnIterator)
                    {
                        //Naming Convention:
                        //The name of each foreign key field be MUST BE the name of the class field + "_" + the name of the key field in the targetclass
                        thisKey += (thisKey != "" ? ", " : "") + member.Name + "_" + col.Name;
                        otherkey += (otherkey != "" ? ", " : "") + col.Name;
                    }

                    //Check: this name MUST ALWAYS BE the same on the both side of a bi-directional association
                    name = member.Type.ReturnedClass.FullName
                        + "_" + Inflector.Pluralize(member.PersistentClass.NodeName);
                }

                //CHECK: When do you want to add an IncludeAttribute ?
                if (!_classMetadata.IsLazy)
                {
                    var incAttr = new IncludeAttribute();
                    attributes.Add(incAttr);
                }

                var attribute = new AssociationAttribute(
                    name,
                    thisKey,
                    otherkey
                    );
                Type fromParent = ForeignKeyDirection.ForeignKeyFromParent.GetType();
                attribute.IsForeignKey =
                    fromParent.IsInstanceOfType(((IAssociationType)member.Type).ForeignKeyDirection);
                attributes.Add(attribute);
            }
            //RoundtripOriginal
            if (member == _classMetadata.Version)
                attributes.Add(new RoundtripOriginalAttribute());
            return attributes.ToArray();
        }
		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 properies fetching for {0} beacuse 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 properies fetching for {0} beacuse 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))
				{
					log.Warn("entity [" + 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)
			{
				throw new MappingException("optimistic-lock setting requires dynamic-update=\"true\": " + type.FullName);
			}

			hasCollections = foundCollection;
			hasMutableProperties = foundMutable;

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

			tuplizerMapping = new EntityEntityModeToTuplizerMapping(persistentClass, this);
		}
        private IList<OrderMaster> GetOrders(string ids, string orders)
        {

            string[] idArray = ids.Split(',');
            string[] orderArray = orders.Split(',');
            if (idArray.Length == 0)
            {
                throw new BusinessException("请选择打印明细。");
            }
            string orderDetHql = string.Empty;
            string orderMstrHql = string.Empty;
            IList<object> idParm = new List<object>();
            IList<object> orderNoParm = new List<object>();
            int i = 0;
            foreach (string id in idArray)
            {
                if (orderDetHql == string.Empty)
                {
                    orderDetHql = "from OrderDetail as d where d.Id in (?";
                    orderMstrHql = "from OrderMaster as o where o.OrderNo in (?";
                }
                else
                {
                    orderDetHql += ", ?";
                    orderMstrHql += ",?";
                }
                idParm.Add(id);
                orderNoParm.Add(orderArray[i++]);
            }
            IList<OrderDetail> orderDetailList = base.genericMgr.FindAll<OrderDetail>(orderDetHql + ")", idParm.ToArray());
            IList<OrderMaster> orderMasterList = base.genericMgr.FindAll<OrderMaster>(orderMstrHql + ")", orderNoParm.ToArray());

            foreach (OrderMaster orderMaster in orderMasterList)
            {
                IList<OrderDetail> orderDetailByMaster = new List<OrderDetail>();
                foreach (OrderDetail orderDetail in orderDetailList)
                {
                    if (orderMaster.OrderNo == orderDetail.OrderNo)
                    {
                        orderDetailByMaster.Add(orderDetail);
                    }
                    else
                    {
                        continue;
                    }
                }
                orderMaster.OrderDetails = orderDetailByMaster;

            }

            return orderMasterList;

        }
示例#17
0
        private bool RetrieveUnpublishedPages()
        {
            // Check if user can manage content
            var allRoles = new List<string>(RootModuleConstants.UserRoles.AllRoles);
            if (!string.IsNullOrEmpty(cmsConfiguration.Security.FullAccessRoles))
            {
                allRoles.Add(cmsConfiguration.Security.FullAccessRoles);
            }

            var retrieveUnpublishedPages = securityService.IsAuthorized(RootModuleConstants.UserRoles.MultipleRoles(allRoles.ToArray()));
            return retrieveUnpublishedPages;
        }
        private SearchStatementModel PrepareSearchStatement(GridCommand command, OrderMasterSearchModel searchModel)
        {

            string whereStatement = "where exists (select 1 from OrderMaster as o where d.OrderNo=o.OrderNo and o.Type =" + (int)com.Sconit.CodeMaster.OrderType.Transfer + ""
                 + " and o.SubType = " + (int)com.Sconit.CodeMaster.OrderSubType.Normal
                 + " and o.Status  in (" + (int)com.Sconit.CodeMaster.OrderStatus.Submit+","+(int)com.Sconit.CodeMaster.OrderStatus.InProcess+")";
            if (searchModel.Priority != null)
            {
                whereStatement += " and o.Priority=" + searchModel.Priority + "";
            }
            whereStatement += ") and exists( select 1 from Custodian as c where c.Item=d.Item and c.Location=d.LocationFrom and c.UserCode='" + searchModel.Checker + "')";
            IList<object> param = new List<object>();

            HqlStatementHelper.AddLikeStatement("OrderNo", searchModel.OrderNo, HqlStatementHelper.LikeMatchMode.Start, "d", ref whereStatement, param);



            if (searchModel.DateFrom != null & searchModel.DateTo != null)
            {
                HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.DateFrom, searchModel.DateTo, "d", ref whereStatement, param);
            }
            else if (searchModel.DateFrom != null & searchModel.DateTo == null)
            {
                HqlStatementHelper.AddGeStatement("CreateDate", searchModel.DateFrom, "d", ref whereStatement, param);
            }
            else if (searchModel.DateFrom == null & searchModel.DateTo != null)
            {
                HqlStatementHelper.AddLeStatement("CreateDate", searchModel.DateTo, "d", ref whereStatement, param);
            }
            if (command.SortDescriptors.Count > 0)
            {
                if (command.SortDescriptors[0].Member == "OrderTypeDescription")
                {
                    command.SortDescriptors[0].Member = "Type";
                }
                else if (command.SortDescriptors[0].Member == "OrderPriorityDescription")
                {
                    command.SortDescriptors[0].Member = "Priority";
                }
                else if (command.SortDescriptors[0].Member == "OrderStatusDescription")
                {
                    command.SortDescriptors[0].Member = "Status";
                }
            }


            string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
            if (command.SortDescriptors.Count == 0)
            {
                sortingStatement = " order by d.CreateDate desc";
            }
            SearchStatementModel searchStatementModel = new SearchStatementModel();
            searchStatementModel.SelectCountStatement = selectCountStatement;
            searchStatementModel.SelectStatement = selectStatement;
            searchStatementModel.WhereStatement = whereStatement;
            searchStatementModel.SortingStatement = sortingStatement;
            searchStatementModel.Parameters = param.ToArray<object>();

            return searchStatementModel;
        }
		private SqlString GenerateSequentialSelect(ILoadable persister)
		{
			//note that this method could easily be moved up to BasicEntityPersister,
			//if we ever needed to reuse it from other subclasses

			//figure out which tables need to be fetched
			AbstractEntityPersister subclassPersister = (AbstractEntityPersister)persister;
			HashedSet<int> tableNumbers = new HashedSet<int>();
			string[] props = subclassPersister.PropertyNames;
			string[] classes = subclassPersister.PropertySubclassNames;
			for (int i = 0; i < props.Length; i++)
			{
				int propTableNumber = GetSubclassPropertyTableNumber(props[i], classes[i]);
				if (IsSubclassTableSequentialSelect(propTableNumber) && !IsSubclassTableLazy(propTableNumber))
				{
					tableNumbers.Add(propTableNumber);
				}
			}
			if ((tableNumbers.Count == 0))
				return null;

			//figure out which columns are needed
			List<int> columnNumbers = new List<int>();
			int[] columnTableNumbers = SubclassColumnTableNumberClosure;
			for (int i = 0; i < SubclassColumnClosure.Length; i++)
			{
				if (tableNumbers.Contains(columnTableNumbers[i]))
					columnNumbers.Add(i);
			}

			//figure out which formulas are needed
			List<int> formulaNumbers = new List<int>();
			int[] formulaTableNumbers = SubclassColumnTableNumberClosure;
			for (int i = 0; i < SubclassFormulaTemplateClosure.Length; i++)
			{
				if (tableNumbers.Contains(formulaTableNumbers[i]))
					formulaNumbers.Add(i);
			}

			//render the SQL
			return RenderSelect(ArrayHelper.ToIntArray(tableNumbers), columnNumbers.ToArray(), formulaNumbers.ToArray());
		}
示例#20
0
 public string[] GetMappingAssemblies()
 {
     List<string> s = new List<string>();
        foreach (MSBuild.BuildItem bi in assemblies)
        {
        s.Add(bi.Include);
        }
        return s.ToArray();
 }
示例#21
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.AssemblyQualifiedName;

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

			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>();

			#region temporary

			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];

			#endregion


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

			foreach (Mapping.Property prop in persistentClass.PropertyClosureIterator)
			{
				if (prop == persistentClass.Version)
				{
					tempVersionProperty = i;
					properties[i] = PropertyFactory.BuildVersionProperty(prop, lazyAvailable);
				}
				else
				{
					properties[i] = PropertyFactory.BuildStandardProperty(prop, lazyAvailable);
				}

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

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

				#region temporary
				bool lazyProperty = prop.IsLazy && lazyAvailable;
				if (lazyProperty)
					hasLazy = true;
				propertyLaziness[i] = lazyProperty;

				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 && !lazyProperty;
				propertyCheckability[i] = propertyUpdateability[i] ||
				                          (propertyTypes[i].IsAssociationType &&
				                           ((IAssociationType) propertyTypes[i]).IsAlwaysDirtyChecked);

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

				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 (hasLazyProperties) log.Info("lazy property fetching available for: " + name);

			lazy = persistentClass.IsLazy && 
				(!persistentClass.HasPocoRepresentation || !ReflectHelper.IsFinalClass(persistentClass.ProxyInterface));
			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))
				{
					log.Warn("entity [" + 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)
			{
				throw new MappingException("optimistic-lock setting requires dynamic-update=\"true\": " + type.FullName);
			}

			hasCollections = foundCollection;
			hasMutableProperties = foundMutable;

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

			tuplizerMapping = new EntityEntityModeToTuplizerMapping(persistentClass, this);
		}
        public ISlabInfo[] GetSlabInfoByTimeInterval(long aFrom, long aTo)
        {
            try {
                using (var session = NHibernateHelper.OpenSession()) {
                    var entitys = session.CreateCriteria(typeof(SlabInfoEntity))
                    .Add(Restrictions.Between("StartScanTime", aFrom, aTo))
                    .List<SlabInfoEntity>();

                    var results = new List<ISlabInfo>();
                    foreach (var entity in entitys) {
                        results.Add(new SlabInfoImpl {
                            Id = entity.Id,
                            Number = entity.Number,
                            StandartSizeId = entity.StandartSizeId,
                            StartScanTime = entity.StartScanTime,
                            EndScanTime = entity.EndScanTime
                        });
                    }

                    return results.ToArray();
                }
            }
            catch (Exception ex) {
                logger.Error("Ошибка при чтении SlabInfo: " + ex.Message);
                return null;
            }
        }
		protected AbstractEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
																			ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			isLazyPropertiesCacheable = persistentClass.IsLazyPropertiesCacheable;
			cacheEntryStructure = factory.Settings.IsStructuredCacheEntriesEnabled
															? (ICacheEntryStructure)new StructuredCacheEntry(this)
															: (ICacheEntryStructure)new UnstructuredCacheEntry();

			entityMetamodel = new EntityMetamodel(persistentClass, factory);

			if (persistentClass.HasPocoRepresentation)
			{
				//TODO: this is currently specific to pojos, but need to be available for all entity-modes
				foreach (Subclass subclass in persistentClass.SubclassIterator)
				{
					entityNameBySubclass[subclass.MappedClass] = subclass.EntityName;
				}
			}

			batchSize = persistentClass.BatchSize.HasValue ? persistentClass.BatchSize.Value : factory.Settings.DefaultBatchFetchSize;
			hasSubselectLoadableCollections = persistentClass.HasSubselectLoadableCollections;

			propertyMapping = new BasicEntityPropertyMapping(this);

			#region IDENTIFIER

			identifierColumnSpan = persistentClass.Identifier.ColumnSpan;
			rootTableKeyColumnNames = new string[identifierColumnSpan];
			identifierAliases = new string[identifierColumnSpan];

			rowIdName = persistentClass.RootTable.RowId;

			loaderName = persistentClass.LoaderName;

			// TODO NH: Not safe cast to Column
			int i = 0;
			foreach (Column col in persistentClass.Identifier.ColumnIterator)
			{
				rootTableKeyColumnNames[i] = col.GetQuotedName(factory.Dialect);
				identifierAliases[i] = col.GetAlias(factory.Dialect, persistentClass.RootTable);
				i++;
			}

			#endregion

			#region VERSION

			if (persistentClass.IsVersioned)
			{
				foreach (Column col in persistentClass.Version.ColumnIterator)
				{
					versionColumnName = col.GetQuotedName(factory.Dialect);
					break; //only happens once
				}
			}
			else
			{
				versionColumnName = null;
			}

			#endregion

			#region WHERE STRING

			sqlWhereString = !string.IsNullOrEmpty(persistentClass.Where) ? "( " + persistentClass.Where + ") " : null;
			sqlWhereStringTemplate = sqlWhereString == null
																? null
																: Template.RenderWhereStringTemplate(sqlWhereString, factory.Dialect,
																																		 factory.SQLFunctionRegistry);

			#endregion

			#region PROPERTIES

			// NH: see consistence with the implementation on EntityMetamodel where we are disabling lazy-properties for no lazy entities
			bool lazyAvailable = IsInstrumented(EntityMode.Poco) && entityMetamodel.IsLazy;

			int hydrateSpan = entityMetamodel.PropertySpan;
			propertyColumnSpans = new int[hydrateSpan];
			propertySubclassNames = new string[hydrateSpan];
			propertyColumnAliases = new string[hydrateSpan][];
			propertyColumnNames = new string[hydrateSpan][];
			propertyColumnFormulaTemplates = new string[hydrateSpan][];
			propertyUniqueness = new bool[hydrateSpan];
			propertySelectable = new bool[hydrateSpan];
			propertyColumnUpdateable = new bool[hydrateSpan][];
			propertyColumnInsertable = new bool[hydrateSpan][];
			var thisClassProperties = new HashSet<Property>();

			lazyProperties = new HashedSet<string>();
			List<string> lazyNames = new List<string>();
			List<int> lazyNumbers = new List<int>();
			List<IType> lazyTypes = new List<IType>();
			List<string[]> lazyColAliases = new List<string[]>();

			i = 0;
			bool foundFormula = false;
			foreach (Property prop in persistentClass.PropertyClosureIterator)
			{
				thisClassProperties.Add(prop);

				int span = prop.ColumnSpan;
				propertyColumnSpans[i] = span;
				propertySubclassNames[i] = prop.PersistentClass.EntityName;
				string[] colNames = new string[span];
				string[] colAliases = new string[span];
				string[] templates = new string[span];
				int k = 0;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					colAliases[k] = thing.GetAlias(factory.Dialect, prop.Value.Table);
					if (thing.IsFormula)
					{
						foundFormula = true;
						templates[k] = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					}
					else
					{
						colNames[k] = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
					}
					k++;
				}
				propertyColumnNames[i] = colNames;
				propertyColumnFormulaTemplates[i] = templates;
				propertyColumnAliases[i] = colAliases;

				if (lazyAvailable && prop.IsLazy)
				{
					lazyProperties.Add(prop.Name);
					lazyNames.Add(prop.Name);
					lazyNumbers.Add(i);
					lazyTypes.Add(prop.Value.Type);
					lazyColAliases.Add(colAliases);
				}

				propertyColumnUpdateable[i] = prop.Value.ColumnUpdateability;
				propertyColumnInsertable[i] = prop.Value.ColumnInsertability;

				propertySelectable[i] = prop.IsSelectable;

				propertyUniqueness[i] = prop.Value.IsAlternateUniqueKey;

				i++;
			}
			hasFormulaProperties = foundFormula;
			lazyPropertyColumnAliases = lazyColAliases.ToArray();
			lazyPropertyNames = lazyNames.ToArray();
			lazyPropertyNumbers = lazyNumbers.ToArray();
			lazyPropertyTypes = lazyTypes.ToArray();

			#endregion

			#region SUBCLASS PROPERTY CLOSURE

			List<string> columns = new List<string>();
			List<bool> columnsLazy = new List<bool>();
			List<string> aliases = new List<string>();
			List<string> formulas = new List<string>();
			List<string> formulaAliases = new List<string>();
			List<string> formulaTemplates = new List<string>();
			List<bool> formulasLazy = new List<bool>();
			List<IType> types = new List<IType>();
			List<string> names = new List<string>();
			List<string> classes = new List<string>();
			List<string[]> templates2 = new List<string[]>();
			List<string[]> propColumns = new List<string[]>();
			List<FetchMode> joinedFetchesList = new List<FetchMode>();
			List<CascadeStyle> cascades = new List<CascadeStyle>();
			List<bool> definedBySubclass = new List<bool>();
			List<int[]> propColumnNumbers = new List<int[]>();
			List<int[]> propFormulaNumbers = new List<int[]>();
			List<bool> columnSelectables = new List<bool>();
			List<bool> propNullables = new List<bool>();

			foreach (Property prop in persistentClass.SubclassPropertyClosureIterator)
			{
				names.Add(prop.Name);
				classes.Add(prop.PersistentClass.EntityName);
				bool isDefinedBySubclass = !thisClassProperties.Contains(prop);
				definedBySubclass.Add(isDefinedBySubclass);
				propNullables.Add(prop.IsOptional || isDefinedBySubclass); //TODO: is this completely correct?
				types.Add(prop.Type);

				string[] cols = new string[prop.ColumnSpan];
				string[] forms = new string[prop.ColumnSpan];
				int[] colnos = new int[prop.ColumnSpan];
				int[] formnos = new int[prop.ColumnSpan];
				int l = 0;
				bool lazy = prop.IsLazy && lazyAvailable;
				foreach (ISelectable thing in prop.ColumnIterator)
				{
					if (thing.IsFormula)
					{
						string template = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
						formnos[l] = formulaTemplates.Count;
						colnos[l] = -1;
						formulaTemplates.Add(template);
						forms[l] = template;
						formulas.Add(thing.GetText(factory.Dialect));
						formulaAliases.Add(thing.GetAlias(factory.Dialect));
						formulasLazy.Add(lazy);
					}
					else
					{
						string colName = thing.GetTemplate(factory.Dialect, factory.SQLFunctionRegistry);
						colnos[l] = columns.Count; //before add :-)
						formnos[l] = -1;
						columns.Add(colName);
						cols[l] = colName;
						aliases.Add(thing.GetAlias(factory.Dialect, prop.Value.Table));
						columnsLazy.Add(lazy);
						columnSelectables.Add(prop.IsSelectable);
					}
					l++;
				}
				propColumns.Add(cols);
				templates2.Add(forms);
				propColumnNumbers.Add(colnos);
				propFormulaNumbers.Add(formnos);

				joinedFetchesList.Add(prop.Value.FetchMode);
				cascades.Add(prop.CascadeStyle);
			}
			subclassColumnClosure = columns.ToArray();
			subclassColumnAliasClosure = aliases.ToArray();
			subclassColumnLazyClosure = columnsLazy.ToArray();
			subclassColumnSelectableClosure = columnSelectables.ToArray();

			subclassFormulaClosure = formulas.ToArray();
			subclassFormulaTemplateClosure = formulaTemplates.ToArray();
			subclassFormulaAliasClosure = formulaAliases.ToArray();
			subclassFormulaLazyClosure = formulasLazy.ToArray();

			subclassPropertyNameClosure = names.ToArray();
			subclassPropertySubclassNameClosure = classes.ToArray();
			subclassPropertyTypeClosure = types.ToArray();
			subclassPropertyNullabilityClosure = propNullables.ToArray();
			subclassPropertyFormulaTemplateClosure = templates2.ToArray();
			subclassPropertyColumnNameClosure = propColumns.ToArray();
			subclassPropertyColumnNumberClosure = propColumnNumbers.ToArray();
			subclassPropertyFormulaNumberClosure = propFormulaNumbers.ToArray();

			subclassPropertyCascadeStyleClosure = cascades.ToArray();
			subclassPropertyFetchModeClosure = joinedFetchesList.ToArray();

			propertyDefinedOnSubclass = definedBySubclass.ToArray();

			#endregion

			// Handle any filters applied to the class level
			filterHelper = new FilterHelper(persistentClass.FilterMap, factory.Dialect, factory.SQLFunctionRegistry);

			temporaryIdTableName = persistentClass.TemporaryIdTableName;
			temporaryIdTableDDL = persistentClass.TemporaryIdTableDDL;
		}
示例#24
0
        /// <summary>
        /// Loads available assemblies.
        /// </summary>
        internal static void LoadAssemblies()
        {
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                if (container == null)
                {
                    throw new CmsException("Better CMS dependencies container is not initialized.");
                }

                if (HostingEnvironment.IsHosted)
                {
                    HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedResourcesVirtualPathProvider(container.Resolve<IEmbeddedResourcesProvider>()));
                }
                else
                {
                    throw new CmsException("Failed to register EmbeddedResourcesVirtualPathProvider as a virtual path provider.");
                }

                ControllerBuilder.Current.SetControllerFactory(container.Resolve<DefaultCmsControllerFactory>());

                IAssemblyManager assemblyManager = container.Resolve<IAssemblyManager>();
                                
                // First add referenced modules...
                assemblyManager.AddReferencedModules();
                
                // ...then scan and register uploaded modules.
                assemblyManager.AddUploadedModules();

                var moduleRegistration = container.Resolve<IModulesRegistration>();
                moduleRegistration.InitializeModules();

                // Register precompiled views for all the assemblies
                var precompiledAssemblies = new List<PrecompiledViewAssembly>();
                moduleRegistration.GetModules().Select(m => m.ModuleDescriptor).Distinct().ForEach(
                    descriptor =>
                        {
                            var precompiledAssembly = new PrecompiledViewAssembly(descriptor.GetType().Assembly, string.Format("~/Areas/{0}/", descriptor.AreaName))
                                                  {
                                                      UsePhysicalViewsIfNewer = false
                                                  };
                            precompiledAssemblies.Add(precompiledAssembly);
                        });
                
                var engine = new CompositePrecompiledMvcEngine(precompiledAssemblies.ToArray());
                ViewEngines.Engines.Add(engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }
        }