public string[] ToColumns(string tableAlias, string path, bool inSelect, bool forceAlias)
        {
            CheckInitialized();
            IPropertyMapping propertyMapping = GetPropertyMapping(path);

            // If this from element is a collection and the path is a collection property (maxIndex, etc.) then
            // generate a sub-query.
            if (!inSelect && _queryableCollection != null && CollectionProperties.IsCollectionProperty(path))
            {
                IDictionary <string, IFilter> enabledFilters = _fromElement.Walker.EnabledFilters;

                string subquery = CollectionSubqueryFactory.CreateCollectionSubquery(
                    _joinSequence,
                    enabledFilters,
                    propertyMapping.ToColumns(tableAlias, path)
                    );
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("toColumns({0},{1}) : subquery = {2}", tableAlias, path, subquery);
                }
                return(new [] { "(" + subquery + ")" });
            }
            else
            {
                if (forceAlias)
                {
                    return(propertyMapping.ToColumns(tableAlias, path));
                }
                else if (_fromElement.Walker.StatementType == HqlSqlWalker.SELECT)
                {
                    return(propertyMapping.ToColumns(tableAlias, path));
                }
                else if (_fromElement.Walker.CurrentClauseType == HqlSqlWalker.SELECT)
                {
                    return(propertyMapping.ToColumns(tableAlias, path));
                }
                else if (_fromElement.Walker.IsSubQuery)
                {
                    // We already know it's subqery for DML query.
                    // If this FROM_ELEMENT represents a correlation to the outer-most query we must use real table name
                    // for UPDATE(typically in a SET clause)/DELETE queries unless it's multi-table reference inside top level where clause
                    // (as this subquery will actually be used in the "id select" phase of that multi-table executor)
                    var useAlias = _fromElement.Walker.StatementType == HqlSqlWalker.INSERT ||
                                   (IsMultiTable && _fromElement.Walker.CurrentTopLevelClauseType == HqlSqlWalker.WHERE);

                    if (!useAlias && IsCorrelation)
                    {
                        return(propertyMapping.ToColumns(ExtractTableName(), path));
                    }

                    return(propertyMapping.ToColumns(tableAlias, path));
                }
                else
                {
                    string[] columns = propertyMapping.ToColumns(path);
                    Log.Info("Using non-qualified column reference [{0} -> ({1})]", path, ArrayHelper.ToString(columns));
                    return(columns);
                }
            }
        }
 private void ApplyStorageAttribute(IPropertyMapping mapping)
 {
     if (!mapping.Attributes.ContainsKey(Constants.Storage))
     {
         mapping.Attributes[Constants.Storage] = NameSpecifier(mapping);
     }
 }
예제 #3
0
        protected IQueryableCollection GetQueryableCollection(string entityName, string actualPropertyName,
                                                              ISessionFactoryImplementor factory)
        {
            IPropertyMapping ownerMapping = (IPropertyMapping)factory.GetEntityPersister(entityName);
            IType            type         = ownerMapping.ToType(actualPropertyName);

            if (!type.IsCollectionType)
            {
                throw new MappingException(
                          "Property path [" + entityName + "." + actualPropertyName + "] does not reference a collection"
                          );
            }

            string role = ((CollectionType)type).Role;

            try
            {
                return((IQueryableCollection)factory.GetCollectionPersister(role));
            }
            catch (InvalidCastException cce)
            {
                throw new QueryException("collection role is not queryable: " + role, cce);
            }
            catch (Exception e)
            {
                throw new QueryException("collection role not found: " + role, e);
            }
        }
예제 #4
0
        public EntityContext(
            IEntityContextFactory factory,
            IMappingsRepository mappings,
            IEntityStore entityStore,
            IEntitySource entitySource,
            IBaseUriSelectionPolicy baseUriSelector,
            IRdfTypeCache typeCache,
            IBlankNodeIdGenerator blankIdGenerator,
            IResultTransformerCatalog transformerCatalog,
            IEntityCaster caster,
            IDatasetChangesTracker changeTracker,
            IResourceResolutionStrategy resourceResolutionStrategy,
            ILogger log)
            : this(changeTracker)
        {
            _factory                    = factory;
            _entityStore                = entityStore;
            _entitySource               = entitySource;
            _baseUriSelector            = baseUriSelector;
            _mappings                   = mappings;
            _typeCache                  = typeCache;
            _blankIdGenerator           = blankIdGenerator;
            _transformerCatalog         = transformerCatalog;
            _caster                     = caster;
            _typedEntityMapping         = _mappings.MappingFor <ITypedEntity>();
            _typesPropertyMapping       = _typedEntityMapping.PropertyFor("Types");
            _resourceResolutionStrategy = resourceResolutionStrategy;
            _log = log;

            if (_baseUriSelector == null)
            {
                _log.Warning("No Base URI Selection Policy. It will not be possible to use relative URIs");
            }
        }
예제 #5
0
        /// <inheritdoc />
        protected virtual object Transform(INode node, IPropertyMapping property, IEntityContext context)
        {
            object result = property.Converter.Convert(node, context);

            if (result != null)
            {
                if ((property.ReturnType.GetTypeInfo().IsGenericType) && (typeof(Nullable <>) == property.ReturnType.GetGenericTypeDefinition()))
                {
                    return(property.ReturnType.GetTypeInfo().GetConstructor(property.ReturnType.GetTypeInfo().GetGenericArguments()).Invoke(new[] { result }));
                }

                bool isEnumerable = (property.ReturnType.IsEnumerable()) && (property.ReturnType != typeof(byte[]));
                Type itemType     = property.ReturnType;
                if (isEnumerable)
                {
                    itemType = property.ReturnType.FindItemType();
                }

                if (((!isEnumerable) || (property.ReturnType != itemType)) && (!itemType.GetTypeInfo().IsInstanceOfType(result)))
                {
                    if (itemType == typeof(string))
                    {
                        result = TransformToString(itemType, result);
                    }
                    else
                    {
                        result = System.Convert.ChangeType(result, itemType);
                    }
                }
            }

            return(result);
        }
예제 #6
0
        private void ApplyMapping <TMetadata>(IPropertyMapping mapping, object source, TMetadata target,
                                              Action <string> log)
        {
            log.Invoke($"Applying mapping from source {mapping.SourceName} -> {mapping.TargetPropertyName}");

            mapping.Apply(source, target);
        }
        private void OverrideSelector(QueryComponent component, System.Linq.Expressions.Expression selector)
        {
            if ((component is Identifier) && (selector is System.Linq.Expressions.MemberExpression))
            {
                System.Linq.Expressions.MemberExpression memberExpression = (System.Linq.Expressions.MemberExpression)selector;
                if (!(memberExpression.Member is PropertyInfo))
                {
                    throw new NotSupportedException(System.String.Format("Selection on members of type '{0}' are not supported.", memberExpression.Member.MemberType));
                }

                PropertyInfo propertyInfo = (PropertyInfo)memberExpression.Member;
                if (typeof(IEntity).IsAssignableFrom(propertyInfo.DeclaringType))
                {
                    _propertyMapping = _entityContext.Mappings.FindPropertyMapping((PropertyInfo)memberExpression.Member);
                    if (typeof(IEntity).IsAssignableFrom(_propertyMapping.ReturnType))
                    {
                        OverrideEntitySelector((Identifier)component);
                    }
                    else
                    {
                        OverrideLiteralSelector(this.GetEntityAccessor((FromClauseBase)FindQuerySource(memberExpression).ReferencedQuerySource));
                    }
                }
            }
            else if (component is StrongEntityAccessor)
            {
                _propertyMapping = IdentifierPropertyMapping.Default;
                OverrideIdentifierSelector((StrongEntityAccessor)component);
            }
        }
        /// <summary>
        /// Transforms the resulting <paramref name="nodes"/> to a <see cref="IRdfListAdapter{T}"/>
        /// </summary>
        public override object FromNodes(IEntityProxy parent, IPropertyMapping property, IEntityContext context, [AllowNull] IEnumerable<Node> nodes)
        {
            var listHead = (IEntity)base.FromNodes(parent, property, context, nodes);
            var ownerType = GetOwnerType(property);
            var nodeType = GetNodeType(property);
            var itemType = property.ReturnType.GetGenericArguments()[0].FindItemType();
            var ctor = typeof(RdfListAdapter<,,>).MakeGenericType(ownerType, nodeType, itemType)
                .GetConstructor(new[] { typeof(IEntityContext), typeof(IEntity), nodeType, typeof(OverridingGraphSelector) });

            object head;
            if (listHead == null)
            {
                head = context.GetType().GetInterfaceMap(typeof(IEntityContext))
                    .InterfaceMethods
                    .Where(item => (item.Name == "Create") && (item.IsGenericMethodDefinition) && (item.GetParameters().Length == 1) && (item.GetParameters()[0].ParameterType == typeof(EntityId)))
                    .Select(item => item.MakeGenericMethod(nodeType))
                    .First()
                    .Invoke(context, new object[] { new EntityId(Vocabularies.Rdf.nil) });
            }
            else
            {
                head = typeof(EntityExtensions).GetMethod("AsEntity").MakeGenericMethod(nodeType).Invoke(null, new object[] { listHead });
            }

            var paremeters = parent.GraphSelectionOverride ?? new OverridingGraphSelector(parent.Id, parent.EntityMapping, property);
            ((IEntityProxy)((IEntity)head).UnwrapProxy()).OverrideGraphSelection(paremeters);
            return ctor.Invoke(new[] { context, parent, head, paremeters });
        }
예제 #9
0
        /// <summary>
        /// Returns the type of a property, given it's name (the last part) and the full path.
        /// </summary>
        /// <param name="propertyName">The last part of the full path to the property.</param>
        /// <param name="propertyPath">The full property path.</param>
        /// <returns>The type</returns>
        public IType GetPropertyType(string propertyName, string propertyPath)
        {
            CheckInitialized();

            IType type = null;

            // If this is an entity and the property is the identifier property, then use getIdentifierType().
            //      Note that the propertyName.equals( propertyPath ) checks whether we have a component
            //      key reference, where the component class property name is the same as the
            //      entity id property name; if the two are not equal, this is the case and
            //      we'd need to "fall through" to using the property mapping.
            if (_persister != null && (propertyName == propertyPath) && propertyName == _persister.IdentifierPropertyName)
            {
                type = _persister.IdentifierType;
            }
            else
            {                   // Otherwise, use the property mapping.
                IPropertyMapping mapping = GetPropertyMapping(propertyName);
                type = mapping.ToType(propertyPath);
            }
            if (type == null)
            {
                throw new MappingException("Property " + propertyName + " does not exist in " +
                                           ((_queryableCollection == null) ? "class" : "collection") + " "
                                           + ((_queryableCollection == null) ? _fromElement.ClassName : _queryableCollection.Role));
            }
            return(type);
        }
예제 #10
0
 protected override void OnBeforePopulate(IPropertyMapping mapping, object target, object source)
 {
     if (mapping is CsvFieldMapping)
     {
         ((CsvFieldMapping)mapping).FieldDelimiter = FieldDelimiter;
     }
 }
        /// <summary>
        /// Converts a list <paramref name="value"/> to an <see cref="IRdfListAdapter{T}"/> if necessary and return the RDF:List's head
        /// </summary>
        /// <returns>an <see cref="IEntity"/></returns>
        /// <exception cref="ArgumentException">when value is not a collection</exception>
        public override IEnumerable<Node> ToNodes(object value, IEntityProxy proxy, IPropertyMapping property, IEntityContext context)
        {
            if (!(value is IEnumerable))
            {
                throw new ArgumentException("Value must implement IEnumerable", "value");
            }

            if (typeof(IRdfListAdapter<>).IsAssignableFromSpecificGeneric(value.GetType()))
            {
                yield return Node.FromEntityId(((IEntity)value.GetType().GetProperty("Head").GetValue(value)).Id);
            }
            else
            {
                var nodeType = GetNodeType(property);
                var ownerType = GetOwnerType(property);
                var itemType = property.ReturnType.GetGenericArguments()[0].FindItemType();
                var ctor = typeof(RdfListAdapter<,,>).MakeGenericType(ownerType, nodeType, itemType)
                    .GetConstructor(new[] { typeof(IEntityContext), typeof(IEntity), typeof(OverridingGraphSelector) });
                var paremeters = proxy.GraphSelectionOverride ?? new OverridingGraphSelector(proxy.Id, proxy.EntityMapping, property);
                var rdfList = ctor.Invoke(new object[] { context, proxy, paremeters });
                var interfaceMapping = rdfList.GetType().GetInterfaceMap(typeof(IRdfListAdapter<>).MakeGenericType(itemType));
                var addMethodInfo = interfaceMapping.InterfaceMethods.First(item => item.Name == "Add");

                foreach (var item in (IEnumerable)value)
                {
                    addMethodInfo.Invoke(rdfList, new[] { item });
                }

                yield return Node.FromEntityId(((IEntity)interfaceMapping.InterfaceMethods.First(item => item.Name == "get_Head").Invoke(rdfList, null)).Id);
            }
        }
예제 #12
0
        /// <summary>
        /// Clones the mapping of another resource.
        /// </summary>
        /// <param name="other"></param>
        void IPropertyMapping.CloneFrom(IPropertyMapping other)
        {
            if (_dataType != other.DataType)
            {
                return;
            }

            if (_value != null && _isList)
            {
                IList collection = (IList)_value;

                collection.Clear();

                IList otherCollection = (IList)other.GetValueObject();

                foreach (var v in otherCollection)
                {
                    collection.Add(v);
                }

                _isUnsetValue = other.IsUnsetValue;
            }
            else
            {
                _value        = (T)other.GetValueObject();
                _isUnsetValue = other.IsUnsetValue;
            }
        }
예제 #13
0
 public void Add(IPropertyMapping <TEntity> property)
 {
     if (!string.IsNullOrEmpty(property?.Name))
     {
         this[property.Name.ToLower()] = property;
     }
 }
예제 #14
0
 private void AddToResult(string uniqueKey, IPropertyMapping property)
 {
     if (!parseResult.ContainsKey(uniqueKey))
     {
         parseResult.Add(uniqueKey, new ExpressionParseResult(uniqueKey, property));
     }
 }
예제 #15
0
        private Type GetTypeDyctionaryEntityNames(IPropertyMapping property, bool isOwnerType = false)
        {
            var entityType = property.EntityMapping.EntityType.GetTypeInfo();
            DictionaryEntityNames entityName;
            Assembly mappingAssembly;

            if (_assemblyCache.TryGetValue(entityType.Assembly, out mappingAssembly))
            {
                entityName = new DictionaryEntityNames(
                    entityType.Namespace,
                    entityType.Name,
                    property.Name,
                    mappingAssembly.FullName);
            }
            else
            {
                entityName = new TypeDictionaryEntityNames(property.EntityMapping.EntityType.GetTypeInfo().GetProperty(property.Name));
                if (Type.GetType(entityName.EntryTypeFullyQualifiedName, false) != null)
                {
                    _assemblyCache[entityType.Assembly] = mappingAssembly = entityType.Assembly;
                }
                else
                {
                    _assemblyCache[entityType.Assembly] = mappingAssembly = _emitHelper.GetDynamicModule().Assembly;
                    entityName = new DictionaryEntityNames(
                        entityType.Namespace,
                        entityType.Name,
                        property.Name,
                        mappingAssembly.FullName);
                }
            }

            return(mappingAssembly.GetType(isOwnerType ? entityName.FullOwnerTypeName : entityName.FullEntryTypeName));
        }
예제 #16
0
        /// <summary>
        /// Gets the column name mapping for a property
        /// </summary>
        /// <param name="propertyName">Property name</param>
        /// <returns>Mapped column name</returns>
        public string GetColumnName(string propertyName)
        {
            string           columnName = null;
            IPropertyMapping mapping    = (from map in PropertyMap
                                           where map.PropertyInfo.Name == propertyName
                                           select map).FirstOrDefault();

            if (mapping != null)
            {
                columnName = mapping.SourceColumnName;
            }
            else
            {
                //if no direct mapping, check references:
                foreach (IDataReaderMap referenceMap in ReferenceMap.Values)
                {
                    columnName = referenceMap.GetColumnName(propertyName);
                    if (!columnName.IsNullOrEmpty())
                    {
                        break;
                    }
                }
            }
            return(columnName);
        }
예제 #17
0
        /// <summary>Visits a member expression.</summary>
        /// <param name="expression">Expression to be visited.</param>
        /// <returns>Expression visited</returns>
        protected override System.Linq.Expressions.Expression VisitMember(System.Linq.Expressions.MemberExpression expression)
        {
            if ((expression.Member.Name == "Id") && (typeof(IEntity).IsAssignableFrom(expression.Member.DeclaringType)))
            {
                Remotion.Linq.Clauses.FromClauseBase target = GetMemberTarget(expression);
                if (target != null)
                {
                    return(VisitEntityId(new EntityIdentifierExpression(expression, target)));
                }

                ExceptionHelper.ThrowInvalidCastException(typeof(IEntity), expression.Member.DeclaringType);
            }
            else if (expression.Member is PropertyInfo)
            {
                IPropertyMapping propertyMapping = _entityContext.Mappings.FindPropertyMapping((PropertyInfo)expression.Member);
                if (propertyMapping != null)
                {
                    Remotion.Linq.Clauses.FromClauseBase target = GetMemberTarget(expression);
                    if (target != null)
                    {
                        return(VisitEntityProperty(new EntityPropertyExpression(expression, propertyMapping, target, (_itemNameOverride ?? expression.Member.Name))));
                    }

                    ExceptionHelper.ThrowInvalidCastException(typeof(IEntity), expression.Member.DeclaringType);
                }
                else
                {
                    return(VisitProperty(expression));
                }
            }

            return(base.VisitMember(expression));
        }
        public bool ValidateMappingExistsFor <TSource, TDestination>(string fields) where TDestination : Entity
        {
            IPropertyMapping propertyMapping = Resolve <TSource, TDestination>();

            if (string.IsNullOrWhiteSpace(fields))
            {
                return(true);
            }

            var fieldsAfterSplit = fields.Split(',');

            foreach (var field in fieldsAfterSplit)
            {
                var trimmedField      = field.Trim();
                var indexOfFirstSpace = trimmedField.IndexOf(" ", StringComparison.Ordinal);
                var propertyName      = indexOfFirstSpace == -1 ? trimmedField : trimmedField.Remove(indexOfFirstSpace);
                if (string.IsNullOrWhiteSpace(propertyName))
                {
                    continue;
                }
                if (!propertyMapping.MappingDictionary.ContainsKey(propertyName))
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #19
0
        private Option <Action <TMetadata> > GetMappingApplication <TMetadata>(IPropertyMapping propertyMapping,
                                                                               IEnumerable <object> sources, TMetadata target, Action <string> log)
        {
            Option <object> source = sources.FirstOrDefault(s => propertyMapping.CanApply(s, target));

            return(source.Map(s => (Action <TMetadata>)(t => ApplyMapping(propertyMapping, s, t, log))));
        }
예제 #20
0
        private void BuildPropertyMapping(MergingEntityMapping existingEntityMapping, IPropertyMappingProvider propertyMappingProvider)
        {
            if (propertyMappingProvider == null)
            {
                return;
            }

            IConverter valueConverter = null;

            if (propertyMappingProvider.ValueConverterType != null)
            {
                valueConverter = _converterProvider.FindConverter(propertyMappingProvider.ValueConverterType);
            }

            var collectionMappingProvider    = propertyMappingProvider as ICollectionMappingProvider;
            IPropertyMapping propertyMapping = collectionMappingProvider != null
                ? CollectionMapping.CreateFrom(existingEntityMapping, collectionMappingProvider, valueConverter, _qiriMappings)
                : PropertyMapping.CreateFrom(existingEntityMapping, propertyMappingProvider, valueConverter, _qiriMappings);

            var existingPropertyMapping = existingEntityMapping.Properties.FirstOrDefault(mapping => mapping.Name == propertyMappingProvider.Property.Name);

            if (existingPropertyMapping != null)
            {
                if (!PropertyMappingEqualityComparer.Default.Equals(propertyMapping, existingPropertyMapping))
                {
                    throw new AmbiguousMappingException(
                              $"Mapping for ${propertyMappingProvider.Property.Name} for type ${existingEntityMapping.Type} is already defined.");
                }

                return;
            }

            existingEntityMapping.Properties.Add(propertyMapping);
        }
예제 #21
0
        /// <summary>Transforms the resulting <paramref name="nodes"/> to a <see cref="IRdfListAdapter{T}"/>.</summary>
        public override object FromNodes(IEntityProxy parent, IPropertyMapping property, IEntityContext context, IEnumerable <INode> nodes)
        {
            var listHead  = (IEntity)base.FromNodes(parent, property, context, nodes);
            var ownerType = GetOwnerType(property);
            var nodeType  = GetNodeType(property);
            var itemType  = property.ReturnType.GetTypeInfo().GetGenericArguments()[0].FindItemType();
            var ctor      = typeof(RdfListAdapter <, ,>).MakeGenericType(ownerType, nodeType, itemType).GetTypeInfo()
                            .GetConstructor(new[] { typeof(IEntityContext), typeof(IEntity), nodeType, typeof(OverridingGraphSelector) });

            object head;

            if (listHead == null)
            {
                head = context.GetType().GetTypeInfo().GetRuntimeInterfaceMap(typeof(IEntityContext))
                       .InterfaceMethods
                       .Where(item => (item.Name == "Create") && (item.IsGenericMethodDefinition) && (item.GetParameters().Length == 1) && (item.GetParameters()[0].ParameterType == typeof(EntityId)))
                       .Select(item => item.MakeGenericMethod(nodeType))
                       .First()
                       .Invoke(context, new object[] { new EntityId(Vocabularies.Rdf.nil) });
            }
            else
            {
                head = typeof(EntityExtensions).GetTypeInfo().GetMethod("AsEntity").MakeGenericMethod(nodeType).Invoke(null, new object[] { listHead });
            }

            var paremeters = parent.GraphSelectionOverride ?? new OverridingGraphSelector(parent.Id, parent.EntityMapping, property);

            ((IEntityProxy)((IEntity)head).UnwrapProxy()).OverrideGraphSelection(paremeters);
            return(ctor.Invoke(new[] { context, parent, head, paremeters }));
        }
예제 #22
0
            public Uri SelectGraph(EntityId id, IEntityMapping entityMapping, IPropertyMapping predicate)
            {
                string replacementProtocol = "http";

                if (predicate != null && predicate.Uri != null)
                {
                    switch (predicate.Uri.ToString())
                    {
                    case "http://xmlns.com/foaf/0.1/familyName":
                    case "http://xmlns.com/foaf/0.1/givenName":
                        replacementProtocol = "personal";
                        break;

                    case "http://xmlns.com/foaf/0.1/knows":
                        replacementProtocol = "friendsOf";
                        break;

                    case "http://xmlns.com/foaf/0.1/homePage":
                    case "http://xmlns.com/foaf/0.1/interest":
                        replacementProtocol = "interestsOf";
                        break;
                    }
                }

                return(new Uri(id.ToString().Replace("http", replacementProtocol)));
            }
예제 #23
0
        /// <summary>Converts a value to nodes.</summary>
        public IEnumerable<Node> ConvertBack(object value,IPropertyMapping property)
        {
            var convertedNodes=new List<Node>();

            if (typeof(IEntity).IsAssignableFrom(property.ReturnType))
            {
                convertedNodes.Add(ConvertOneBack(value));
            }

            if (typeof(IEnumerable<IEntity>).IsAssignableFrom(property.ReturnType))
            {
                var convertedEntities=from entity in ((IEnumerable)value).Cast<IEntity>()
                                      select ConvertOneBack(entity);
                convertedNodes.AddRange(convertedEntities);
            }

            if ((value is IEnumerable)&&!(value is string))
            {
                Type targetType=property.ReturnType.GetGenericArguments().First();
                foreach (object item in (IEnumerable)value)
                {
                    bool canAddItem=true;
                    Type[] constraints=new Type[0];
                    if ((targetType.IsGenericParameter)&&((constraints=targetType.GetGenericParameterConstraints()).Length>0))
                    {
                        foreach (Type constraint in constraints)
                        {
                            if (!constraint.IsAssignableFrom(item.GetType()))
                            {
                                canAddItem=false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        canAddItem=targetType.IsAssignableFrom(item.GetType());
                    }

                    if (canAddItem)
                    {
                        var converter=_converters.UriNodeConverters.FirstOrDefault(c => c.CanConvertBack(item,property));
                        if (converter!=null)
                        {
                            convertedNodes.AddRange(converter.ConvertBack(item));
                        }
                        else
                        {
                            convertedNodes.Add(ConvertOneBack(item));
                        }
                    }
                }
            }
            else
            {
                convertedNodes.Add(ConvertOneBack(value));
            }

            return convertedNodes;
        }
        public string Resolve(MemberInfo info)
        {
            if (info == null)
            {
                return(null);
            }

            var name = info.Name;

            IPropertyMapping propertyMapping = null;

            if (this._settings.PropertyMappings.TryGetValue(info, out propertyMapping))
            {
                return(propertyMapping.Name);
            }

            var att = ElasticsearchPropertyAttributeBase.From(info);

            if (att != null && !att.Name.IsNullOrEmpty())
            {
                return(att.Name);
            }

            return(_settings.PropertyMappingProvider?.CreatePropertyMapping(info)?.Name ?? _settings.DefaultFieldNameInferrer(name));
        }
예제 #25
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="context"></param>
        /// <param name="tmpOutputTableName"></param>
        /// <param name="propertyMapping"></param>
        /// <param name="items"></param>
        internal static void LoadFromTmpOutputTable <TEntity>(this IDbContextWrapper context, string tmpOutputTableName,
                                                              IPropertyMapping propertyMapping, IList <TEntity> items)
        {
            var command    = $"SELECT {propertyMapping.ColumnName} FROM {tmpOutputTableName} ORDER BY {propertyMapping.ColumnName};";
            var identities = context.SqlQuery <int>(command).ToList();

            foreach (var result in identities)
            {
                var index    = identities.IndexOf(result);
                var property = items[index].GetType().GetProperty(propertyMapping.PropertyName);

                if (property != null && property.CanWrite)
                {
                    property.SetValue(items[index], result, null);
                }

                else
                {
                    throw new Exception();
                }
            }

            command = GetDropTableCommand(tmpOutputTableName);
            context.ExecuteSqlCommand(command);
        }
예제 #26
0
 /// <summary>
 /// Load all cached resources from the mapped property. The values of the mapped property are resolved when this method returns.
 /// </summary>
 /// <param name="propertyMapping"></param>
 private void LoadCachedValues(IPropertyMapping propertyMapping)
 {
     if (ResourceCache.HasCachedValues(propertyMapping))
     {
         ResourceCache.LoadCachedValues(propertyMapping);
     }
 }
예제 #27
0
        /// <summary>
        /// 排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">待排序的query</param>
        /// <param name="orderBy">从客户端传过来的排序字符串</param>
        /// <param name="propertyMapping">映射表</param>
        /// <returns></returns>
        public static IQueryable <T> ApplySort <T>(this IQueryable <T> source,
                                                   string orderBy, IPropertyMapping propertyMapping)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var mappingDictionary = propertyMapping.MappingDictionary;

            if (mappingDictionary == null)
            {
                throw new ArgumentNullException(nameof(mappingDictionary));
            }

            if (string.IsNullOrEmpty(orderBy))
            {
                return(source);
            }
            //将排序字符串分开
            var orderByAfterSplit = orderBy.Split(',');

            //遍历每一个排序属性
            foreach (var orderByClause in orderByAfterSplit.Reverse())
            {
                //把前后多余的空格去掉
                var trimmedOrderByCluse = orderByClause.Trim();
                //获得排序属性的最后是否以' desc'结尾
                var orderDescending = trimmedOrderByCluse.EndsWith(" desc");
                //找出第一个空格的位置
                var indexOffFirstSpace = trimmedOrderByCluse.IndexOf(" ", StringComparison.Ordinal);
                //拿到最终的属性,可以根据空格的位置获取,也可以根据是否以desc结尾获取
                var propertyName = indexOffFirstSpace == -1 ?
                                   trimmedOrderByCluse : trimmedOrderByCluse.Remove(indexOffFirstSpace);
                //判读映射表中是否包含这个属性,不包含则抛出异常
                if (!mappingDictionary.ContainsKey(propertyName))
                {
                    throw new ArgumentNullException(nameof(propertyName));
                }
                //获得映射后的属性list
                var mappedProperties = mappingDictionary[propertyName];
                if (mappedProperties == null)
                {
                    throw new ArgumentNullException(nameof(mappedProperties));
                }
                //必须反转
                mappedProperties.Reverse();
                foreach (var destinationProperty in mappedProperties)
                {
                    if (destinationProperty.Revert)
                    {
                        orderDescending = !orderDescending;
                    }
                    //真正的排序方法
                    source = source.OrderBy(destinationProperty.Name + (orderDescending ? " desc" : " asc"), "collate nocase");
                }
            }
            return(source);
        }
 private static void CopyAttributeToMapping(AssociationAttribute attr, IPropertyMapping belongsTo)
 {
     if (attr.IsForeignKey) belongsTo.Attributes[Constants.IsForeignKey] = "true";
     if (!string.IsNullOrEmpty(attr.ThisKey)) belongsTo.Attributes[Constants.ThisKey] = attr.ThisKey;
     if (!string.IsNullOrEmpty(attr.OtherKey)) belongsTo.Attributes[Constants.OtherKey] = attr.OtherKey;
     if(!string.IsNullOrEmpty(attr.DeleteRule)) belongsTo.Attributes[Constants.DeleteRule] = attr.DeleteRule;
     if(!string.IsNullOrEmpty(attr.Storage)) belongsTo.Attributes[Constants.Storage] = attr.Storage;
 }
예제 #29
0
 /// <summary>
 /// Adds a mapping for the target
 /// </summary>
 /// <param name="mapping"></param>
 public void AddMapping(IPropertyMapping mapping)
 {
     if (!PropertyMapLookup.Contains(mapping.TargetName))
     {
         PropertyMap.Add(mapping);
         PropertyMapLookup.Add(mapping.TargetName);
     }
 }
예제 #30
0
 /// <summary>
 /// Tests if the mapping has a certain cached values.
 /// </summary>
 /// <param name="mapping"></param>
 /// <param name="uri"></param>
 /// <returns></returns>
 public bool HasCachedValues(IPropertyMapping mapping, Uri uri)
 {
     if (Cache.ContainsKey(mapping))
     {
         return(Cache[mapping].Contains(uri));
     }
     return(false);
 }
예제 #31
0
        public virtual void AddPropertyToMapping(Property property, object value, bool fromModel)
        {
            if (value == null)
            {
                return;
            }

            if (property.Uri.OriginalString == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
            {
                Uri uri;

                if (value is IResource)
                {
                    uri = (value as IResource).Uri;
                }
                else if (value is Uri)
                {
                    uri = value as Uri;
                }
                else
                {
                    return;
                }

                if (GetTypes().Any(t => t.Uri == uri))
                {
                    return;
                }
            }

            IPropertyMapping propertyMapping = GetPropertyMapping(property, value.GetType());

            if (propertyMapping != null)
            {
                // yes, so we try to set or add it
                if (fromModel && value is IResource && propertyMapping.DataType != typeof(Uri) && propertyMapping.GenericType != typeof(Uri))
                {
                    // we generate the resource from the model, so we cache all mapped resources
                    ResourceCache.CacheValue(propertyMapping, (value as IResource).Uri);
                }
                else
                {
                    propertyMapping.SetOrAddMappedValue(value);
                }
            }
            // no, we add it to the property
            else if (_properties.ContainsKey(property))
            {
                _properties[property].Add(value);
            }
            else
            {
                _properties.Add(property, new HashSet <object>()
                {
                    value
                });
            }
        }
예제 #32
0
        private Uri SelectNamedGraph(IPropertyMapping property)
        {
            if (_overrideSourceGraph != null)
            {
                return(_overrideSourceGraph.SelectGraph(_selector));
            }

            return(_selector.SelectGraph(Id, _entityMapping, property));
        }
예제 #33
0
        private TypeInfo GetDictionaryType(IPropertyMapping property)
        {
            Type keyType        = property.ReturnType.GenericTypeArguments[0];
            Type valueType      = property.ReturnType.GenericTypeArguments[1];
            Type pairEntityType = _typeProvider.GetEntryType(property);
            Type ownerType      = _typeProvider.GetOwnerType(property);

            return(typeof(RdfDictionary <, , ,>).MakeGenericType(keyType, valueType, pairEntityType, ownerType).GetTypeInfo());
        }
        private Persister.Entity.IJoinable GetPathJoinable(string path)
        {
            // start with the root
            IJoinable last = rootPersister;

            var tokens = path.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            if (tokens.Length == 0)
            {
                return(last);
            }

            IPropertyMapping lastEntity = rootPersister;
            int i = 0;

            if (entityJoins.TryGetValue(tokens[0], out var entityJoinInfo))
            {
                last       = entityJoinInfo.Persister;
                lastEntity = (IPropertyMapping)last;
                i++;
            }

            string componentPath = string.Empty;

            for (; i < tokens.Length; i++)
            {
                componentPath += tokens[i];
                IType type = lastEntity.ToType(componentPath);
                if (type.IsAssociationType)
                {
                    if (type.IsCollectionType)
                    {
                        // ignore joinables for composite collections
                        var collectionType = (CollectionType)type;
                        var persister      = Factory.GetCollectionPersister(collectionType.Role);
                        if (persister.ElementType.IsEntityType == false)
                        {
                            return(null);
                        }
                    }
                    IAssociationType atype = (IAssociationType)type;

                    last          = atype.GetAssociatedJoinable(Factory);
                    lastEntity    = (NHibernate_Persister_Entity.IPropertyMapping)Factory.GetEntityPersister(atype.GetAssociatedEntityName(Factory));
                    componentPath = "";
                }
                else if (type.IsComponentType)
                {
                    componentPath += '.';
                }
                else
                {
                    throw new QueryException("not an association: " + componentPath);
                }
            }
            return(last);
        }
        private Type GetDictionaryType(IPropertyMapping property)
        {
            Type keyType = property.ReturnType.GenericTypeArguments[0];
            Type valueType = property.ReturnType.GenericTypeArguments[1];
            Type pairEntityType = _typeProvider.GetEntryType(property);
            Type ownerType = _typeProvider.GetOwnerType(property);

            return typeof(RdfDictionary<,,,>).MakeGenericType(keyType, valueType, pairEntityType, ownerType);
        }
        public Uri SelectGraph(EntityId entityId, IEntityMapping entityMapping, IPropertyMapping predicate)
        {
            EntityId nonBlankId = entityId;
            if (nonBlankId is BlankId)
            {
                nonBlankId = ((BlankId)nonBlankId).RootEntityId;
            }

            return new Uri(System.Text.RegularExpressions.Regex.Replace((nonBlankId != null ? nonBlankId.Uri.AbsoluteUri : ((BlankId)entityId).Graph.AbsoluteUri), "((?<!data.)magi)", "data.magi"));
        }
		public string ContinueFromManyToMany( System.Type clazz, string[ ] joinColumns, QueryTranslator q )
		{
			Start( q );
			continuation = true;
			currentName = q.CreateNameFor( clazz );
			q.AddType( currentName, clazz );
			IQueryable classPersister = q.GetPersister( clazz );
			join.AddJoin( classPersister.TableName, currentName, joinColumns, classPersister.IdentifierColumnNames, joinType );
			currentPropertyMapping = classPersister;
			return currentName;
		}
예제 #38
0
 // returns -1 if parameter is null
 public int Add(IPropertyMapping value)
 {
     if (value != null) {
         // throws NotSupportedException
         int i = List.Add(value);
         hash.Add(value.ColumnName, value);
         return i;
     }
     else {
         return -1;
     }
 }
        public Uri SelectGraph(EntityId entityId, IEntityMapping entityMapping, IPropertyMapping predicate)
        {
            if (entityId is BlankId)
            {
                EntityId nonBlankId = ((BlankId)entityId).RootEntityId;
                if (nonBlankId != null)
                {
                    entityId = nonBlankId;
                }
            }

            return entityId.Uri;
        }
        public IResultTransformer GetTransformer(IPropertyMapping property)
        {
            var collection = property as ICollectionMapping;
            if (collection != null)
            {
                switch (collection.StoreAs)
                {
                    case StoreAs.RdfList:
                        return new RdfListTransformer();
                    case StoreAs.SimpleCollection:
                        return new ObservableCollectionTransformer();
                }
            }

            return new SimpleTransformer(new OriginalResult());
        }
        /// <summary>Default constructor with base <see cref="System.Linq.Expressions.MemberExpression" />, <see cref="IPropertyMapping" /> and <see cref="Remotion.Linq.Clauses.FromClauseBase" />.</summary>
        /// <param name="expression">Base member expression.</param>
        /// <param name="propertyMapping">Ontology property mapping.</param>
        /// <param name="target">Target of the invocation.</param>
        /// <param name="name">Name of the element in the property.</param>
        internal EntityPropertyExpression(System.Linq.Expressions.MemberExpression expression, IPropertyMapping propertyMapping, Remotion.Linq.Clauses.FromClauseBase target, string name)
            : base()
        {
            if (!(expression.Member is PropertyInfo))
            {
                throw new ArgumentOutOfRangeException("expression");
            }

            if (name.Length == 0)
            {
                throw new ArgumentOutOfRangeException("name");
            }

            _expression = expression;
            _propertyMapping = propertyMapping;
            _target = target;
            _name = name;
        }
        /// <summary>
        /// Not used
        /// </summary>
        public IEnumerable<Node> ToNodes(object value, IEntityProxy proxy, IPropertyMapping property, IEntityContext context)
        {
            var dictionaryIface = typeof(IDictionary<,>).MakeGenericType(property.ReturnType.GenericTypeArguments);
            var dictionaryType = GetDictionaryType(property);

            if (!dictionaryIface.IsInstanceOfType(value))
            {
                throw new ArgumentException(string.Format("Value must be a of type {0}", dictionaryIface), "value");
            }

            var dictionary = value as IRdfDictionary;
            if (dictionary == null)
            {
                dictionary = (IRdfDictionary)dictionaryType.GetConstructors()
                                                         .Single(c => c.GetParameters().Length == 3)
                                                         .Invoke(new[] { proxy.Id, context, value });
            }

            return dictionary.DictionaryEntries.Select(entity => Node.FromEntityId(entity.Id));
        }
        /// <summary>Get an <see cref="ObservableCollection{T}"/> containing <paramref name="nodes"/>' values.</summary>
        public override object FromNodes(IEntityProxy parent, IPropertyMapping property, IEntityContext context, [AllowNull] IEnumerable<Node> nodes)
        {
            var convertedValues = nodes.Select(node => ((ICollectionMapping)property).ElementConverter.Convert(node, context));
            var collectionElements = ((IEnumerable<object>)Aggregator.Aggregate(convertedValues)).ToArray();

            var genericArguments = property.ReturnType.GetGenericArguments();
            if (typeof(IEntity).IsAssignableFrom(genericArguments.Single()))
            {
                genericArguments = new[] { typeof(IEntity) };
            }

            var castMethod = EnumerableCast.MakeGenericMethod(genericArguments);
            var convertedCollection = castMethod.Invoke(null, new object[] { collectionElements });
            var observable = (INotifyCollectionChanged)typeof(ObservableCollection<>).MakeGenericType(genericArguments)
                .GetConstructor(new[] { typeof(IEnumerable<>).MakeGenericType(genericArguments) })
                .Invoke(new[] { convertedCollection });

            observable.CollectionChanged += (sender, args) => Impromptu.InvokeSet(parent, property.Name, sender);
            return observable;
        }
        /// <inheritdoc />
        public IResultTransformer GetTransformer(IPropertyMapping property)
        {
            var collectionMapping = property as ICollectionMapping;
            if (collectionMapping != null)
            {
                if (collectionMapping.StoreAs == StoreAs.RdfList)
                {
                    return new RdfListTransformer();
                }

                if (collectionMapping.StoreAs == StoreAs.SimpleCollection)
                {
                    return new ObservableCollectionTransformer();
                }
            }
            else if (property is IDictionaryMapping)
            {
                return new DictionaryTransformer();
            }

            return new SimpleTransformer(new SingleOrDefault());
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="propertyName"></param>
		/// <param name="propertyType"></param>
		/// <param name="q"></param>
		/// <remarks>NOTE: we avoid joining to the next table if the named property is just the foreign key value</remarks>
		private void DereferenceEntity(string propertyName, EntityType propertyType, QueryTranslator q)
		{
			//if its "id"
			bool isIdShortcut = EntityID.Equals(propertyName) && !propertyType.IsUniqueKeyReference;

			//or its the id property name
			string idPropertyName;
			try
			{
				idPropertyName = propertyType.GetIdentifierOrUniqueKeyPropertyName(q.Factory);
			}
			catch (MappingException me)
			{
				throw new QueryException(me);
			}
			bool isNamedIdPropertyShortcut = idPropertyName != null && idPropertyName.Equals(propertyName);

			if (isIdShortcut || isNamedIdPropertyShortcut)
			{
				// special shortcut for id properties, skip the join!
				// this must only occur at the _end_ of a path expression
				DereferenceProperty(propertyName);
			}
			else
			{
				string entityClass = propertyType.GetAssociatedEntityName();
				string name = q.CreateNameFor(entityClass);
				q.AddType(name, entityClass);
				//String[] keyColNames = memberPersister.getIdentifierColumnNames();
				AddJoin(name, propertyType);
                if (propertyType.IsOneToOne)
                {
                    oneToOneOwnerName = currentName;
                }
                else
                {
                    oneToOneOwnerName = null;
                }
				ownerAssociationType = propertyType;
				currentName = name;
				currentProperty = propertyName;
				q.AddPathAliasAndJoin(path.ToString(0, path.ToString().LastIndexOf(StringHelper.Dot)), name, joinSequence.Copy());
				componentPath.Length = 0;
				currentPropertyMapping = q.GetPersister(entityClass);
			}
		}
		public void Token(string token, QueryTranslator q)
		{
			if (token != null)
			{
				path.Append(token);
			}

			string alias = q.GetPathAlias(path.ToString());
			if (alias != null)
			{
				Reset(q); //reset the dotcount (but not the path)
				currentName = alias; //after reset!
				currentPropertyMapping = q.GetPropertyMapping(currentName);
				if (!ignoreInitialJoin)
				{
					JoinSequence ojf = q.GetPathJoin(path.ToString());
					try
					{
						joinSequence.AddCondition(ojf.ToJoinFragment(q.EnabledFilters, true).ToWhereFragmentString); //after reset!
					}
					catch (MappingException me)
					{
						throw new QueryException(me);
					}
					// we don't need to worry about any condition in the ON clause
					// here (toFromFragmentString), since anything in the ON condition 
					// is already applied to the whole query
				}
			}
			else if (".".Equals(token))
			{
				dotcount++;
			}
			else
			{
				if (dotcount == 0)
				{
					if (!continuation)
					{
						if (!q.IsName(token))
						{
							throw new QueryException("undefined alias or unknown mapping: " + token);
						}
						currentName = token;
						currentPropertyMapping = q.GetPropertyMapping(currentName);
					}
				}
				else if (dotcount == 1)
				{
					if (currentName != null)
					{
						currentProperty = token;
					}
					else if (collectionName != null)
					{
						//IQueryableCollection p = q.GetCollectionPersister( collectionRole );
						//DoCollectionProperty( token, p, collectionName );
						continuation = false;
					}
					else
					{
						throw new QueryException("unexpected");
					}
				}
				else
				{
					// dotcount>=2

					// Do the corresponding RHS
					IType propertyType = PropertyType;

					if (propertyType == null)
					{
						throw new QueryException("unresolved property: " + currentProperty);
					}

					if (propertyType.IsComponentType)
					{
						DereferenceComponent(token);
					}
					else if (propertyType.IsEntityType)
					{
						DereferenceEntity(token, (EntityType) propertyType, q);
					}
					else if (propertyType.IsCollectionType)
					{
						DereferenceCollection(token, ((CollectionType) propertyType).Role, q);
					}
					else if (token != null)
					{
						throw new QueryException("dereferenced: " + currentProperty);
					}
				}
			}
		}
 private static Type GetOwnerType(IPropertyMapping property)
 {
     return EmitHelper.GetBuilder().GetType(string.Format("{0}_{1}_ListOwner", property.DeclaringType.FullName, property.Name), true);
 }
 /// <summary>Gets a node for each collection element.</summary>
 public override IEnumerable<Node> ToNodes(object collection, IEntityProxy proxy, IPropertyMapping property, IEntityContext context)
 {
     return from object value in (IEnumerable)collection
            select base.ToNodes(value, proxy, property, context).Single();
 }
 /// <summary>Default constructor with base <see cref="System.Linq.Expressions.MemberExpression" />, <see cref="IPropertyMapping" /> and <see cref="Remotion.Linq.Clauses.FromClauseBase" />.</summary>
 /// <param name="expression">Base member expression.</param>
 /// <param name="propertyMapping">Ontology property mapping.</param>
 /// <param name="target">Target of the invocation.</param>
 internal EntityPropertyExpression(System.Linq.Expressions.MemberExpression expression, IPropertyMapping propertyMapping, Remotion.Linq.Clauses.FromClauseBase target) :
     this(expression, propertyMapping, target, expression.Member.Name)
 {
 }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="q"></param>
		/// <returns></returns>
		public string AddFromCollection(QueryTranslator q)
		{
			IType collectionElementType = PropertyType;

			if (collectionElementType == null)
			{
				throw new QueryException(
					string.Format("must specify 'elements' for collection valued property in from clause: {0}", path));
			}
			if (collectionElementType.IsEntityType)
			{
				// an association
				IQueryableCollection collectionPersister = q.GetCollectionPersister(collectionRole);
				IQueryable entityPersister = (IQueryable) collectionPersister.ElementPersister;
				string clazz = entityPersister.EntityName;

				string elementName;
				if (collectionPersister.IsOneToMany)
				{
					elementName = collectionName;
					// allow index() function
					q.DecoratePropertyMapping(elementName, collectionPersister);
				}
				else
				{
					// many to many
					q.AddCollection(collectionName, collectionRole);
					elementName = q.CreateNameFor(clazz);
					AddJoin(elementName, (IAssociationType) collectionElementType);
				}
				q.AddFrom(elementName, clazz, joinSequence);
				currentPropertyMapping = new CollectionPropertyMapping(collectionPersister);
				return elementName;
			}
			
			// collection of values
			q.AddFromCollection(collectionName, collectionRole, joinSequence);
			return collectionName;
		}
		public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg,
		                                   ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			if (factory.Settings.IsStructuredCacheEntriesEnabled)
			{
				cacheEntryStructure = collection.IsMap
				                      	? (ICacheEntryStructure) new StructuredMapCacheEntry()
				                      	: (ICacheEntryStructure) new StructuredCollectionCacheEntry();
			}
			else
			{
				cacheEntryStructure = new UnstructuredCacheEntry();
			}

			dialect = factory.Dialect;
			sqlExceptionConverter = factory.SQLExceptionConverter;
			collectionType = collection.CollectionType;
			role = collection.Role;
			entityName = collection.OwnerEntityName;
			ownerPersister = factory.GetEntityPersister(entityName);
			queryLoaderName = collection.LoaderName;
			nodeName = collection.NodeName;
			isMutable = collection.IsMutable;

			Table table = collection.CollectionTable;
			fetchMode = collection.Element.FetchMode;
			elementType = collection.Element.Type;
			isPrimitiveArray = collection.IsPrimitiveArray;
			isArray = collection.IsArray;
			subselectLoadable = collection.IsSubselectLoadable;
			qualifiedTableName = table.GetQualifiedName(dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);

			int spacesSize = 1 + collection.SynchronizedTables.Count;
			spaces = new string[spacesSize];
			int ispa = 0;
			spaces[ispa++] = qualifiedTableName;
			foreach (string s in collection.SynchronizedTables)
			{
				spaces[ispa++] = s;
			}

			sqlOrderByString = collection.OrderBy;
			hasOrder = sqlOrderByString != null;
			sqlOrderByStringTemplate = hasOrder
			                           	? Template.RenderOrderByStringTemplate(sqlOrderByString, dialect,
			                           	                                       factory.SQLFunctionRegistry)
			                           	: null;
			sqlWhereString = !string.IsNullOrEmpty(collection.Where) ? '(' + collection.Where + ')' : null;
			hasWhere = sqlWhereString != null;
			sqlWhereStringTemplate = hasWhere
			                         	? Template.RenderWhereStringTemplate(sqlWhereString, dialect, factory.SQLFunctionRegistry)
			                         	: null;
			hasOrphanDelete = collection.HasOrphanDelete;
			int batch = collection.BatchSize;
			if (batch == -1)
			{
				batch = factory.Settings.DefaultBatchFetchSize;
			}
			batchSize = batch;

			isVersioned = collection.IsOptimisticLocked;

			keyType = collection.Key.Type;
			int keySpan = collection.Key.ColumnSpan;
			keyColumnNames = new string[keySpan];
			keyColumnAliases = new string[keySpan];
			int k = 0;
			foreach (Column col in collection.Key.ColumnIterator)
			{
				keyColumnNames[k] = col.GetQuotedName(dialect);
				keyColumnAliases[k] = col.GetAlias(dialect);
				k++;
			}
			ISet distinctColumns = new HashedSet();
			CheckColumnDuplication(distinctColumns, collection.Key.ColumnIterator);

			#region Element

			IValue element = collection.Element;
			if (!collection.IsOneToMany)
			{
				CheckColumnDuplication(distinctColumns, element.ColumnIterator);
			}

			string elemNode = collection.ElementNodeName;
			if (elementType.IsEntityType)
			{
				string _entityName = ((EntityType) elementType).GetAssociatedEntityName();
				elementPersister = factory.GetEntityPersister(_entityName);
				if (elemNode == null)
				{
					elemNode = cfg.GetClassMapping(_entityName).NodeName;
				}
				// NativeSQL: collect element column and auto-aliases
			}
			else
			{
				elementPersister = null;
			}
			elementNodeName = elemNode;

			int elementSpan = element.ColumnSpan;
			elementColumnAliases = new string[elementSpan];
			elementColumnNames = new string[elementSpan];
			elementFormulaTemplates = new string[elementSpan];
			elementFormulas = new string[elementSpan];
			elementColumnIsSettable = new bool[elementSpan];
			elementColumnIsInPrimaryKey = new bool[elementSpan];
			bool isPureFormula = true;
			bool hasNotNullableColumns = false;
			int j = 0;
			foreach (ISelectable selectable in element.ColumnIterator)
			{
				elementColumnAliases[j] = selectable.GetAlias(dialect);
				if (selectable.IsFormula)
				{
					Formula form = (Formula) selectable;
					elementFormulaTemplates[j] = form.GetTemplate(dialect, factory.SQLFunctionRegistry);
					elementFormulas[j] = form.FormulaString;
				}
				else
				{
					Column col = (Column) selectable;
					elementColumnNames[j] = col.GetQuotedName(dialect);
					elementColumnIsSettable[j] = true;
					elementColumnIsInPrimaryKey[j] = !col.IsNullable;
					if (!col.IsNullable)
					{
						hasNotNullableColumns = true;
					}

					isPureFormula = false;
				}
				j++;
			}
			elementIsPureFormula = isPureFormula;

			//workaround, for backward compatibility of sets with no
			//not-null columns, assume all columns are used in the
			//row locator SQL
			if (!hasNotNullableColumns)
			{
				ArrayHelper.Fill(elementColumnIsInPrimaryKey, true);
			}

			#endregion

			#region INDEX AND ROW SELECT

			hasIndex = collection.IsIndexed;
			if (hasIndex)
			{
				// NativeSQL: collect index column and auto-aliases
				IndexedCollection indexedCollection = (IndexedCollection) collection;
				indexType = indexedCollection.Index.Type;
				int indexSpan = indexedCollection.Index.ColumnSpan;
				indexColumnNames = new string[indexSpan];
				indexFormulaTemplates = new string[indexSpan];
				indexFormulas = new string[indexSpan];
				indexColumnIsSettable = new bool[indexSpan];
				indexColumnAliases = new string[indexSpan];
				bool hasFormula = false;
				int i = 0;
				foreach (ISelectable selectable in indexedCollection.Index.ColumnIterator)
				{
					indexColumnAliases[i] = selectable.GetAlias(dialect);
					if (selectable.IsFormula)
					{
						Formula indexForm = (Formula) selectable;
						indexFormulaTemplates[i] = indexForm.GetTemplate(dialect, factory.SQLFunctionRegistry);
						indexFormulas[i] = indexForm.FormulaString;
						hasFormula = true;
					}
					else
					{
						Column indexCol = (Column) selectable;
						indexColumnNames[i] = indexCol.GetQuotedName(dialect);
						indexColumnIsSettable[i] = true;
					}
					i++;
				}
				indexContainsFormula = hasFormula;
				baseIndex = indexedCollection.IsList ? ((List) indexedCollection).BaseIndex : 0;

				indexNodeName = indexedCollection.IndexNodeName;
				CheckColumnDuplication(distinctColumns, indexedCollection.Index.ColumnIterator);
			}
			else
			{
				indexContainsFormula = false;
				indexColumnIsSettable = null;
				indexFormulaTemplates = null;
				indexFormulas = null;
				indexType = null;
				indexColumnNames = null;
				indexColumnAliases = null;
				baseIndex = 0;
				indexNodeName = null;
			}

			hasIdentifier = collection.IsIdentified;
			if (hasIdentifier)
			{
				if (collection.IsOneToMany)
				{
					throw new MappingException("one-to-many collections with identifiers are not supported.");
				}
				IdentifierCollection idColl = (IdentifierCollection) collection;
				identifierType = idColl.Identifier.Type;

				Column col = null;
				foreach (Column column in idColl.Identifier.ColumnIterator)
				{
					col = column;
					break;
				}

				identifierColumnName = col.GetQuotedName(dialect);
				identifierColumnAlias = col.GetAlias(dialect);
				identifierGenerator =
					idColl.Identifier.CreateIdentifierGenerator(factory.Dialect, factory.Settings.DefaultCatalogName,
					                                            factory.Settings.DefaultSchemaName, null);
				// NH see : identityDelegate declaration
				IPostInsertIdentifierGenerator pig = (identifierGenerator as IPostInsertIdentifierGenerator);
				if (pig != null)
				{
					identityDelegate = pig.GetInsertGeneratedIdentifierDelegate(this, Factory, UseGetGeneratedKeys());
				}
				else
				{
					identityDelegate = null;
				}

				CheckColumnDuplication(distinctColumns, idColl.Identifier.ColumnIterator);
			}
			else
			{
				identifierType = null;
				identifierColumnName = null;
				identifierColumnAlias = null;
				identifierGenerator = null;
				identityDelegate = null;
			}

			#endregion

			#region GENERATE THE SQL

			// NH Different behavior : for the Insert SQL we are managing isPostInsertIdentifier (not supported in H3.2.5) 
			if (collection.CustomSQLInsert == null)
			{
				if (!IsIdentifierAssignedByInsert)
				{
					sqlInsertRowString = GenerateInsertRowString();
				}
				else
				{
					sqlInsertRowString = GenerateIdentityInsertRowString();
				}
				insertCallable = false;
				insertCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				SqlType[] parmsTypes = GenerateInsertRowString().ParameterTypes;
				sqlInsertRowString = new SqlCommandInfo(collection.CustomSQLInsert, parmsTypes);
				insertCallable = collection.IsCustomInsertCallable;
				insertCheckStyle = collection.CustomSQLInsertCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLInsert, insertCallable);
			}

			sqlUpdateRowString = GenerateUpdateRowString();
			if (collection.CustomSQLUpdate == null)
			{
				updateCallable = false;
				updateCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				sqlUpdateRowString = new SqlCommandInfo(collection.CustomSQLUpdate, sqlUpdateRowString.ParameterTypes);
				updateCallable = collection.IsCustomUpdateCallable;
				updateCheckStyle = collection.CustomSQLUpdateCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLUpdate, updateCallable);
			}

			sqlDeleteRowString = GenerateDeleteRowString();
			if (collection.CustomSQLDelete == null)
			{
				deleteCallable = false;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteRowString = new SqlCommandInfo(collection.CustomSQLDelete, sqlDeleteRowString.ParameterTypes);
				deleteCallable = collection.IsCustomDeleteCallable;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

			sqlDeleteString = GenerateDeleteString();
			if (collection.CustomSQLDeleteAll == null)
			{
				deleteAllCallable = false;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteString = new SqlCommandInfo(collection.CustomSQLDeleteAll, sqlDeleteString.ParameterTypes);
				deleteAllCallable = collection.IsCustomDeleteAllCallable;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

		    isCollectionIntegerIndex = collection.IsIndexed && !collection.IsMap;
			sqlDetectRowByIndexString = GenerateDetectRowByIndexString();
			sqlDetectRowByElementString = GenerateDetectRowByElementString();
			sqlSelectRowByIndexString = GenerateSelectRowByIndexString();

			LogStaticSQL();

			#endregion

			isLazy = collection.IsLazy;
			isExtraLazy = collection.ExtraLazy;
			isInverse = collection.IsInverse;

			if (collection.IsArray)
			{
				elementClass = ((Array) collection).ElementClass;
			}
			else
			{
				// for non-arrays, we don't need to know the element class
				elementClass = null;
			}

			if (elementType.IsComponentType)
			{
				elementPropertyMapping =
					new CompositeElementPropertyMapping(elementColumnNames, elementFormulaTemplates,
					                                    (IAbstractComponentType) elementType, factory);
			}
			else if (!elementType.IsEntityType)
			{
				elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
			}
			else
			{
				elementPropertyMapping = elementPersister as IPropertyMapping;
				if (elementPropertyMapping == null)
				{
					elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
				}
			}

			// Handle any filters applied to this collection
			filterHelper = new FilterHelper(collection.FilterMap, dialect, factory.SQLFunctionRegistry);

			// Handle any filters applied to this collection for many-to-many
			manyToManyFilterHelper = new FilterHelper(collection.ManyToManyFilterMap, dialect, factory.SQLFunctionRegistry);
			manyToManyWhereString = !string.IsNullOrEmpty(collection.ManyToManyWhere)
			                        	? "( " + collection.ManyToManyWhere + " )"
			                        	: null;
			manyToManyWhereTemplate = manyToManyWhereString == null
			                          	? null
			                          	: Template.RenderWhereStringTemplate(manyToManyWhereString, factory.Dialect,
			                          	                                     factory.SQLFunctionRegistry);
			manyToManyOrderByString = collection.ManyToManyOrdering;
			manyToManyOrderByTemplate = manyToManyOrderByString == null
			                            	? null
			                            	: Template.RenderOrderByStringTemplate(manyToManyOrderByString, factory.Dialect,
			                            	                                       factory.SQLFunctionRegistry);
			InitCollectionPropertyMap();
		}
예제 #52
0
		public void DecoratePropertyMapping(string name, IPropertyMapping mapping)
		{
			decoratedPropertyMappings.Add(name, mapping);
		}
		public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache,
		                                   ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			dialect = factory.Dialect;
			this.cache = cache;
			//sqlExceptionConverter = factory.SQLExceptionConverter;
			collectionType = collection.CollectionType;
			role = collection.Role;
			ownerClass = collection.OwnerClass;
			ownerPersister = factory.GetEntityPersister(ownerClass);
			queryLoaderName = collection.LoaderName;
			Alias alias = new Alias("__");

			sqlOrderByString = collection.OrderBy;
			hasOrder = sqlOrderByString != null;
			sqlOrderByStringTemplate = hasOrder
			                           	? Template.RenderOrderByStringTemplate(sqlOrderByString, dialect,
			                           	                                       factory.SQLFunctionRegistry) : null;

			sqlWhereString = collection.Where;
			hasWhere = sqlWhereString != null;
			sqlWhereStringTemplate = hasWhere
			                         	? Template.RenderWhereStringTemplate(sqlWhereString, dialect, factory.SQLFunctionRegistry)
			                         	: null;

			hasOrphanDelete = collection.OrphanDelete;

			batchSize = collection.BatchSize;
			isVersioned = collection.IsOptimisticLocked;

			keyType = collection.Key.Type;
			int keySpan = collection.Key.ColumnSpan;
			keyColumnNames = new string[keySpan];
			string[] keyAliases = new string[keySpan];
			int k = 0;
			foreach (Column col in collection.Key.ColumnCollection)
			{
				keyColumnNames[k] = col.GetQuotedName(dialect);
				keyAliases[k] = col.GetAlias(dialect);
				k++;
			}
			keyColumnAliases = alias.ToAliasStrings(keyAliases, dialect);
			//unquotedKeyColumnNames = StringHelper.Unquote( keyColumnAliases );
			ISet distinctColumns = new HashedSet();
			CheckColumnDuplication(distinctColumns, collection.Key.ColumnCollection);

			//isSet = collection.IsSet;
			//isSorted = collection.IsSorted;
			primitiveArray = collection.IsPrimitiveArray;
			array = collection.IsArray;
			subselectLoadable = collection.IsSubselectLoadable;

			IValue element = collection.Element;
			int elementSpan = element.ColumnSpan;
			Table table = collection.CollectionTable;
			fetchMode = element.FetchMode;
			elementType = element.Type;

			if (!collection.IsOneToMany)
			{
				CheckColumnDuplication(distinctColumns, element.ColumnCollection);
			}

			if (elementType.IsEntityType)
			{
				elementPersister = factory.GetEntityPersister(((EntityType) elementType).AssociatedClass);
			}
			else
			{
				elementPersister = null;
			}

			qualifiedTableName = table.GetQualifiedName(dialect, factory.DefaultSchema);
			elementColumnAliases = new string[elementSpan];
			elementColumnNames = new string[elementSpan];
			elementFormulaTemplates = new string[elementSpan];
			elementFormulas = new string[elementSpan];
			elementColumnIsSettable = new bool[elementSpan];
			elementColumnIsInPrimaryKey = new bool[elementSpan];
			int j = 0;
			foreach (ISelectable selectable in element.ColumnCollection)
			{
				elementColumnAliases[j] = selectable.GetAlias(dialect);
				if (selectable.IsFormula)
				{
					Formula form = (Formula) selectable;
					elementFormulaTemplates[j] = form.GetTemplate(dialect, factory.SQLFunctionRegistry);
					elementFormulas[j] = form.FormulaString;
				}
				else
				{
					Column col = (Column) selectable;
					elementColumnNames[j] = col.GetQuotedName(dialect);
					elementColumnIsSettable[j] = true;
					elementColumnIsInPrimaryKey[j] = !col.IsNullable;
				}
				j++;
			}

			hasIndex = collection.IsIndexed;

			if (hasIndex)
			{
				IndexedCollection indexedCollection = (IndexedCollection) collection;

				indexType = indexedCollection.Index.Type;
				int indexSpan = indexedCollection.Index.ColumnSpan;
				indexColumnNames = new string[indexSpan];

				string[] indexAliases = new string[indexSpan];
				int i = 0;
				foreach (Column indexCol in indexedCollection.Index.ColumnCollection)
				{
					indexAliases[i] = indexCol.GetAlias(dialect);
					indexColumnNames[i] = indexCol.GetQuotedName(dialect);
					i++;
				}
				indexColumnAliases = alias.ToAliasStrings(indexAliases, dialect);
				CheckColumnDuplication(distinctColumns, indexedCollection.Index.ColumnCollection);
			}
			else
			{
				indexType = null;
				indexColumnNames = null;
				indexColumnAliases = null;
			}

			hasIdentifier = collection.IsIdentified;

			if (hasIdentifier)
			{
				if (collection.IsOneToMany)
				{
					throw new MappingException("one-to-many collections with identifiers are not supported.");
				}
				IdentifierCollection idColl = (IdentifierCollection) collection;
				identifierType = idColl.Identifier.Type;

				Column col = null;
				foreach (Column column in idColl.Identifier.ColumnCollection)
				{
					col = column;
					break;
				}

				identifierColumnName = col.GetQuotedName(dialect);
				identifierColumnAlias = alias.ToAliasString(col.GetAlias(dialect), dialect);
				identifierGenerator = idColl.Identifier.CreateIdentifierGenerator(dialect);
				CheckColumnDuplication(distinctColumns, idColl.Identifier.ColumnCollection);
			}
			else
			{
				identifierType = null;
				identifierColumnName = null;
				identifierColumnAlias = null;
				identifierGenerator = null;
			}

			sqlInsertRowString = GenerateInsertRowString();
			if (collection.CustomSQLInsert == null)
			{
				insertCallable = false;
				insertCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				sqlInsertRowString = new SqlCommandInfo(collection.CustomSQLInsert, sqlInsertRowString.ParameterTypes);
				insertCallable = collection.IsCustomInsertCallable;
				insertCheckStyle = collection.CustomSQLInsertCheckStyle == null
				                   	? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLInsert, insertCallable)
				                   	: collection.CustomSQLInsertCheckStyle;
			}

			sqlUpdateRowString = GenerateUpdateRowString();
			if (collection.CustomSQLUpdate == null)
			{
				updateCallable = false;
				updateCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				sqlUpdateRowString = new SqlCommandInfo(collection.CustomSQLUpdate, sqlUpdateRowString.ParameterTypes);
				updateCallable = collection.IsCustomUpdateCallable;
				updateCheckStyle = collection.CustomSQLUpdateCheckStyle == null
				                   	? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLUpdate, updateCallable)
				                   	: collection.CustomSQLUpdateCheckStyle;
			}

			sqlDeleteRowString = GenerateDeleteRowString();
			if (collection.CustomSQLDelete == null)
			{
				deleteCallable = false;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteRowString = new SqlCommandInfo(collection.CustomSQLDelete, sqlDeleteRowString.ParameterTypes);
				deleteCallable = collection.IsCustomDeleteCallable;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

			sqlDeleteString = GenerateDeleteString();
			if (collection.CustomSQLDeleteAll == null)
			{
				deleteAllCallable = false;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteString = new SqlCommandInfo(collection.CustomSQLDeleteAll, sqlDeleteString.ParameterTypes);
				deleteAllCallable = collection.IsCustomDeleteAllCallable;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

			isLazy = collection.IsLazy;

			isInverse = collection.IsInverse;

			if (collection.IsArray)
			{
				elementClass = ((Array) collection).ElementClass;
			}
			else
			{
				// for non-arrays, we don't need to know the element class
				elementClass = null;
			}

			if (elementType.IsComponentType)
			{
				elementPropertyMapping = new CompositeElementPropertyMapping(
					elementColumnNames, elementFormulaTemplates,
					(IAbstractComponentType) elementType, factory);
			}
			else if (!elementType.IsEntityType)
			{
				elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
			}
			else
			{
				IEntityPersister persister = factory.GetEntityPersister(((EntityType) elementType).AssociatedClass);
				// Not all classpersisters implement IPropertyMapping!
				if (persister is IPropertyMapping)
				{
					elementPropertyMapping = (IPropertyMapping) persister;
				}
				else
				{
					elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
				}
			}

			// Handle any filters applied to this collection
			filterHelper = new FilterHelper(collection.FilterMap, dialect, factory.SQLFunctionRegistry);

			// Handle any filters applied to this collection for many-to-many
			manyToManyFilterHelper = new FilterHelper(collection.ManyToManyFilterMap, dialect, factory.SQLFunctionRegistry);
			manyToManyWhereString = StringHelper.IsNotEmpty(collection.ManyToManyWhere) ?
			                        "( " + collection.ManyToManyWhere + " )" :
			                        null;
			manyToManyWhereTemplate = manyToManyWhereString == null
			                          	?
			                          null
			                          	:
			                          Template.RenderWhereStringTemplate(manyToManyWhereString, factory.Dialect,
			                                                             factory.SQLFunctionRegistry);
				// , factory.getSqlFunctionRegistry() );
			manyToManyOrderByString = collection.ManyToManyOrdering;
			manyToManyOrderByTemplate = manyToManyOrderByString == null
			                            	? null
			                            	: Template.RenderOrderByStringTemplate(manyToManyOrderByString, factory.Dialect,
			                            	                                       factory.SQLFunctionRegistry);
				// , factory.getSqlFunctionRegistry() );

			InitCollectionPropertyMap();
		}
예제 #54
0
 internal ReferenceMapping(IPropertyMapping property, Type referenceModelType)
 {
     Property = property;
     ReferenceModelType = referenceModelType;
     Property.References(this);
 }
		public AbstractCollectionPersister( Mapping.Collection collection, ISessionFactoryImplementor factory )
		{
			this.factory = factory;
			dialect = factory.Dialect;
			//sqlExceptionConverter = factory.SQLExceptionConverter;
			collectionType = collection.CollectionType;
			role = collection.Role;
			ownerClass = collection.OwnerClass;
			Alias alias = new Alias( "__" );

			sqlOrderByString = collection.OrderBy;
			hasOrder = sqlOrderByString != null;
			sqlOrderByStringTemplate = hasOrder ? Template.RenderOrderByStringTemplate( sqlOrderByString, dialect ) : null;

			sqlWhereString = collection.Where;
			hasWhere = sqlWhereString != null;
			sqlWhereStringTemplate = hasWhere ? Template.RenderWhereStringTemplate( sqlWhereString, dialect ) : null;

			hasOrphanDelete = collection.OrphanDelete;

			batchSize = collection.BatchSize;

			cache = collection.Cache;

			keyType = collection.Key.Type;
			int keySpan = collection.Key.ColumnSpan;
			keyColumnNames = new string[keySpan];
			string[ ] keyAliases = new string[keySpan];
			int k = 0;
			foreach( Column col in collection.Key.ColumnCollection )
			{
				keyColumnNames[ k ] = col.GetQuotedName( dialect );
				keyAliases[ k ] = col.Alias( dialect );
				k++;
			}
			keyColumnAliases = alias.ToAliasStrings( keyAliases, dialect );
			//unquotedKeyColumnNames = StringHelper.Unquote( keyColumnAliases );
			ISet distinctColumns = new HashedSet();
			CheckColumnDuplication( distinctColumns, collection.Key.ColumnCollection );

			//isSet = collection.IsSet;
			//isSorted = collection.IsSorted;
			primitiveArray = collection.IsPrimitiveArray;
			array = collection.IsArray;

			IValue element = collection.Element;
			int elementSpan = element.ColumnSpan;
			ICollection iter = element.ColumnCollection;
			Table table = collection.CollectionTable;
			enableJoinedFetch = element.OuterJoinFetchSetting;
			elementType = element.Type;

			if( !collection.IsOneToMany )
			{
				CheckColumnDuplication( distinctColumns, element.ColumnCollection );
			}

			if( elementType.IsEntityType )
			{
				elementPersister = factory.GetPersister( ( ( EntityType ) elementType ).AssociatedClass );
			}
			else
			{
				elementPersister = null;
			}

			qualifiedTableName = table.GetQualifiedName( dialect, factory.DefaultSchema );
			string[ ] aliases = new string[elementSpan];
			elementColumnNames = new string[elementSpan];
			int j = 0;
			foreach( Column col in iter )
			{
				elementColumnNames[ j ] = col.GetQuotedName( dialect );
				aliases[ j ] = col.Alias( dialect );
				j++;
			}

			elementColumnAliases = alias.ToAliasStrings( aliases, dialect );

			IType selectColumns;
			string[ ] selectType;

			hasIndex = collection.IsIndexed;

			if( hasIndex )
			{
				IndexedCollection indexedCollection = ( IndexedCollection ) collection;

				indexType = indexedCollection.Index.Type;
				int indexSpan = indexedCollection.Index.ColumnSpan;
				indexColumnNames = new string[indexSpan];

				string[ ] indexAliases = new string[indexSpan];
				int i = 0;
				foreach( Column indexCol in indexedCollection.Index.ColumnCollection )
				{
					indexAliases[ i ] = indexCol.Alias( dialect );
					indexColumnNames[ i ] = indexCol.GetQuotedName( dialect );
					i++;
				}
				selectType = indexColumnNames;
				selectColumns = indexType;
				indexColumnAliases = alias.ToAliasStrings( indexAliases, dialect );
				CheckColumnDuplication( distinctColumns, indexedCollection.Index.ColumnCollection );
			}
			else
			{
				indexType = null;
				indexColumnNames = null;
				indexColumnAliases = null;
				selectType = elementColumnNames;
				selectColumns = elementType;
			}

			hasIdentifier = collection.IsIdentified;

			if( hasIdentifier )
			{
				if( collection.IsOneToMany )
				{
					throw new MappingException( "one-to-many collections with identifiers are not supported." );
				}
				IdentifierCollection idColl = ( IdentifierCollection ) collection;
				identifierType = idColl.Identifier.Type;

				Column col = null;
				foreach( Column column in idColl.Identifier.ColumnCollection )
				{
					col = column;
					break;
				}

				identifierColumnName = col.GetQuotedName( dialect );
				selectType = new string[ ] {identifierColumnName};
				selectColumns = identifierType;
				identifierColumnAlias = alias.ToAliasString( col.Alias( dialect ), dialect );
				unquotedIdentifierColumnName = identifierColumnAlias;
				identifierGenerator = idColl.Identifier.CreateIdentifierGenerator( dialect );
				CheckColumnDuplication( distinctColumns, idColl.Identifier.ColumnCollection );
			}
			else
			{
				identifierType = null;
				identifierColumnName = null;
				identifierColumnAlias = null;
				unquotedIdentifierColumnName = null;
				identifierGenerator = null;
			}

			rowSelectColumnNames = selectType;
			rowSelectType = selectColumns;

			sqlDeleteString = GenerateDeleteString();
			sqlInsertRowString = GenerateInsertRowString();
			sqlUpdateRowString = GenerateUpdateRowString();
			sqlDeleteRowString = GenerateDeleteRowString();
			isLazy = collection.IsLazy;

			isInverse = collection.IsInverse;

			if( collection.IsArray )
			{
				elementClass = ( ( Array ) collection ).ElementClass;
			}
			else
			{
				// for non-arrays, we don't need to know the element class
				elementClass = null;
			}

			initializer = CreateCollectionInitializer( factory );

			if( elementType.IsComponentType )
			{
				elementPropertyMapping = new CompositeElementPropertyMapping( elementColumnNames, ( IAbstractComponentType ) elementType, factory );
			}
			else if( !elementType.IsEntityType )
			{
				elementPropertyMapping = new ElementPropertyMapping( elementColumnNames, elementType );
			}
			else
			{
				IClassPersister persister = factory.GetPersister( ( ( EntityType ) elementType ).AssociatedClass );
				// Not all classpersisters implement IPropertyMapping!
				if( persister is IPropertyMapping )
				{
					elementPropertyMapping = ( IPropertyMapping ) persister;
				}
				else
				{
					elementPropertyMapping = new ElementPropertyMapping( elementColumnNames, elementType );
				}
			}
		}
		private void DereferenceCollection(String propertyName, String role, QueryTranslator q)
		{
			collectionRole = role;
			IQueryableCollection collPersister = q.GetCollectionPersister(role);
			string name = q.CreateNameForCollection(role);
			AddJoin(name, collPersister.CollectionType);

			//if ( collPersister.HasWhere ) 
			//{
			//    join.AddCondition( collPersister.GetSQLWhereString( name ) );
			//}

			collectionName = name;
			collectionOwnerName = currentName;
			currentName = name;
			currentProperty = propertyName;
			componentPath.Length = 0;
			//componentPath = new StringBuilder();
			currentPropertyMapping = new CollectionPropertyMapping(collPersister);
		}
		private void Reset(QueryTranslator q)
		{
			//join = q.CreateJoinFragment( useThetaStyleJoin );
			dotcount = 0;
			currentName = null;
			currentProperty = null;
			collectionName = null;
			collectionRole = null;
			componentPath.Length = 0;
			type = null;
			collectionName = null;
			columns = null;
			expectingCollectionIndex = false;
			continuation = false;
			currentPropertyMapping = null;
		}
		private void DereferenceCollection(String propertyName, String role, QueryTranslator q)
		{
			collectionRole = role;
			IQueryableCollection collPersister = q.GetCollectionPersister( role );
			string[] colNames = collPersister.KeyColumnNames;
			string name = q.CreateNameForCollection(role);
			AddJoin( collPersister.TableName, name, colNames );

			if ( collPersister.HasWhere ) 
			{
				join.AddCondition( collPersister.GetSQLWhereString( name ) );
			}
			collectionName = name;
			collectionOwnerName = currentName;
			currentName = name;
			currentProperty = propertyName;
			componentPath = null;
			//componentPath = new StringBuilder();
			currentPropertyMapping = new CollectionPropertyMapping( collPersister );
		}
		public string ContinueFromManyToMany(string clazz, string[] joinColumns, QueryTranslator q)
		{
			Start(q);
			continuation = true;
			currentName = q.CreateNameFor(clazz);
			q.AddType(currentName, clazz);
			IQueryable classPersister = q.GetPersister(clazz);
			AddJoin(currentName, TypeFactory.ManyToOne(clazz), joinColumns);
			currentPropertyMapping = classPersister;
			return currentName;
		}
예제 #60
0
 static SettingsService()
 {
     // static constructor
     Mapping = new JsonMapping();
 }