예제 #1
0
		public void SequenceWriter(string name, int start, int step, DbDialect dialect,ScriptMode mode, string test){
			var pt = new PersistentClass{Name = name, Schema = "dbo"};
			var sq = new Sequence();
			sq.Setup(null,pt,null,null);
			var wr = new SequenceWriter(sq) { NoComment = true, NoDelimiter = true, Mode = mode, Dialect = dialect }; ;
			Assert.AreEqual(test,wr.ToString().Trim());
		}
예제 #2
0
		/// <summary>
		/// </summary>
		/// <param name="cls"></param>
		/// <param name="output"></param>
		public PokoClassWriter(PersistentClass cls, TextWriter output = null) : base(cls, output) {
			ProcessFields = true;
			ProcessFooter = true;
			ProcessHashMethods = true;
			ProcessHeader = true;
			ProcessReferences = true;
			ProcessInsertConstructor = true;
		}
예제 #3
0
		private void SetupBackCollectionMarker(PersistentClass t, Field reference){
			o.WriteLine("\t\t///<summary>Marks active auto collection in " + reference.Table.Name + " of " +
			            t.Name + " with " + reference.Name + " (" +
			            reference.Comment + ")</summary>");
			o.WriteLine("\t\tpublic bool AutoLoad" + reference.ReferenceClass.Name + reference.ReverseCollectionName + "=" +
			            reference.IsAutoLoadReverseByDefault.ToString().ToLowerInvariant() + ";");
			o.WriteLine("\t\t///<summary>Marks active auto collection in " + reference.Table.Name + " of " +
			            t.Name + " with " + reference.Name + " (" +
			            reference.Comment + ") as Lazy</summary>");
			o.WriteLine("\t\tpublic bool Lazy" + reference.ReferenceClass.Name + reference.ReverseCollectionName + "=" +
			            reference.IsLazyLoadReverseByDefault.ToString().ToLowerInvariant() + ";");
		}
예제 #4
0
		private void SetupDirectMarker(PersistentClass t, Field reference){
			o.WriteLine("\t\t///<summary>Marks active auto foreign key link from " + t.Name + " to " +
			            reference.ReferenceClass.Name + " with " + reference.ReferenceField + " (" +
			            reference.Comment + ")</summary>");
			o.WriteLine("\t\tpublic bool AutoLoad" + t.Name + reference.Name + " = " +
			            reference.IsAutoLoadByDefault.ToString().ToLowerInvariant() + ";");
			o.WriteLine("\t\t///<summary>Marks active auto foreign key link from " + t.Name + " to " +
			            reference.ReferenceClass.Name + " with " + reference.ReferenceField + " (" +
			            reference.Comment + ") as LazyLoad </summary>");
			o.WriteLine("\t\tpublic bool Lazy" + t.Name + reference.Name + " = " +
			            reference.IsLazyLoadByDefault.ToString().ToLowerInvariant() + ";");
		}
예제 #5
0
 public void TestAllObjects()
 {
   var obj1 = new PersistentClass("OBJ1");
   _session.Persist(obj1);
   var obj2 = new PersistentClass("OBJ2");
   _session.Persist(obj2);
   _session.Commit();
   _session.BeginUpdate();
   var list = _session.AllObjects<PersistentClass>();
   var computedCount = Enumerable.Count(list);
   Assert.AreEqual(2, computedCount);
   Assert.AreEqual(2, list.Count);
 }
예제 #6
0
 public void TestIndex()
 {
   var obj1 = new PersistentClass("OBJ1");
   _session.Persist(obj1);
   var obj2 = new PersistentClass("OBJ2");
   _session.Persist(obj2);
   _session.Commit();
   _session.BeginUpdate();
   var index = _session.Index<PersistentClass>("_name");
   var computedCount = Enumerable.Count(index);
   Assert.AreEqual(2, computedCount);
   Assert.AreEqual(2, index.Count);
 }
        public void HandleJoinedSubclass(PersistentClass model, HbmJoinedSubclass joinedSubclassMapping, IDictionary <string, MetaAttribute> inheritedMetas)
        {
            var subclass = new JoinedSubclass(model);

            BindClass(joinedSubclassMapping, subclass, inheritedMetas);
            inheritedMetas = GetMetas(joinedSubclassMapping, inheritedMetas, true);             // get meta's from <joined-subclass>

            // joined subclass
            if (subclass.EntityPersisterClass == null)
            {
                subclass.RootClazz.EntityPersisterClass = typeof(JoinedSubclassEntityPersister);
            }

            //table + schema names
            string schema  = joinedSubclassMapping.schema ?? mappings.SchemaName;
            string catalog = joinedSubclassMapping.catalog ?? mappings.CatalogName;

            Table mytable = mappings.AddTable(schema, catalog, GetClassTableName(subclass, joinedSubclassMapping.table), joinedSubclassMapping.Subselect, false, joinedSubclassMapping.schemaaction);

            ((ITableOwner)subclass).Table = mytable;

            log.Info("Mapping joined-subclass: {0} -> {1}", subclass.EntityName, subclass.Table.Name);

            // KEY
            BindKey(subclass, joinedSubclassMapping.key, mytable);

            subclass.CreatePrimaryKey(dialect);

            if (!subclass.IsJoinedSubclass)
            {
                throw new MappingException(
                          "Cannot map joined-subclass " + subclass.EntityName + " to table " +
                          subclass.Table.Name + ", the same table as its base class.");
            }

            subclass.CreateForeignKey();
            // CHECK
            mytable.AddCheckConstraint(joinedSubclassMapping.check);

            // properties
            new PropertiesBinder(mappings, subclass, dialect).Bind(joinedSubclassMapping.Properties, inheritedMetas);

            BindJoinedSubclasses(joinedSubclassMapping.JoinedSubclasses, subclass, inheritedMetas);

            new FiltersBinder(subclass, Mappings).Bind(joinedSubclassMapping.filter);

            model.AddSubclass(subclass);
            mappings.AddClass(subclass);
        }
예제 #8
0
        public void SequenceWriter(string name, int start, int step, DbDialect dialect, ScriptMode mode, string test)
        {
            var pt = new PersistentClass {
                Name = name, Schema = "dbo"
            };
            var sq = new Sequence();

            sq.Setup(null, pt, null, null);
            var wr = new SequenceWriter(sq)
            {
                NoComment = true, NoDelimiter = true, Mode = mode, Dialect = dialect
            };;

            Assert.AreEqual(test, wr.ToString().Trim());
        }
예제 #9
0
        //public static readonly InheritanceType NONE = new InheritanceType(0);
        //public static readonly InheritanceType JOINED = new InheritanceType(1);
        //public static readonly InheritanceType SINGLE = new InheritanceType(2);
        //public static readonly InheritanceType TABLE_PER_CLASS = new InheritanceType(3);

        /**
         * @param pc The class for which to get the inheritance type.
         * @return The inheritance type of this class. NONE, if this class does not inherit from
         * another persisten class.
         */
        public static InheritanceType.Type GetForChild(PersistentClass pc)
        {
            PersistentClass superclass = pc.Superclass;

            if (superclass == null)
            {
                return(InheritanceType.Type.NONE);
            }

            // We assume that every subclass is of the same type.
            IEnumerator <Subclass> enu = superclass.SubclassIterator.GetEnumerator();

            enu.MoveNext();
            return(DoGetForSubclass(enu.Current));
        }
예제 #10
0
 private static string searchMappedBy(PersistentClass referencedClass, Table collectionTable)
 {
     foreach (var property in referencedClass.PropertyIterator)
     {
         if (property.Value is Mapping.Collection propValueAsColl)
         {
             // The equality is intentional. We want to find a collection property with the same collection table.
             if (propValueAsColl.CollectionTable == collectionTable)
             {
                 return(property.Name);
             }
         }
     }
     return(null);
 }
예제 #11
0
        /// <summary>
        /// Тест наличия правил удаления для ссылок на другие сущьности в класе.
        /// Чтобы исключить класс из проверки добавьте его в коллекцию IgnoreMissingClass
        /// </summary>
        public virtual void DeleteRuleExisitForNHMappedEntityRelationTest(PersistentClass mapping, Property prop)
        {
            if (IgnoreProperties.ContainsKey(mapping.MappedClass) && IgnoreProperties[mapping.MappedClass].Any(x => x.PropertyName == prop.Name))
            {
                Assert.Ignore(IgnoreProperties[mapping.MappedClass].First(x => x.PropertyName == prop.Name).ReasonForIgnoring);
            }

            var propType = prop.Type.ReturnedClass;
            var exist    = DeleteConfig.ClassDeleteRules.Any(c => c.ObjectClass == propType);

            Assert.That(exist, "Класс {0} не имеет правил удаления, но свойство {1}.{2} прописано в мапинге.",
                        prop.Type.ReturnedClass.Name,
                        mapping.MappedClass,
                        prop.Name);
        }
예제 #12
0
        /// <summary>
        /// Тест наличия каскадной зависимости для ссылок на другие сущьности в класе.
        /// </summary>
        public virtual void CascadeDependenceRuleExisitForNHMappedEntityRelationTest(PersistentClass mapping, Property prop, IDeleteRule related)
        {
            if (IgnoreProperties.ContainsKey(mapping.MappedClass) && IgnoreProperties[mapping.MappedClass].Any(x => x.PropertyName == prop.Name))
            {
                Assert.Ignore(IgnoreProperties[mapping.MappedClass].First(x => x.PropertyName == prop.Name).ReasonForIgnoring);
            }

            var info = DeleteConfig.GetDeleteRule(mapping.MappedClass);

            Assert.That(info.DeleteItems.Any(x => x.ParentPropertyName == prop.Name && x.IsCascade),
                        "Cвойство {0}.{1} не имеет каскадного правила удаления, хотя класс {2} помечен как требующий каскадного удаления.",
                        info.ObjectClass.Name,
                        prop.Name,
                        related.ObjectClass.Name);
        }
예제 #13
0
            public void TestAllObjects()
            {
                var obj1 = new PersistentClass("OBJ1");

                _session.Persist(obj1);
                var obj2 = new PersistentClass("OBJ2");

                _session.Persist(obj2);
                _session.Checkpoint();
                var list          = _session.AllObjects <PersistentClass>();
                var computedCount = Enumerable.Count(list);

                Assert.AreEqual(2, computedCount);
                Assert.AreEqual(2, list.Count);
            }
예제 #14
0
            public void TestIndex()
            {
                var obj1 = new PersistentClass("OBJ1");

                _session.Persist(obj1);
                var obj2 = new PersistentClass("OBJ2");

                _session.Persist(obj2);
                _session.Checkpoint();
                var index         = _session.Index <PersistentClass>("_name");
                var computedCount = Enumerable.Count(index);

                Assert.AreEqual(2, computedCount);
                Assert.AreEqual(2, index.Count);
            }
예제 #15
0
        public void GenerateSecondPass(string entityName, PersistentClass persistentClass)
        {
            var identifierMapper   = persistentClass.IdentifierMapper;
            var identifierProperty = persistentClass.IdentifierProperty;

            if (identifierMapper != null)
            {
                generateSecondPass(entityName, identifierMapper);
            }
            else if (identifierProperty != null && identifierProperty.IsComposite)
            {
                var component = (Component)identifierProperty.Value;
                generateSecondPass(entityName, component);
            }
        }
예제 #16
0
        public void ReadSubClasses()
        {
            PersistentClass cm            = cfg.GetClassMapping("NHibernate.Test.MappingTest.DomesticAnimal");
            MetaAttribute   metaAttribute = cm.GetMetaAttribute("Auditable");

            Assert.That(metaAttribute, Is.Not.Null);

            cm            = cfg.GetClassMapping("NHibernate.Test.MappingTest.Cat");
            metaAttribute = cm.GetMetaAttribute("Auditable");
            Assert.That(metaAttribute, Is.Not.Null);

            cm            = cfg.GetClassMapping("NHibernate.Test.MappingTest.Dog");
            metaAttribute = cm.GetMetaAttribute("Auditable");
            Assert.That(metaAttribute, Is.Not.Null);
        }
 public PocoEntityInstantiator(
     EntityMetamodel entityMetamodel,
     PersistentClass persistentClass,
     IInstantiationOptimizer optimizer,
     IProxyFactory proxyFactory)
     : base(
         persistentClass.MappedClass,
         optimizer,
         persistentClass.HasEmbeddedIdentifier)
 {
     _entityMetamodel        = entityMetamodel;
     _proxyInterface         = persistentClass.ProxyInterface;
     _enhancedForLazyLoading = entityMetamodel.BytecodeEnhancementMetadata.EnhancedForLazyLoading;
     _proxyFactory           = proxyFactory;
 }
예제 #18
0
        private void addForEntity(PersistentClass persistentClass, IDictionary <System.Type, IEntityMeta> dicToFill)
        {
            var typ = persistentClass.MappedClass;

            fillClass(typ, dicToFill);
            var props = new List <Property>();

            props.AddRange(persistentClass.PropertyIterator);
            if (persistentClass.IdentifierProperty != null && !persistentClass.IdentifierProperty.IsComposite)
            {
                props.Add(persistentClass.IdentifierProperty);
            }

            fillMembers(typ, props, dicToFill);
        }
예제 #19
0
 private static string searchMappedBy(PersistentClass referencedClass, Mapping.Collection collectionValue)
 {
     foreach (var property in referencedClass.PropertyIterator)
     {
         if (MetadataTools.IsNoneAccess(property.PropertyAccessorName))
         {
             continue;
         }
         //should probably not care if order is same...
         if (property.Value.ColumnIterator.SequenceEqual(collectionValue.Key.ColumnIterator))
         {
             return(property.Name);
         }
     }
     return(null);
 }
예제 #20
0
        private void HandleManyToOne(Property property, PersistentClass classMapping)
        {
            var manyToOne = property.Value as ManyToOne;

            if (manyToOne == null || manyToOne.ReferencedEntityName != typeof(User).FullName)
            {
                return;
            }
            var value = new ManyToOne(classMapping.Table)
            {
                ReferencedEntityName = _userType.FullName
            };

            CopyColumns(manyToOne, value);
            property.Value = value;
        }
예제 #21
0
        public PocoEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity)
            : base(entityMetamodel, mappedEntity)
        {
            mappedClass              = mappedEntity.MappedClass;
            proxyInterface           = mappedEntity.ProxyInterface;
            islifecycleImplementor   = typeof(ILifecycle).IsAssignableFrom(mappedClass);
            isValidatableImplementor = typeof(IValidatable).IsAssignableFrom(mappedClass);

            SetReflectionOptimizer();

            Instantiator = BuildInstantiator(mappedEntity);

            ClearOptimizerWhenUsingCustomAccessors();

            proxyValidator = Cfg.Environment.BytecodeProvider.ProxyFactoryFactory.ProxyValidator;
        }
예제 #22
0
        public void ApplyOnEnumColumn()
        {
            PersistentClass classMapping = cfg.GetClassMapping(typeof(Address));
            IEnumerator     ie           = classMapping.GetProperty("AddressType").ColumnIterator.GetEnumerator();

            ie.MoveNext();
            Column serialColumn = (Column)ie.Current;

            Assert.AreEqual("AddressType in (0, 1)", serialColumn.CheckConstraint, "Validator annotation shout generate valid check for Enums");

            ie = classMapping.GetProperty("AddressFlags").ColumnIterator.GetEnumerator();
            ie.MoveNext();
            serialColumn = (Column)ie.Current;

            Assert.That(serialColumn.CheckConstraint, Is.Null.Or.Empty, "Validator annotation should not generate check for [Flag]ed Enums");
        }
예제 #23
0
        private static ConstructorInfo GetConstructor(PersistentClass persistentClass)
        {
            if (persistentClass == null || !persistentClass.HasPocoRepresentation)
            {
                return(null);
            }

            try
            {
                return(ReflectHelper.GetDefaultConstructor(persistentClass.MappedClass));
            }
            catch
            {
                return(null);
            }
        }
예제 #24
0
        IIndex GetIndex(DbConnection connection, PersistentClass entity, string indexName)
        {
            // Check if running on SQL Server.
            if (typeof(MsSql2005Dialect).IsAssignableFrom(dialect.GetType()))
            {
                string EnsureUnquoted(string name)
                {
                    if (null == name || name.Length < 2)
                    {
                        return(name);
                    }

                    if ('[' == name[0] && ']' == name[name.Length - 1]) // quoted?
                    {
                        name = name.Substring(1, name.Length - 2);      // remove outer brackets
                        name = name.Replace("]]", "]");                 // un-escape right-bracket
                    }

                    return(name);
                }

                var restrictions = new []
                {
                    EnsureUnquoted(entity.Table.Catalog),
                    EnsureUnquoted(entity.Table.Schema),
                    EnsureUnquoted(entity.Table.Name),
                    EnsureUnquoted(indexName),
                    null
                };
                return(new SqlServerIndex(connection.GetSchema("IndexColumns", restrictions)));
            }

            if (typeof(Oracle10gDialect).IsAssignableFrom(dialect.GetType()))
            {
                var restrictions = new string[5]
                {
                    entity.Table.Schema?.ToUpper(),
                    indexName?.ToUpper(),
                    null,
                    entity.Table.Name?.ToUpper(),
                    null
                };
                return(new OracleIndex(connection.GetSchema("IndexColumns", restrictions)));
            }

            return(null);
        }
        //@SuppressWarnings({"unchecked"})
        private Triple<XmlElement, IExtendedPropertyMapper, String> GenerateMappingData(
                PersistentClass pc, EntityXmlMappingData xmlMappingData, AuditTableData auditTableData,
                IdMappingData idMapper)
        {
            bool hasDiscriminator = pc.Discriminator != null;

            XmlElement class_mapping = MetadataTools.CreateEntity(xmlMappingData.MainXmlMapping, auditTableData,
                    hasDiscriminator ? pc.DiscriminatorValue : null);
            IExtendedPropertyMapper propertyMapper = new MultiPropertyMapper();

            // Checking if there is a discriminator column
            if (hasDiscriminator)
            {
                XmlElement discriminator_element = class_mapping.OwnerDocument.CreateElement("discriminator");
                class_mapping.AppendChild(discriminator_element);
                MetadataTools.AddColumns(discriminator_element, (IEnumerator<ISelectable>)pc.Discriminator.ColumnIterator.GetEnumerator());
                discriminator_element.SetAttribute("type", pc.Discriminator.Type.Name);
            }

            InheritanceType.Type parentInheritance = InheritanceType.GetForParent(pc);
            switch (parentInheritance)
            {
                case InheritanceType.Type.NONE:
                    break;

                case InheritanceType.Type.SINGLE:
                    AddSingleInheritancePersisterHack(class_mapping);
                    break;

                case InheritanceType.Type.JOINED:
                    AddJoinedInheritancePersisterHack(class_mapping);
                    break;

                case InheritanceType.Type.TABLE_PER_CLASS:
                    AddTablePerClassInheritancePersisterHack(class_mapping);
                    break;
            }

            // Adding the id mapping
            XmlNode xmlMp = class_mapping.OwnerDocument.ImportNode(idMapper.XmlMapping,true);
            class_mapping.AppendChild(xmlMp);

            // Adding the "revision type" property
            AddRevisionType(class_mapping);

            return Triple<XmlElement, IExtendedPropertyMapper, string>.Make<XmlElement, IExtendedPropertyMapper, string>(class_mapping, propertyMapper, null);
        }
예제 #26
0
        protected override IProxyFactory BuildProxyFactory(PersistentClass mappingInfo, IGetter idGetter,
                                                           ISetter idSetter)
        {
            IProxyFactory pf = new MapProxyFactory();

            try
            {
                //TODO: design new lifecycle for ProxyFactory
                pf.PostInstantiate(EntityName, null, null, null, null, null);
            }
            catch (HibernateException he)
            {
                log.Warn("could not create proxy factory for:" + EntityName, he);
                pf = null;
            }
            return(pf);
        }
        /// <summary>
        /// Creates a built in Entity Persister or a custom Persister.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public static IClassPersister CreateClassPersister(PersistentClass model, ISessionFactoryImplementor factory)
        {
            System.Type persisterClass = model.ClassPersisterClass;

            if (persisterClass == null || persisterClass == typeof(EntityPersister))
            {
                return(new EntityPersister(model, factory));
            }
            else if (persisterClass == typeof(NormalizedEntityPersister))
            {
                return(new NormalizedEntityPersister(model, factory));
            }
            else
            {
                return(Create(persisterClass, model, factory));
            }
        }
예제 #28
0
 /// <summary>
 /// </summary>
 /// <param name="model"></param>
 /// <param name="cls"></param>
 /// <param name="bscls"></param>
 /// <param name="xml"></param>
 public override SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls, XElement xml)
 {
     base.Setup(model, cls, bscls, xml);
     Allocation = cls.AllocationInfo;
     FileGroup  = Allocation.FileGroup.Name;
     Name       = cls.FullSqlName.Replace(".", "_").Replace("\"", "") + "_PARTITION";
     Start      = Allocation.PartitioningStart;
     if (null != Allocation.PartitionField)
     {
         Type = Allocation.PartitionField.DataType.ResolveSqlDataType(DbDialect.SqlServer);
     }
     else
     {
         Type = "int";
     }
     return(this);
 }
예제 #29
0
        public PocoInstantiator(PersistentClass persistentClass, IInstantiationOptimizer optimizer)
        {
            mappedClass        = persistentClass.MappedClass;
            proxyInterface     = persistentClass.ProxyInterface;
            embeddedIdentifier = persistentClass.HasEmbeddedIdentifier;
            this.optimizer     = optimizer;

            try
            {
                constructor = ReflectHelper.GetDefaultConstructor(mappedClass);
            }
            catch (PropertyNotFoundException)
            {
                log.Info(string.Format("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName));
                constructor = null;
            }
        }
예제 #30
0
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="cls"></param>
		/// <param name="bscls"></param>
		/// <param name="xml"></param>
		public override SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls, XElement xml){
			base.Setup(model, cls, bscls, xml);
			if (null != xml){
				Start = xml.Attr("start", "10").ToInt();
				Step = xml.Attr("step", "10").ToInt();
			}
			Name = cls.Name + "_SEQ";
			Schema = cls.Schema;
			IsCyclic = cls.CyclicId;
			if (null != cls.PrimaryKey){
				DataType = cls.PrimaryKey.DataType;
			}
			else{
				DataType = cls.DataTypeMap["int"];
			}
			return this;
		}
예제 #31
0
        private void BindTimestamp(HbmTimestamp timestampSchema, PersistentClass rootClass, Table table, IDictionary <string, MetaAttribute> inheritedMetas)
        {
            if (timestampSchema == null)
            {
                return;
            }

            string      propertyName = timestampSchema.name;
            SimpleValue simpleValue  = new SimpleValue(table);

            BindColumns(timestampSchema, simpleValue, propertyName);

            if (!simpleValue.IsTypeSpecified)
            {
                switch (timestampSchema.source)
                {
                case HbmTimestampSource.Vm:
                    simpleValue.TypeName = NHibernateUtil.Timestamp.Name;
                    break;

                case HbmTimestampSource.Db:
                    simpleValue.TypeName = NHibernateUtil.DbTimestamp.Name;
                    break;

                default:
                    simpleValue.TypeName = NHibernateUtil.Timestamp.Name;
                    break;
                }
            }

            var property = new Property(simpleValue);

            BindProperty(timestampSchema, property, inheritedMetas);

            // for version properties marked as being generated, make sure they are "always"
            // generated; "insert" is invalid. This is dis-allowed by the schema, but just to make
            // sure...

            if (property.Generation == PropertyGeneration.Insert)
            {
                throw new MappingException("'generated' attribute cannot be 'insert' for versioning property");
            }
            simpleValue.NullValue = timestampSchema.unsavedvalue == HbmTimestampUnsavedvalue.Null ? null : "undefined";
            rootClass.Version     = property;
            rootClass.AddProperty(property);
        }
예제 #32
0
        private void BindProperties(PersistentClass pclass, IEnumerable <PropertyInfo> infos)
        {
            Table table = pclass.Table;

            foreach (PropertyInfo propertyInfo in infos)
            {
                IValue value;

                // Bind a simple value property
                value = new SimpleValue(table);
                BindColumn((SimpleValue)value, true, propertyInfo.Name);

                Property property = CreateProperty(value, propertyInfo, pclass.ClassName);
                //	property.IsUpdateable = false;
                pclass.AddProperty(property);
            }
        }
        //@SuppressWarnings({"unchecked"})
        private void AddJoins(PersistentClass pc, ICompositeMapperBuilder currentMapper, ClassAuditingData auditingData,
                              String entityName, EntityXmlMappingData xmlMappingData, bool firstPass)
        {
            IEnumerator<Join> joins = pc.JoinIterator.GetEnumerator();

            while (joins.MoveNext())
            {
                Join join = joins.Current;
                XmlElement joinElement = entitiesJoins[entityName][join];

                if (joinElement != null)
                {
                    AddProperties(joinElement, (IEnumerator<Property>)join.PropertyIterator.GetEnumerator(), currentMapper, auditingData, entityName,
                            xmlMappingData, firstPass);
                }
            }
        }
        private static bool GetFilterTextWithAliasContext(
            PersistentClass classMapping,
            string filterName,
            out string filterText)
        {
            filterText = null;

            var metaAttribute = classMapping.GetMetaAttribute("HqlFilter_" + filterName);

            if (metaAttribute == null)
            {
                return(false);
            }

            filterText = metaAttribute.Value;
            return(true);
        }
예제 #35
0
        public virtual IList <Column> listNonPropertyColumns(PersistentClass paramPersistentClass)
        {
            List <object> arrayList = new List <object>();
            List <Column> list      = new List <Column>();

            IEnumerator iterator = paramPersistentClass.RootTable.ColumnIterator;

            while (iterator.MoveNext())
            {
                Column column = (Column)iterator.Current;
                if (!list.Contains(column))
                {
                    arrayList.Add(column);
                }
            }
            return(arrayList.Cast <Column>().ToList());
        }
예제 #36
0
        private static void VerifyCanInterceptPropertiesForLazyOrGhostProperties(PersistentClass persistentClass)
        {
            foreach (var prop in persistentClass.PropertyClosureIterator)
            {
                if (prop.IsLazy == false &&
                    prop.UnwrapProxy == false)
                {
                    continue;
                }

                var getter = prop.GetGetter(persistentClass.MappedClass);
                if (getter.Method == null ||
                    getter.Method.IsDefined(typeof(CompilerGeneratedAttribute), false) == false)
                {
                    log.ErrorFormat("Lazy or ghost property {0}.{1} is not an auto property, which may result in uninitialized property access", persistentClass.EntityName, prop.Name);
                }
            }
        }
예제 #37
0
        private void CreateIdentifierProperty(PersistentClass pclass, IValue identifier, string propName)
        {
            identifier.SetTypeUsingReflection(pclass.MappedClass == null ? null : pclass.MappedClass.AssemblyQualifiedName,
                                              propName, DefaultValues.Accessor);

            var property = new Property(identifier)
            {
                Name = propName,
                PropertyAccessorName = DefaultValues.Accessor,
                Cascade            = mapper.Mappings.DefaultCascade,
                IsUpdateable       = true,
                IsInsertable       = true,
                IsOptimisticLocked = true,
                Generation         = PropertyGeneration.Never
            };

            pclass.IdentifierProperty = property;
        }
예제 #38
0
		private DataType GetTableType(PersistentModel model, string clsname, PersistentClass _cls){
			var cls = clsname == "this" ? _cls: model[clsname];
			if (null == cls){
				model.RegisterError(new BSharpError{Message = "Не могу найти класса для табличного типа "+clsname});
			}
			var result = new DataType();
			result.IsTable = true;
			result.TargetType = cls;
			return result;
		} 
예제 #39
0
		private void ProcessInvalidPartitionField(PersistentClass cls){
			var error = new BSharpError{
				Class = cls.TargetClass,
				Level = ErrorLevel.Error,
				Message = "Поле, отмеченное к партицироанию не найдено"
			};
			Errors.Add(error);
			Context.RegisterError(error);
		}
예제 #40
0
		private void ReadAdvancedDataObjects(PersistentClass cls, XElement xml){
			foreach (SqlObject obj in SqlObject.CreateDefaults(cls)){
				obj.Table = cls;
				cls.SqlObjects.Add(obj);
			}
			foreach (XElement e in xml.Elements()){
				string name = e.Name.LocalName;
				if (name == "ref") continue;
				if (cls.DataTypeMap.ContainsKey(name) && string.IsNullOrWhiteSpace(e.Value)) continue;
				foreach (SqlObject obj in SqlObject.Create(cls, e)){
					cls.SqlObjects.Add(obj);
				}
			}
		}
예제 #41
0
		/// <summary>
		///     Загружает поле из XML
		/// </summary>
		/// <param name="c"></param>
		/// <param name="e"></param>
		/// <param name="cls"></param>
		/// <returns></returns>
		public Field Setup(IBSharpClass c, XElement e, PersistentClass cls){
			Table = cls;
			Definition = e;
			SetupCommon(c, e);
			if (ImplicitRef || e.Name.LocalName == "ref"){
				SetupReference(c, e);
			}
			else{
				SetupUsualField(c, e);
			}
			SetupDefaultValue(c, e);

			return this;
		}
예제 #42
0
		private void ProcessNullPartitionField(PersistentClass cls){
			var error = new BSharpError{
				Class = cls.TargetClass,
				Level = ErrorLevel.Error,
				Message = "Таблица отмечена к партицированию, но поле не указано"
			};
			Errors.Add(error);
			Context.RegisterError(error);
		}
예제 #43
0
		/// <summary>
		///     Конфигурирует модель из B#
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		public PersistentModel Setup(IBSharpContext context){
			Context = context;
			IEnumerable<IBSharpClass> tables = Context.ResolveAll(TablePrototype+";attr:"+TableAttribute).ToArray();
			foreach (IBSharpClass table in tables){
				var pclass = new PersistentClass();
				pclass.Setup(table);
				pclass.Model = this;
				Classes[pclass.FullSqlName.ToLowerInvariant()] = pclass;
			}
			SetupDefaultScripts();
			foreach (SqlObject obj in SqlObject.CreateDatabaseWide(this)){
				DatabaseSqlObjects.Add(obj);
			}
			BuildModel();
			ReadScripts();
			return this;
		}
예제 #44
0
		private DataType GetIdRefType(PersistentModel model, string clsname, string argname, PersistentClass _cls){
			
			
			var cls = clsname=="this"?_cls: model[clsname];
			if (null == cls)
			{
				model.RegisterError(new BSharpError { Message = "Не могу найти класса для ссылочного типа " + clsname });
				return null;
			}
			var result = cls[argname].DataType.Copy();
			result.IsIdRef = true;
			result.TargetType = cls;
			return result;
		}
예제 #45
0
		/// <summary>
		/// </summary>
		/// <param name="cls"></param>
		/// <param name="output"></param>
		protected CodeWriterBase(PersistentClass cls, TextWriter output) : this(output){
			Cls = cls;
		}
예제 #46
0
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="cls"></param>
		/// <param name="bscls"></param>
		/// <param name="xml"></param>
		/// <returns></returns>
		public override SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls,
		                                XElement xml){
			model = model ?? cls.Model;
			base.Setup(model, cls, bscls, xml);
			
			string xname = xml.Name.LocalName;
			IsProcedure = xname == "void" || (xname == "function" && string.IsNullOrWhiteSpace(xml.Attr("returns")));
			if (!IsProcedure){
				if (xname.EndsWith("__STAR__")){
					var tp = xname.Substring(0, xname.Length - 8);
					ReturnType = GetTableType(model, tp,cls);
				}
				else{
					string dtype = xname;
					if (dtype == "function"){
						dtype = xml.Attr("returns");
					}
					if (Table.DataTypeMap.ContainsKey(dtype)){
						ReturnType = Table.DataTypeMap[dtype];
					}
					else{
						ReturnType = new DataType{IsNative = true, SqlText = dtype};
					}


				}
			}
			if (xml.GetSmartValue("sql-method").ToBool()){
				var sqlm = SqlMethodOptions.IsMethod;
				var opts = xml.GetSmartValue("sql-method");
				if (!string.IsNullOrWhiteSpace(opts)){
					sqlm |= opts.To<SqlMethodOptions>();
				}
				SqlMethod = sqlm;
			}
			int i = 0;
			foreach (XAttribute a in xml.Attributes()){
				string name = a.Name.LocalName.Unescape(EscapingType.XmlName);
				string val = a.Value;
				if (name.StartsWith("@")){
					string[] namepair = name.Substring(1).Split('-');
					string argname = namepair[0];
					SqlFunctionArgument arg;
					if (!Arguments.ContainsKey(argname)){
						Arguments[argname] = new SqlFunctionArgument{Name = argname, DataType = Table.DataTypeMap["string"], Index = i++};
					}
					arg = Arguments[argname];
					if (namepair.Length == 1){
//only type determine
						if (Table.DataTypeMap.ContainsKey(val)){
							arg.DataType = Table.DataTypeMap[val];
						}
						else{
							arg.DataType = GetIdRefType(model,val,argname,cls);
						}
					}
					else{
						bool hastype = false;
						bool hasdefault = false;
						for (int j = 1; j < namepair.Length; j++){
							string part = namepair[j];
							if (part == "default"){
								hasdefault = true;
							}
							else if (part == "out"){
								arg.IsOutput = true;
							}
							else if (Table.DataTypeMap.ContainsKey(part)){
								arg.DataType = Table.DataTypeMap[part];
								hastype = true;
							}
							else{
								Model.RegisterError(new BSharpError{Message = "unknown arg part " + part, Xml = xml, Class = Table.TargetClass});
							}
						}
						if ((hastype || hasdefault) && !string.IsNullOrWhiteSpace(val)){
							arg.DefaultValue = new DefaultValue{DefaultValueType = DbDefaultValueType.Native, Value = val};
						}
					}
				}
			}
			return this;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="owner"></param>
		public PrimitiveArray( PersistentClass owner ) : base( owner )
		{
		}