Esempio n. 1
0
 internal virtual ParameterVar ReplaceStrongSpatialParameterVar(ParameterVar oldVar)
 {
     return(this.ReplaceParameterVar(oldVar, (Func <TypeUsage, TypeUsage>)(t => TypeHelpers.CreateSpatialUnionTypeUsage(t))));
 }
Esempio n. 2
0
        private DbExpression AddFkRelatedEntityRefs(DbExpression viewConstructor)
        {
            // If the extent being simplified is not a C-Space entity set, or if it has already
            // been processed by the simplifier, then keep the original expression by returning
            // null.
            //
            if (doNotProcess)
            {
                return(null);
            }

            if (extent.BuiltInTypeKind != BuiltInTypeKind.EntitySet
                ||
                extent.EntityContainer.DataSpace != DataSpace.CSpace)
            {
                doNotProcess = true;
                return(null);
            }

            // Get a reference to the entity set being simplified, and find all the foreign key
            // (foreign key) associations for which the association set references that entity set,
            // with either association end.
            //
            var targetSet = (EntitySet)extent;
            var relSets   =
                targetSet.EntityContainer.BaseEntitySets
                .Where(es => es.BuiltInTypeKind == BuiltInTypeKind.AssociationSet)
                .Cast <AssociationSet>()
                .Where(
                    assocSet =>
                    assocSet.ElementType.IsForeignKey &&
                    assocSet.AssociationSetEnds.Any(se => se.EntitySet == targetSet)
                    )
                .ToList();

            // If no foreign key association sets that reference the entity set are present, then
            // no further processing is necessary, because FK-based related entity references cannot
            // be computed and added to the entities constructed for the entity set.
            if (relSets.Count == 0)
            {
                doNotProcess = true;
                return(null);
            }

            // For every relationship set that references this entity set, the relationship type and
            // foreign key constraint are used to determine if the entity set is the dependent set.
            // If it is the dependent set, then it is possible to augment the view definition with a
            // related entity ref that represents the navigation of the relationship set's relationship
            // from the dependent end (this entity set) to the the principal end (the entity set that
            // is referenced by the other association set end of the relationship set).
            //
            var principalSetsAndDependentTypes = new HashSet <Tuple <EntityType, AssociationSetEnd, ReferentialConstraint> >();

            foreach (var relSet in relSets)
            {
                // Retrieve the single referential constraint from the foreign key association, and
                // use it to determine whether the association set end that represents the dependent
                // end of the association references this entity set.
                //
                var fkConstraint    = relSet.ElementType.ReferentialConstraints[0];
                var dependentSetEnd = relSet.AssociationSetEnds[fkConstraint.ToRole.Name];

                if (dependentSetEnd.EntitySet == targetSet)
                {
                    var requiredSourceNavType =
                        (EntityType)TypeHelpers.GetEdmType <RefType>(dependentSetEnd.CorrespondingAssociationEndMember.TypeUsage).ElementType;
                    var principalSetEnd = relSet.AssociationSetEnds[fkConstraint.FromRole.Name];

                    // Record the entity type that an element of this dependent entity set must have in order
                    // to be a valid navigation source for the relationship set's relationship, along with the
                    // association set end for the destination (principal) end of the navigation and the FK
                    // constraint that is associated with the relationship type. This information may be used
                    // later to construct a related entity ref for any entity constructor expression in the view
                    // that produces an entity of the required source type or a subtype.
                    //
                    principalSetsAndDependentTypes.Add(Tuple.Create(requiredSourceNavType, principalSetEnd, fkConstraint));
                }
            }

            // If no foreign key association sets that use the entity set as the dependent set are present,
            // then no further processing is possible, since FK-based related entity refs can only be added
            // to the view definition for navigations from the dependent end of the relationship to the principal.
            //
            if (principalSetsAndDependentTypes.Count == 0)
            {
                doNotProcess = true;
                return(null);
            }

            // This rule supports a view that is capped with a projection of the form
            // (input).Project(x => new Entity())
            // or
            // (input).Project(x => CASE WHEN (condition1) THEN new Entity1() ELSE WHEN (condition2) THEN new Entity2()... ELSE new EntityN())
            // where every new instance expression Entity1()...EntityN() constructs an entity of a type
            // that is compatible with the entity set's element type.
            // Here, the list of all DbNewInstanceExpressions contained in the projection is remembered,
            // along with any CASE statement conditions, if present. These expressions will be updated
            // if necessary and used to build a new capping projection if any of the entity constructors
            // are augmented with FK-based related entity references.
            //
            var entityProject = (DbProjectExpression)viewConstructor;
            var constructors  = new List <DbNewInstanceExpression>();
            List <DbExpression> conditions = null;

            if (entityProject.Projection.ExpressionKind
                == DbExpressionKind.Case)
            {
                // If the projection is a DbCaseExpression, then every result must be a DbNewInstanceExpression
                var discriminatedConstructor = (DbCaseExpression)entityProject.Projection;
                conditions = new List <DbExpression>(discriminatedConstructor.When.Count);
                for (var idx = 0; idx < discriminatedConstructor.When.Count; idx++)
                {
                    conditions.Add(discriminatedConstructor.When[idx]);
                    constructors.Add((DbNewInstanceExpression)discriminatedConstructor.Then[idx]);
                }
                constructors.Add((DbNewInstanceExpression)discriminatedConstructor.Else);
            }
            else
            {
                // Otherwise, the projection must be a single DbNewInstanceExpression
                constructors.Add((DbNewInstanceExpression)entityProject.Projection);
            }

            var rebuildView = false;

            for (var idx = 0; idx < constructors.Count; idx++)
            {
                var entityConstructor     = constructors[idx];
                var constructedEntityType = TypeHelpers.GetEdmType <EntityType>(entityConstructor.ResultType);

                var relatedRefs =
                    principalSetsAndDependentTypes
                    .Where(psdt => constructedEntityType == psdt.Item1 || constructedEntityType.IsSubtypeOf(psdt.Item1))
                    .Select(
                        psdt => RelatedEntityRefFromAssociationSetEnd(constructedEntityType, entityConstructor, psdt.Item2, psdt.Item3))
                    .ToList();

                if (relatedRefs.Count > 0)
                {
                    if (entityConstructor.HasRelatedEntityReferences)
                    {
                        relatedRefs = entityConstructor.RelatedEntityReferences.Concat(relatedRefs).ToList();
                    }

                    entityConstructor = DbExpressionBuilder.CreateNewEntityWithRelationshipsExpression(
                        constructedEntityType, entityConstructor.Arguments, relatedRefs);
                    constructors[idx] = entityConstructor;
                    rebuildView       = true;
                }
            }

            // Default to returning null to indicate that this rule did not produce a modified expression
            //
            DbExpression result = null;

            if (rebuildView)
            {
                // rebuildView is true, so entity constructing DbNewInstanceExpression(s) were encountered
                // and updated with additional related entity refs. The DbProjectExpression that caps the
                // view definition therefore needs to be rebuilt and returned as the result of this rule.
                //
                if (conditions != null)
                {
                    // The original view definition projection was a DbCaseExpression.
                    // The new expression is also a DbCaseExpression that uses the conditions from the
                    // original expression together with the updated result expressions to produce the
                    // new capping projection.
                    //
                    var whens = new List <DbExpression>(conditions.Count);
                    var thens = new List <DbExpression>(conditions.Count);
                    for (var idx = 0; idx < conditions.Count; idx++)
                    {
                        whens.Add(conditions[idx]);
                        thens.Add(constructors[idx]);
                    }

                    result = entityProject.Input.Project(DbExpressionBuilder.Case(whens, thens, constructors[conditions.Count]));
                }
                else
                {
                    // Otherwise, the capping projection consists entirely of the updated DbNewInstanceExpression.
                    //
                    result = entityProject.Input.Project(constructors[0]);
                }
            }

            // Regardless of whether or not the view was updated, this rule should not be applied again during rule processing
            doNotProcess = true;
            return(result);
        }
Esempio n. 3
0
        public Value Interpret(Context.IContext context)
        {
            var leftResult  = _left.Interpret(context);
            var rightResult = _right.Interpret(context);

            if (leftResult.Type == ValueTypes.Bool && rightResult.Type == ValueTypes.Bool)
            {
                return(new Value(ValueTypes.Bool, TypeHelpers.Convert <bool>(leftResult) && TypeHelpers.Convert <bool>(rightResult)));
            }

            throw new SyntaxException($"{leftResult.Type} and {rightResult.Type} don't have AND operation.");
        }
Esempio n. 4
0
        private void UpdateEntry <TEntity>(IEntityWrapper wrappedEntity, EntityEntry existingEntry)
        {
            DebugCheck.NotNull(wrappedEntity);
            DebugCheck.NotNull(wrappedEntity.Entity);
            DebugCheck.NotNull(existingEntry);
            DebugCheck.NotNull(existingEntry.Entity);

            var clrType = typeof(TEntity);

            if (clrType != existingEntry.WrappedEntity.IdentityType)
            {
                var key = existingEntry.EntityKey;
                throw new NotSupportedException(
                          Strings.Materializer_RecyclingEntity(
                              TypeHelpers.GetFullName(key.EntityContainerName, key.EntitySetName), clrType.FullName,
                              existingEntry.WrappedEntity.IdentityType.FullName));
            }

            if (EntityState.Added
                == existingEntry.State)
            {
                throw new InvalidOperationException(Strings.Materializer_AddedEntityAlreadyExists(clrType.FullName));
            }

            if (MergeOption.AppendOnly != MergeOption)
            {
                // existing entity, update CSpace values in place
                Debug.Assert(EntityState.Added != existingEntry.State, "entry in State=Added");
                Debug.Assert(EntityState.Detached != existingEntry.State, "entry in State=Detached");

                if (MergeOption.OverwriteChanges == MergeOption)
                {
                    if (EntityState.Deleted
                        == existingEntry.State)
                    {
                        existingEntry.RevertDelete();
                    }
                    existingEntry.UpdateCurrentValueRecord(wrappedEntity.Entity);
                    Context.ObjectStateManager.ForgetEntryWithConceptualNull(existingEntry, resetAllKeys: true);
                    existingEntry.AcceptChanges();
                    Context.ObjectStateManager.FixupReferencesByForeignKeys(existingEntry, replaceAddedRefs: true);
                }
                else
                {
                    Debug.Assert(MergeOption.PreserveChanges == MergeOption, "not MergeOption.PreserveChanges");
                    if (EntityState.Unchanged
                        == existingEntry.State)
                    {
                        // same behavior as MergeOption.OverwriteChanges
                        existingEntry.UpdateCurrentValueRecord(wrappedEntity.Entity);
                        Context.ObjectStateManager.ForgetEntryWithConceptualNull(existingEntry, resetAllKeys: true);
                        existingEntry.AcceptChanges();
                        Context.ObjectStateManager.FixupReferencesByForeignKeys(existingEntry, replaceAddedRefs: true);
                    }
                    else
                    {
                        if (Context.ContextOptions.UseLegacyPreserveChangesBehavior)
                        {
                            // Do not mark properties as modified if they differ from the entity.
                            existingEntry.UpdateRecordWithoutSetModified(wrappedEntity.Entity, existingEntry.EditableOriginalValues);
                        }
                        else
                        {
                            // Mark properties as modified if they differ from the entity
                            existingEntry.UpdateRecordWithSetModified(wrappedEntity.Entity, existingEntry.EditableOriginalValues);
                        }
                    }
                }
            }
        }
Esempio n. 5
0
 protected static void AssertCollectionType(TypeUsage type)
 {
     Assert(TypeSemantics.IsCollectionType(type), "Type Mismatch: Expected Collection type: Found {0}", TypeHelpers.GetFullName(type));
 }
 public static IExtensibleModelBinder GetPossibleBinderInstance(Type closedModelType, Type openModelType, Type openBinderType)
 {
     Type[] typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(closedModelType, openModelType);
     return((typeArguments != null) ? (IExtensibleModelBinder)Activator.CreateInstance(openBinderType.MakeGenericType(typeArguments)) : null);
 }
Esempio n. 7
0
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            Check.NotNull(edmType, "edmType");

            Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            var primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw ADP1.Argument(EntityRes.GetString(EntityRes.ProviderDoesNotSupportType, edmType.EdmType));
            }

            var facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bit"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["uniqueidentifier"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Decimal:     // decimal, numeric, money
            {
                byte precision;
                if (!TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    precision = 18;
                }

                byte scale;
                if (!TypeHelpers.TryGetScale(edmType, out scale))
                {
                    scale = 0;
                }
                var tu = TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale);
                return(tu);
            }

            case PrimitiveTypeKind.Binary:     // binary, varbinary, image, timestamp, rowversion
            {
                var isFixedLength = null != facets[ProviderManifest.FixedLengthFacetName].Value &&
                                    (bool)facets[ProviderManifest.FixedLengthFacetName].Value;
                var f           = facets[ProviderManifest.MaxLengthFacetName];
                var isMaxLength = Helper.IsUnboundedFacetValue(f) || null == f.Value || (int)f.Value > binaryMaxSize;
                var maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;
                if (isFixedLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(
                        StoreTypeNameToStorePrimitiveType["binary"], true, (isMaxLength ? binaryMaxSize : maxLength));
                }
                else
                {
                    if (null == f.Value)
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, binaryMaxSize);
                    }
                    else if (Helper.IsUnboundedFacetValue(f) ||
                             edmType.EdmType.Name == "image")
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["image"], false);
                    }
                    else if ((int)f.Value > binaryMaxSize)
                    {
                        throw ADP1.ColumnGreaterThanMaxLengthNotSupported(edmType.EdmType.Name, binaryMaxSize);
                    }
                    else
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, maxLength);
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.String:
                //char, nchar, varchar, nvarchar, ntext, text, xml
            {
                var isFixedLength = null != facets[ProviderManifest.FixedLengthFacetName].Value &&
                                    (bool)facets[ProviderManifest.FixedLengthFacetName].Value;
                var f = facets[ProviderManifest.MaxLengthFacetName];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                var isMaxLength = Helper.IsUnboundedFacetValue(f) || null == f.Value || (int)f.Value > (nvarcharMaxSize);
                var maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;

                if (isFixedLength)
                {
                    tu = TypeUsage.CreateStringTypeUsage(
                        StoreTypeNameToStorePrimitiveType["nchar"], true, true, (isMaxLength ? nvarcharMaxSize : maxLength));
                }
                else
                {
                    if (null == f.Value)
                    {
                        // if it is unknown, fallback to nvarchar[4000] instead of ntext since it has limited store semantics
                        tu = TypeUsage.CreateStringTypeUsage(
                            StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, nvarcharMaxSize);
                    }
                    else if (Helper.IsUnboundedFacetValue(f) ||
                             edmType.EdmType.Name == "ntext")
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["ntext"], true, false);
                    }
                    else if ((int)f.Value > nvarcharMaxSize)
                    {
                        throw ADP1.ColumnGreaterThanMaxLengthNotSupported(edmType.EdmType.Name, nvarcharMaxSize);
                    }
                    else
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, maxLength);
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.DateTime:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            default:
                throw ADP1.NotSupported(
                          EntityRes.GetString(
                              EntityRes.NoStoreTypeForEdmType, TypeHelpers.GetIdentity(edmType), primitiveType.PrimitiveTypeKind));
            }
        }
Esempio n. 8
0
        public void Can_map_namespaceUri_to_assemblyqualifiedtypename()
        {
            var type = TypeHelpers.ResolveFullTypeName(namespaces, "Button");

            type.Should().Be(typeof(Button).AssemblyQualifiedName);
        }
Esempio n. 9
0
 /// <summary>Generates a property.</summary>
 /// <param name="property">The property.</param>
 /// <returns>The property.</returns>
 public virtual Property GenerateProperty(PropertyInfo property)
 {
     return(TypeHelpers.GenerateFeature(property.PropertyType, property.Name));
 }
Esempio n. 10
0
        /// <summary>
        /// Expects a reference to an array and an index on the stack.
        ///
        /// Pops both, and pushes the element in the array at the index onto the stack.
        /// </summary>
        public Emit <DelegateType> LoadElement(Type elementType)
        {
            if (elementType == null)
            {
                throw new ArgumentNullException("elementType");
            }

            OpCode?instr = null;

            IEnumerable <StackTransition> transitions = null;

            var arrType = elementType.MakeArrayType();

            if (elementType.IsPointer)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { elementType }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { elementType }),
                };

                instr = OpCodes.Ldelem_I;
            }

            if (!TypeHelpers.IsValueType(elementType) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { elementType }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { elementType }),
                };

                instr = OpCodes.Ldelem_Ref;
            }

            if (elementType == typeof(sbyte) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(int) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(int) }),
                };

                instr = OpCodes.Ldelem_I1;
            }

            if (elementType == typeof(byte) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(int) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(int) }),
                };

                instr = OpCodes.Ldelem_U1;
            }

            if (elementType == typeof(short) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(int) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(int) }),
                };

                instr = OpCodes.Ldelem_I2;
            }

            if (elementType == typeof(ushort) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(int) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(int) }),
                };

                instr = OpCodes.Ldelem_U2;
            }

            if (elementType == typeof(int) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(int) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(int) }),
                };

                instr = OpCodes.Ldelem_I4;
            }

            if (elementType == typeof(uint) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(int) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(int) }),
                };

                instr = OpCodes.Ldelem_U4;
            }

            if ((elementType == typeof(long) || elementType == typeof(ulong)) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(long) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(long) }),
                };

                instr = OpCodes.Ldelem_I8;
            }

            if (elementType == typeof(float) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(float) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(float) }),
                };

                instr = OpCodes.Ldelem_R4;
            }

            if (elementType == typeof(double) && !instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { typeof(double) }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { typeof(double) }),
                };

                instr = OpCodes.Ldelem_R8;
            }

            if (!instr.HasValue)
            {
                transitions =
                    new[]
                {
                    new StackTransition(new [] { typeof(NativeIntType), arrType }, new [] { elementType }),
                    new StackTransition(new [] { typeof(int), arrType }, new [] { elementType }),
                };

                UpdateState(OpCodes.Ldelem, elementType, Wrap(transitions, "LoadElement"));
                return(this);
            }

            UpdateState(instr.Value, Wrap(transitions, "LoadElement"));

            return(this);
        }
Esempio n. 11
0
 public void Setup()
 {
     TypeHelpers.Initialze(Css.DefaultCssNamespaceMapping, true);
 }
Esempio n. 12
0
        public BindableProperty GetDependencyProperty(Type bindableObjectType, string propertyName)
        {
            string dpName = $"{propertyName}Property";

            return(TypeHelpers.GetFieldValue(bindableObjectType, dpName) as BindableProperty);
        }
 public ReferenceInformation(ClrDump clrDump, ulong address, ulong refAddress) : this(clrDump, address)
 {
     FieldName = ClrDump.GetFieldNameReference(refAddress, address);
     FieldName = TypeHelpers.RealName(FieldName);
 }
Esempio n. 14
0
        internal virtual UnnestOp CreateUnnestOp(Var v)
        {
            Table tableInstance = this.CreateTableInstance(Command.CreateTableDefinition(TypeHelpers.GetEdmType <CollectionType>(v.Type).TypeUsage));

            return(this.CreateUnnestOp(v, tableInstance));
        }
Esempio n. 15
0
        /// <summary>Implements the visitor pattern for the type.</summary>
        /// <returns>The implemented visitor pattern.</returns>
        /// <param name="type">The type.</param>
        protected override EdmType VisitType(EdmType type)
        {
            var retType = type;

            if (BuiltInTypeKind.RefType
                == type.BuiltInTypeKind)
            {
                var refType          = (RefType)type;
                var mappedEntityType = (EntityType)VisitType(refType.ElementType);
                if (!ReferenceEquals(refType.ElementType, mappedEntityType))
                {
                    retType = new RefType(mappedEntityType);
                }
            }
            else if (BuiltInTypeKind.CollectionType
                     == type.BuiltInTypeKind)
            {
                var collectionType    = (CollectionType)type;
                var mappedElementType = VisitTypeUsage(collectionType.TypeUsage);
                if (!ReferenceEquals(collectionType.TypeUsage, mappedElementType))
                {
                    retType = new CollectionType(mappedElementType);
                }
            }
            else if (BuiltInTypeKind.RowType
                     == type.BuiltInTypeKind)
            {
                var rowType = (RowType)type;
                List <KeyValuePair <string, TypeUsage> > mappedPropInfo = null;
                for (var idx = 0; idx < rowType.Properties.Count; idx++)
                {
                    var originalProp   = rowType.Properties[idx];
                    var mappedPropType = VisitTypeUsage(originalProp.TypeUsage);
                    if (!ReferenceEquals(originalProp.TypeUsage, mappedPropType))
                    {
                        if (mappedPropInfo == null)
                        {
                            mappedPropInfo = new List <KeyValuePair <string, TypeUsage> >(
                                rowType.Properties.Select(
                                    prop => new KeyValuePair <string, TypeUsage>(prop.Name, prop.TypeUsage)
                                    ));
                        }
                        mappedPropInfo[idx] = new KeyValuePair <string, TypeUsage>(originalProp.Name, mappedPropType);
                    }
                }
                if (mappedPropInfo != null)
                {
                    var mappedProps = mappedPropInfo.Select(propInfo => new EdmProperty(propInfo.Key, propInfo.Value));
                    retType = new RowType(mappedProps, rowType.InitializerMetadata);
                }
            }
            else
            {
                if (!_metadata.TryGetType(type.Name, type.NamespaceName, type.DataSpace, out retType) ||
                    null == retType)
                {
                    throw new ArgumentException(Strings.Cqt_Copier_TypeNotFound(TypeHelpers.GetFullName(type.NamespaceName, type.Name)));
                }
            }

            return(retType);
        }
Esempio n. 16
0
 /// <summary>Generates a property.</summary>
 /// <param name="property">The property.</param>
 /// <returns>The property.</returns>
 public override Property GenerateProperty(PropertyInfo property)
 {
     return(TypeHelpers.GenerateLabel(property.PropertyType, property.Name));
 }
Esempio n. 17
0
        public Value Interpret(Context.IContext context)
        {
            var leftResult  = _left.Interpret(context);
            var rightResult = _right.Interpret(context);

            if (leftResult.Type == ValueTypes.Int && rightResult.Type == ValueTypes.Int)
            {
                return(new Value(ValueTypes.Int, TypeHelpers.Convert <int>(leftResult) - TypeHelpers.Convert <int>(rightResult)));
            }
            throw new SyntaxException($"{leftResult.Type} and {rightResult.Type} don't have SUBRACT operation.");
        }
Esempio n. 18
0
 public void TypeAllowsNullValueReturnsFalseForNonNullableGenericValueType()
 {
     Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(KeyValuePair <int, string>)));
 }
Esempio n. 19
0
        public override TypeUsage GetEdmType(TypeUsage storeType)
        {
            Check.NotNull(storeType, "storeType");

            var storeTypeName = storeType.EdmType.Name.ToLowerInvariant();

            if (!base.StoreTypeNameToEdmPrimitiveType.ContainsKey(storeTypeName))
            {
                throw ADP1.Argument(EntityRes.GetString(EntityRes.ProviderDoesNotSupportType, storeTypeName));
            }

            var edmPrimitiveType = base.StoreTypeNameToEdmPrimitiveType[storeTypeName];

            var maxLength   = 0;
            var isFixedLen  = false;
            var isUnbounded = true;

            PrimitiveTypeKind newPrimitiveTypeKind;

            switch (storeTypeName)
            {
            // for some types we just go with simple type usage with no facets
            case "tinyint":
            case "smallint":
            case "bigint":
            case "bit":
            case "uniqueidentifier":
            case "int":
                return(TypeUsage.CreateDefaultTypeUsage(edmPrimitiveType));

            case "nvarchar":
                newPrimitiveTypeKind = PrimitiveTypeKind.String;
                isUnbounded          = !TypeHelpers.TryGetMaxLength(storeType, out maxLength);
                isFixedLen           = false;
                break;

            case "nchar":
                newPrimitiveTypeKind = PrimitiveTypeKind.String;
                isUnbounded          = !TypeHelpers.TryGetMaxLength(storeType, out maxLength);
                isFixedLen           = true;
                break;

            case "ntext":
                newPrimitiveTypeKind = PrimitiveTypeKind.String;
                isUnbounded          = true;
                isFixedLen           = false;
                break;

            case "binary":
                newPrimitiveTypeKind = PrimitiveTypeKind.Binary;
                isUnbounded          = !TypeHelpers.TryGetMaxLength(storeType, out maxLength);
                isFixedLen           = true;
                break;

            case "varbinary":
                newPrimitiveTypeKind = PrimitiveTypeKind.Binary;
                isUnbounded          = !TypeHelpers.TryGetMaxLength(storeType, out maxLength);
                isFixedLen           = false;
                break;

            case "image":
                newPrimitiveTypeKind = PrimitiveTypeKind.Binary;
                isUnbounded          = true;
                isFixedLen           = false;
                break;

            case "timestamp":
            case "rowversion":
                return(TypeUsage.CreateBinaryTypeUsage(edmPrimitiveType, true, 8));

            case "float":
            case "real":
                return(TypeUsage.CreateDefaultTypeUsage(edmPrimitiveType));

            case "decimal":
            case "numeric":
            {
                byte precision;
                byte scale;
                if (TypeHelpers.TryGetPrecision(storeType, out precision) &&
                    TypeHelpers.TryGetScale(storeType, out scale))
                {
                    return(TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType, precision, scale));
                }
                else
                {
                    return(TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType));
                }
            }

            case "money":
                return(TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType, 19, 4));

            case "datetime":
                return(TypeUsage.CreateDateTimeTypeUsage(edmPrimitiveType, null));

            default:
                throw ADP1.NotSupported(EntityRes.GetString(EntityRes.ProviderDoesNotSupportType, storeTypeName));
            }

            Debug.Assert(
                newPrimitiveTypeKind == PrimitiveTypeKind.String || newPrimitiveTypeKind == PrimitiveTypeKind.Binary,
                "at this point only string and binary types should be present");

            switch (newPrimitiveTypeKind)
            {
            case PrimitiveTypeKind.String:
                if (!isUnbounded)
                {
                    return(TypeUsage.CreateStringTypeUsage(edmPrimitiveType, /*isUnicode*/ true, isFixedLen, maxLength));
                }
                else
                {
                    return(TypeUsage.CreateStringTypeUsage(edmPrimitiveType, /*isUnicode*/ true, isFixedLen));
                }

            case PrimitiveTypeKind.Binary:
                if (!isUnbounded)
                {
                    return(TypeUsage.CreateBinaryTypeUsage(edmPrimitiveType, isFixedLen, maxLength));
                }
                else
                {
                    return(TypeUsage.CreateBinaryTypeUsage(edmPrimitiveType, isFixedLen));
                }

            default:
                throw ADP1.NotSupported(EntityRes.GetString(EntityRes.ProviderDoesNotSupportType, storeTypeName));
            }
        }
Esempio n. 20
0
 public void TypeAllowsNullValueReturnsFalseForNonNullableGenericValueTypeDefinition()
 {
     Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(KeyValuePair <,>)));
 }
Esempio n. 21
0
        // <summary>
        // REQUIRES:: entity exists; MergeOption is AppendOnly
        // Handles state management for an entity with the given key. When the entity already exists
        // in the state manager, it is returned directly. Otherwise, the entityDelegate is invoked and
        // the resulting entity is returned.
        // </summary>
        public IEntityWrapper HandleEntityAppendOnly <TEntity>(
            Func <Shaper, IEntityWrapper> constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
        {
            Debug.Assert(MergeOption == MergeOption.AppendOnly, "only use HandleEntityAppendOnly when MergeOption is AppendOnly");
            DebugCheck.NotNull(constructEntityDelegate);

            IEntityWrapper result;

            if (null == (object)entityKey)
            {
                // no entity set, so no tracking is required for this entity, just
                // call the delegate to "materialize" it.
                result = constructEntityDelegate(this);
                RegisterMaterializedEntityForEvent(result);
            }
            else
            {
                Debug.Assert(null != entitySet, "if there is an entity key, there must also be an entity set");

                // check for an existing entity with the same key
                var existingEntry = Context.ObjectStateManager.FindEntityEntry(entityKey);
                if (null != existingEntry &&
                    !existingEntry.IsKeyEntry)
                {
                    Debug.Assert(existingEntry.EntityKey.Equals(entityKey), "Found ObjectStateEntry with wrong EntityKey");
                    if (typeof(TEntity)
                        != existingEntry.WrappedEntity.IdentityType)
                    {
                        var key = existingEntry.EntityKey;
                        throw new NotSupportedException(
                                  Strings.Materializer_RecyclingEntity(
                                      TypeHelpers.GetFullName(key.EntityContainerName, key.EntitySetName), typeof(TEntity).FullName,
                                      existingEntry.WrappedEntity.IdentityType.FullName));
                    }

                    if (EntityState.Added
                        == existingEntry.State)
                    {
                        throw new InvalidOperationException(
                                  Strings.Materializer_AddedEntityAlreadyExists(typeof(TEntity).FullName));
                    }
                    result = existingEntry.WrappedEntity;
                }
                else
                {
                    // We don't already have the entity, so construct it
                    result = constructEntityDelegate(this);
                    RegisterMaterializedEntityForEvent(result);
                    if (null == existingEntry)
                    {
                        Context.ObjectStateManager.AddEntry(result, entityKey, entitySet, "HandleEntity", false);
                    }
                    else
                    {
                        Context.ObjectStateManager.PromoteKeyEntry(
                            existingEntry, result, false, /*setIsLoaded*/ true, /*keyEntryInitialized*/ false);
                    }
                }
            }
            return(result);
        }
Esempio n. 22
0
 public void TypeAllowsNullValueReturnsFalseForNonNullableValueType()
 {
     Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(int)));
 }
Esempio n. 23
0
 protected static void AssertBoolean(TypeUsage type)
 {
     Assert(TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.Boolean), "Type Mismatch: Expected Boolean; found {0} instead", TypeHelpers.GetFullName(type));
 }
Esempio n. 24
0
 public void TypeAllowsNullValueReturnsTrueForInterfaceType()
 {
     Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(IDisposable)));
 }
Esempio n. 25
0
        private static DbExpression SimplifyNestedTphDiscriminator(DbExpression expression)
        {
            var entityProjection    = (DbProjectExpression)expression;
            var booleanColumnFilter = (DbFilterExpression)entityProjection.Input.Expression;
            var rowProjection       = (DbProjectExpression)booleanColumnFilter.Input.Expression;
            var discriminatorFilter = (DbFilterExpression)rowProjection.Input.Expression;

            var predicates         = FlattenOr(booleanColumnFilter.Predicate).ToList();
            var propertyPredicates =
                predicates.OfType <DbPropertyExpression>()
                .Where(
                    px => px.Instance.ExpressionKind == DbExpressionKind.VariableReference &&
                    ((DbVariableReferenceExpression)px.Instance).VariableName == booleanColumnFilter.Input.VariableName)
                .ToList();

            if (predicates.Count
                != propertyPredicates.Count)
            {
                return(null);
            }

            var predicateColumnNames = propertyPredicates.Select(px => px.Property.Name).ToList();

            var discriminatorPredicates = new Dictionary <object, DbComparisonExpression>();

            if (!TypeSemantics.IsEntityType(discriminatorFilter.Input.VariableType)
                ||
                !TryMatchDiscriminatorPredicate(discriminatorFilter, (compEx, discValue) => discriminatorPredicates.Add(discValue, compEx)))
            {
                return(null);
            }

            var discriminatorProp    = (EdmProperty)((DbPropertyExpression)(discriminatorPredicates.First().Value).Left).Property;
            var rowConstructor       = (DbNewInstanceExpression)rowProjection.Projection;
            var resultRow            = TypeHelpers.GetEdmType <RowType>(rowConstructor.ResultType);
            var inputPredicateMap    = new Dictionary <string, DbComparisonExpression>();
            var selectorPredicateMap = new Dictionary <string, DbComparisonExpression>();
            var columnValues         = new Dictionary <string, DbExpression>(rowConstructor.Arguments.Count);

            for (var idx = 0; idx < rowConstructor.Arguments.Count; idx++)
            {
                var propName  = resultRow.Properties[idx].Name;
                var columnVal = rowConstructor.Arguments[idx];
                if (predicateColumnNames.Contains(propName))
                {
                    if (columnVal.ExpressionKind
                        != DbExpressionKind.Case)
                    {
                        return(null);
                    }
                    var casePredicate = (DbCaseExpression)columnVal;
                    if (casePredicate.When.Count != 1
                        ||
                        !TypeSemantics.IsBooleanType(casePredicate.Then[0].ResultType) ||
                        !TypeSemantics.IsBooleanType(casePredicate.Else.ResultType)
                        ||
                        casePredicate.Then[0].ExpressionKind != DbExpressionKind.Constant ||
                        casePredicate.Else.ExpressionKind != DbExpressionKind.Constant
                        ||
                        (bool)((DbConstantExpression)casePredicate.Then[0]).Value != true ||
                        (bool)((DbConstantExpression)casePredicate.Else).Value)
                    {
                        return(null);
                    }

                    DbPropertyExpression comparedProp;
                    object constValue;
                    if (
                        !TryMatchPropertyEqualsValue(
                            casePredicate.When[0], rowProjection.Input.VariableName, out comparedProp, out constValue)
                        ||
                        comparedProp.Property != discriminatorProp
                        ||
                        !discriminatorPredicates.ContainsKey(constValue))
                    {
                        return(null);
                    }

                    inputPredicateMap.Add(propName, discriminatorPredicates[constValue]);
                    selectorPredicateMap.Add(propName, (DbComparisonExpression)casePredicate.When[0]);
                }
                else
                {
                    columnValues.Add(propName, columnVal);
                }
            }

            // Build a new discriminator-based filter that only includes the same rows allowed by the higher '_from0' column-based filter
            var newDiscriminatorPredicate = Helpers.BuildBalancedTreeInPlace(
                new List <DbExpression>(inputPredicateMap.Values), (left, right) => left.Or(right));

            discriminatorFilter = discriminatorFilter.Input.Filter(newDiscriminatorPredicate);

            var entitySelector = (DbCaseExpression)entityProjection.Projection;
            var newWhens       = new List <DbExpression>(entitySelector.When.Count);
            var newThens       = new List <DbExpression>(entitySelector.Then.Count);

            for (var idx = 0; idx < entitySelector.When.Count; idx++)
            {
                var propWhen   = (DbPropertyExpression)entitySelector.When[idx];
                var entityThen = (DbNewInstanceExpression)entitySelector.Then[idx];

                DbComparisonExpression discriminatorWhen;
                if (!selectorPredicateMap.TryGetValue(propWhen.Property.Name, out discriminatorWhen))
                {
                    return(null);
                }
                newWhens.Add(discriminatorWhen);

                var inputBoundEntityConstructor = ValueSubstituter.Substitute(entityThen, entityProjection.Input.VariableName, columnValues);
                newThens.Add(inputBoundEntityConstructor);
            }

            var newElse           = ValueSubstituter.Substitute(entitySelector.Else, entityProjection.Input.VariableName, columnValues);
            var newEntitySelector = DbExpressionBuilder.Case(newWhens, newThens, newElse);

            DbExpression result = discriminatorFilter.BindAs(rowProjection.Input.VariableName).Project(newEntitySelector);

            return(result);
        }
Esempio n. 26
0
 public void TypeAllowsNullValueReturnsTrueForNullableType()
 {
     Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(int?)));
 }
Esempio n. 27
0
 public bool IsMatch(Type type)
 {
     return(type.IsValueType && !type.IsEnum && !type.IsPrimitive && !TypeHelpers.IsSimpleType(type));
 }
Esempio n. 28
0
 public void TypeAllowsNullValueReturnsTrueForReferenceType()
 {
     Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(object)));
 }
Esempio n. 29
0
        internal Node GetInternalTree(Command targetIqtCommand, IList <Node> targetIqtArguments)
        {
            if (m_internalTreeNode == null)
            {
                var viewGenErrors = new List <EdmSchemaError>();
                DiscriminatorMap   discriminatorMap;
                DbQueryCommandTree tree = GenerateFunctionView(viewGenErrors, out discriminatorMap);
                if (viewGenErrors.Count > 0)
                {
                    throw new MappingException(Helper.CombineErrorMessage(viewGenErrors));
                }
                Debug.Assert(tree != null, "tree != null");

                // Convert this into an ITree first
                Command itree       = ITreeGenerator.Generate(tree, discriminatorMap);
                var     rootProject = itree.Root; // PhysicalProject(RelInput)
                PlanCompiler.Assert(rootProject.Op.OpType == OpType.PhysicalProject, "Expected a physical projectOp at the root of the tree - found " + rootProject.Op.OpType);
                var rootProjectOp = (PhysicalProjectOp)rootProject.Op;
                Debug.Assert(rootProjectOp.Outputs.Count == 1, "rootProjectOp.Outputs.Count == 1");
                var rootInput = rootProject.Child0; // the RelInput in PhysicalProject(RelInput)

                // #554756: VarVec enumerators are not cached on the shared Command instance.
                itree.DisableVarVecEnumCaching();

                // Function import returns a collection, so convert it to a scalar by wrapping into CollectOp.
                Node relNode = rootInput;
                Var  relVar  = rootProjectOp.Outputs[0];
                // ProjectOp does not implement Type property, so get the type from the column map.
                TypeUsage functionViewType = rootProjectOp.ColumnMap.Type;
                if (!Command.EqualTypes(functionViewType, this.FunctionImport.ReturnParameter.TypeUsage))
                {
                    Debug.Assert(TypeSemantics.IsPromotableTo(functionViewType, this.FunctionImport.ReturnParameter.TypeUsage), "Mapping expression result type must be promotable to the c-space function return type.");

                    // Build "relNode = Project(relNode, SoftCast(relVar))"
                    CollectionType expectedCollectionType = (CollectionType)this.FunctionImport.ReturnParameter.TypeUsage.EdmType;
                    var            expectedElementType    = expectedCollectionType.TypeUsage;

                    Node varRefNode     = itree.CreateNode(itree.CreateVarRefOp(relVar));
                    Node castNode       = itree.CreateNode(itree.CreateSoftCastOp(expectedElementType), varRefNode);
                    Node varDefListNode = itree.CreateVarDefListNode(castNode, out relVar);

                    ProjectOp projectOp = itree.CreateProjectOp(relVar);
                    relNode = itree.CreateNode(projectOp, relNode, varDefListNode);
                }

                // Build "Collect(PhysicalProject(relNode))
                m_internalTreeNode = itree.BuildCollect(relNode, relVar);
            }
            Debug.Assert(m_internalTreeNode != null, "m_internalTreeNode != null");

            // Prepare argument replacement dictionary
            Debug.Assert(m_commandParameters.Length == targetIqtArguments.Count, "m_commandParameters.Length == targetIqtArguments.Count");
            Dictionary <string, Node> viewArguments = new Dictionary <string, Node>(m_commandParameters.Length);

            for (int i = 0; i < m_commandParameters.Length; ++i)
            {
                var commandParam = (DbParameterReferenceExpression)m_commandParameters[i];
                var argumentNode = targetIqtArguments[i];

                // If function import parameter is of enum type, the argument value for it will be of enum type. We however have
                // converted enum types to underlying types for m_commandParameters. So we now need to softcast the argument
                // expression to the underlying type as well.
                if (TypeSemantics.IsEnumerationType(argumentNode.Op.Type))
                {
                    argumentNode = targetIqtCommand.CreateNode(
                        targetIqtCommand.CreateSoftCastOp(TypeHelpers.CreateEnumUnderlyingTypeUsage(argumentNode.Op.Type)),
                        argumentNode);
                }

                Debug.Assert(TypeSemantics.IsPromotableTo(argumentNode.Op.Type, commandParam.ResultType), "Argument type must be promotable to parameter type.");

                viewArguments.Add(commandParam.ParameterName, argumentNode);
            }

            return(FunctionViewOpCopier.Copy(targetIqtCommand, m_internalTreeNode, viewArguments));
        }
Esempio n. 30
0
 internal virtual ParameterVar ReplaceEnumParameterVar(ParameterVar oldVar)
 {
     return(this.ReplaceParameterVar(oldVar, (Func <TypeUsage, TypeUsage>)(t => TypeHelpers.CreateEnumUnderlyingTypeUsage(t))));
 }