Exemplo n.º 1
0
        /// <summary>
        /// Determines if this column is a narrower data type than another column.
        /// Used to determine if altering the supplied column definition to this definition will result in data loss.
        /// </summary>
        /// <param name="column"> The column to compare to. </param>
        /// <param name="providerManifest"> Details of the database provider being used. </param>
        /// <returns> True if this column is of a narrower data type. </returns>
        public bool IsNarrowerThan(ColumnModel column, DbProviderManifest providerManifest)
        {
            Check.NotNull <ColumnModel>(column, nameof(column));
            Check.NotNull <DbProviderManifest>(providerManifest, nameof(providerManifest));
            TypeUsage storeType1 = providerManifest.GetStoreType(this.TypeUsage);
            TypeUsage storeType2 = providerManifest.GetStoreType(column.TypeUsage);

            if (ColumnModel._typeSize[this.Type] >= ColumnModel._typeSize[column.Type])
            {
                bool?isUnicode1 = this.IsUnicode;
                if ((isUnicode1.HasValue ? (isUnicode1.GetValueOrDefault() ? 1 : 0) : 1) == 0)
                {
                    bool?isUnicode2 = column.IsUnicode;
                    if ((isUnicode2.HasValue ? (isUnicode2.GetValueOrDefault() ? 1 : 0) : 1) != 0)
                    {
                        goto label_6;
                    }
                }
                bool?isNullable1 = this.IsNullable;
                if ((isNullable1.HasValue ? (isNullable1.GetValueOrDefault() ? 1 : 0) : 1) == 0)
                {
                    bool?isNullable2 = column.IsNullable;
                    if ((isNullable2.HasValue ? (isNullable2.GetValueOrDefault() ? 1 : 0) : 1) != 0)
                    {
                        goto label_6;
                    }
                }
                return(ColumnModel.IsNarrowerThan(storeType1, storeType2));
            }
label_6:
            return(true);
        }
Exemplo n.º 2
0
        internal void Configure(
            DbDatabaseMapping databaseMapping,
            MappingFragment fragment,
            EntityType entityType,
            DbProviderManifest providerManifest)
        {
            EdmProperty edmProperty = fragment.Table.Properties.SingleOrDefault <EdmProperty>((Func <EdmProperty, bool>)(c => string.Equals(c.Name, this.Discriminator, StringComparison.Ordinal)));

            if (edmProperty != null && ValueConditionConfiguration.GetMappingFragmentsWithColumnAsDefaultDiscriminator(databaseMapping, fragment.Table, edmProperty).Any <MappingFragment>())
            {
                edmProperty.Name = fragment.Table.Properties.Select <EdmProperty, string>((Func <EdmProperty, string>)(p => p.Name)).Uniquify(edmProperty.Name);
                edmProperty      = (EdmProperty)null;
            }
            if (edmProperty == null)
            {
                edmProperty = new EdmProperty(this.Discriminator, providerManifest.GetStoreType(DatabaseMappingGenerator.DiscriminatorTypeUsage))
                {
                    Nullable = false
                };
                TablePrimitiveOperations.AddColumn(fragment.Table, edmProperty);
            }
            if (ValueConditionConfiguration.AnyBaseTypeToTableWithoutColumnCondition(databaseMapping, entityType, fragment.Table, edmProperty))
            {
                edmProperty.Nullable = true;
            }
            System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration configuration = edmProperty.GetConfiguration() as System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration;
            if (this.Value != null)
            {
                this.ConfigureColumnType(providerManifest, configuration, edmProperty);
                fragment.AddDiscriminatorCondition(edmProperty, this.Value);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(edmProperty.TypeName))
                {
                    TypeUsage storeType = providerManifest.GetStoreType(DatabaseMappingGenerator.DiscriminatorTypeUsage);
                    edmProperty.PrimitiveType = (PrimitiveType)storeType.EdmType;
                    edmProperty.MaxLength     = new int?(128);
                    edmProperty.Nullable      = false;
                }
                this.GetOrCreateConfiguration <System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration>().IsNullable = new bool?(true);
                fragment.AddNullabilityCondition(edmProperty, true);
            }
            if (this._configuration == null)
            {
                return;
            }
            string errorMessage;

            if (configuration != null && (configuration.OverridableConfigurationParts & OverridableConfigurationParts.OverridableInCSpace) != OverridableConfigurationParts.OverridableInCSpace && !configuration.IsCompatible(this._configuration, true, out errorMessage))
            {
                throw Error.ConflictingColumnConfiguration((object)edmProperty, (object)fragment.Table, (object)errorMessage);
            }
            if (this._configuration.IsNullable.HasValue)
            {
                edmProperty.Nullable = this._configuration.IsNullable.Value;
            }
            this._configuration.Configure(edmProperty, fragment.Table, providerManifest, false, false);
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Determines if this column is a narrower data type than another column.
        ///     Used to determine if altering the supplied column definition to this definition will result in data loss.
        /// </summary>
        /// <param name="column"> The column to compare to. </param>
        /// <param name="providerManifest"> Details of the database provider being used. </param>
        /// <returns> True if this column is of a narrower data type. </returns>
        public bool IsNarrowerThan(ColumnModel column, DbProviderManifest providerManifest)
        {
            Check.NotNull(column, "column");
            Check.NotNull(providerManifest, "providerManifest");

            var typeUsage      = providerManifest.GetStoreType(TypeUsage);
            var otherTypeUsage = providerManifest.GetStoreType(column.TypeUsage);

            return((_typeSize[Type] < _typeSize[column.Type]) ||
                   !(IsUnicode ?? true) && (column.IsUnicode ?? true) ||
                   !(IsNullable ?? true) && (column.IsNullable ?? true) ||
                   IsNarrowerThan(typeUsage, otherTypeUsage));
        }
        private void ConfigureRowsAffectedParameter(
            ModificationFunctionMapping modificationStoredProcedureMapping, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(modificationStoredProcedureMapping);
            DebugCheck.NotNull(providerManifest);

            if (!string.IsNullOrWhiteSpace(_rowsAffectedParameter))
            {
                if (modificationStoredProcedureMapping.RowsAffectedParameter == null)
                {
                    var rowsAffectedParameter
                        = new FunctionParameter(
                              "_RowsAffected_",
                              providerManifest.GetStoreType(
                                  TypeUsage.CreateDefaultTypeUsage(
                                      PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32))),
                              ParameterMode.Out);

                    modificationStoredProcedureMapping.Function.AddParameter(rowsAffectedParameter);
                    modificationStoredProcedureMapping.RowsAffectedParameter = rowsAffectedParameter;
                }

                modificationStoredProcedureMapping.RowsAffectedParameter.Name = _rowsAffectedParameter;

                _configuredParameters.Add(modificationStoredProcedureMapping.RowsAffectedParameter);
            }
        }
Exemplo n.º 5
0
        protected EdmProperty MapTableColumn(
            EdmProperty property,
            string columnName,
            bool isInstancePropertyOnDerivedType)
        {
            DebugCheck.NotNull(property);
            DebugCheck.NotEmpty(columnName);

            var underlyingTypeUsage
                = TypeUsage.Create(property.UnderlyingPrimitiveType, property.TypeUsage.Facets);

            var storeTypeUsage = _providerManifest.GetStoreType(underlyingTypeUsage);

            var tableColumnMetadata
                = new EdmProperty(columnName, storeTypeUsage)
                {
                Nullable = isInstancePropertyOnDerivedType || property.Nullable
                };

            if (tableColumnMetadata.IsPrimaryKeyColumn)
            {
                tableColumnMetadata.Nullable = false;
            }

            var storeGeneratedPattern = property.GetStoreGeneratedPattern();

            if (storeGeneratedPattern != null)
            {
                tableColumnMetadata.StoreGeneratedPattern = storeGeneratedPattern.Value;
            }

            MapPrimitivePropertyFacets(property, tableColumnMetadata, storeTypeUsage);

            return(tableColumnMetadata);
        }
Exemplo n.º 6
0
        private void ConfigureColumnType(
            DbProviderManifest providerManifest,
            Properties.Primitive.PrimitivePropertyConfiguration existingConfiguration,
            EdmProperty discriminatorColumn)
        {
            if (((existingConfiguration != null) &&
                 existingConfiguration.ColumnType != null) ||
                ((_configuration != null) &&
                 (_configuration.ColumnType != null)))
            {
                return;
            }

            PrimitiveType primitiveType;

            Value.GetType().IsPrimitiveType(out primitiveType);

            var edmType
                = (PrimitiveType)providerManifest.GetStoreType(
                      (primitiveType == PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String))
                        ? DatabaseMappingGenerator.DiscriminatorTypeUsage
                        : TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(primitiveType.PrimitiveTypeKind))).EdmType;

            if ((existingConfiguration != null) &&
                !discriminatorColumn.TypeName.Equals(edmType.Name, StringComparison.OrdinalIgnoreCase))
            {
                throw Error.ConflictingInferredColumnType(
                          discriminatorColumn.Name, discriminatorColumn.TypeName, edmType.Name);
            }

            discriminatorColumn.PrimitiveType = edmType;
        }
Exemplo n.º 7
0
        private static TypeUsage GetStoreTypeUsage(this EdmMember edmMember, DbProviderManifest providerManifest)
        {
            TypeUsage storeType = null;

            var conceptualType = edmMember.TypeUsage;

            Debug.Assert(conceptualType != null, "EdmMember's TypeUsage is null");
            if (conceptualType != null)
            {
                // if the EDM type is an enum, then we need to pass in the underlying type to the GetStoreType API.
                var enumType = conceptualType.EdmType as EnumType;
                storeType = (enumType != null)
                                ? providerManifest.GetStoreType(TypeUsage.CreateDefaultTypeUsage(enumType.UnderlyingType))
                                : providerManifest.GetStoreType(conceptualType);
            }
            return(storeType);
        }
        /// <summary>
        ///     Generates SQL to specify the data type of a column.
        ///     This method just generates the actual type, not the SQL to create the column.
        /// </summary>
        /// <param name="defaultValue"> The definition of the column. </param>
        /// <returns> SQL representing the data type. </returns>
        protected virtual string BuildColumnType(ColumnModel column)
        {
            Check.NotNull(column, "column");

            if (column.IsTimestamp)
            {
                return("rowversion");
            }

            var originalStoreTypeName = column.StoreType;

            if (string.IsNullOrWhiteSpace(originalStoreTypeName))
            {
                var typeUsage = _providerManifest.GetStoreType(column.TypeUsage).EdmType;

                originalStoreTypeName = typeUsage.Name;
            }

            var storeTypeName = originalStoreTypeName;

            const string MaxSuffix = "(max)";

            if (storeTypeName.EndsWith(MaxSuffix, StringComparison.Ordinal))
            {
                storeTypeName = Quote(storeTypeName.Substring(0, storeTypeName.Length - MaxSuffix.Length)) + MaxSuffix;
            }
            else
            {
                storeTypeName = Quote(storeTypeName);
            }

            switch (originalStoreTypeName)
            {
            case "decimal":
            case "numeric":
                storeTypeName += "(" + (column.Precision ?? DefaultNumericPrecision)
                                 + ", " + (column.Scale ?? DefaultScale) + ")";
                break;

            case "datetime2":
            case "datetimeoffset":
            case "time":
                storeTypeName += "(" + (column.Precision ?? DefaultTimePrecision) + ")";
                break;

            case "binary":
            case "varbinary":
            case "nvarchar":
            case "varchar":
            case "char":
            case "nchar":
                storeTypeName += "(" + (column.MaxLength ?? DefaultMaxLength) + ")";
                break;
            }

            return(storeTypeName);
        }
        private string BuildPropertyType(PropertyModel propertyModel)
        {
            DebugCheck.NotNull(propertyModel);

            var originalStoreTypeName = propertyModel.StoreType;

            if (string.IsNullOrWhiteSpace(originalStoreTypeName))
            {
                var typeUsage = _providerManifest.GetStoreType(propertyModel.TypeUsage).EdmType;

                originalStoreTypeName = typeUsage.Name;
            }

            var storeTypeName = originalStoreTypeName;

            const string MaxSuffix = "(max)";

            if (storeTypeName.EndsWith(MaxSuffix, StringComparison.Ordinal))
            {
                storeTypeName = Quote(storeTypeName.Substring(0, storeTypeName.Length - MaxSuffix.Length)) + MaxSuffix;
            }
            else
            {
                storeTypeName = Quote(storeTypeName);
            }

            switch (originalStoreTypeName)
            {
            case "decimal":
            case "numeric":
                storeTypeName += "(" + (propertyModel.Precision ?? DefaultNumericPrecision)
                                 + ", " + (propertyModel.Scale ?? DefaultScale) + ")";
                break;

            case "datetime2":
            case "datetimeoffset":
            case "time":
                storeTypeName += "(" + (propertyModel.Precision ?? DefaultTimePrecision) + ")";
                break;

            case "binary":
            case "varbinary":
            case "nvarchar":
            case "varchar":
            case "char":
            case "nchar":
                storeTypeName += "(" + (propertyModel.MaxLength ?? DefaultMaxLength) + ")";
                break;
            }

            return(storeTypeName);
        }
Exemplo n.º 10
0
        private string BuildParamType(ParameterModel param)
        {
            string        type = MySqlProviderServices.Instance.GetColumnType(_providerManifest.GetStoreType(param.TypeUsage));
            StringBuilder sb   = new StringBuilder();

            sb.Append(type);

            if (new string[] { "char", "varchar" }.Contains(type.ToLower()))
            {
                if (param.MaxLength.HasValue)
                {
                    sb.AppendFormat("({0}) ", param.MaxLength.Value);
                }
            }

            if (param.Precision.HasValue && param.Scale.HasValue)
            {
                sb.AppendFormat("( {0}, {1} ) ", param.Precision.Value, param.Scale.Value);
            }

            return(sb.ToString());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Builds a SQL property type fragment from the specified <see cref="ColumnModel"/>.
        /// </summary>
        public static string BuildPropertyType(DbProviderManifest providerManifest, PropertyModel column)
        {
            if (providerManifest == null || column == null)
            {
                return(string.Empty);
            }

            var originalStoreType = column.StoreType;

            if (string.IsNullOrWhiteSpace(originalStoreType))
            {
                var typeUsage = providerManifest.GetStoreType(column.TypeUsage).EdmType;
                originalStoreType = typeUsage.Name;
            }

            var storeType = originalStoreType;

            const string maxSuffix = "(max)";

            if (storeType.EndsWith(maxSuffix, StringComparison.Ordinal))
            {
                storeType = storeType.Substring(0, storeType.Length - maxSuffix.Length) + maxSuffix;
            }

            switch (originalStoreType.ToUpperInvariant())
            {
            case "DECIMAL":
            case "NUMERIC":
                storeType += "(" + (column.Precision ?? _defaultNumericPrecision)
                             + ", " + (column.Scale ?? _defaultNumericScale) + ")";
                break;

            case "DATETIME":
            case "TIME":
                storeType += "(" + (column.Precision ?? _defaultTimePrecision) + ")";
                break;

            case "BLOB":
            case "VARCHAR2":
            case "VARCHAR":
            case "CHAR":
            case "NVARCHAR":
            case "NVARCHAR2":
                storeType += "(" + (column.MaxLength ?? _defaultStringMaxLength) + ")";
                break;
            }

            return(storeType);
        }
Exemplo n.º 12
0
        private string ConstruirTipoPropriedade(ColumnModel propModeloPropriedade)
        {
            var lstrOriginalStoreTypeName = propModeloPropriedade.StoreType;

            if (string.IsNullOrWhiteSpace(lstrOriginalStoreTypeName))
            {
                var ltypeUsage = pprovProviderManifest.GetStoreType(propModeloPropriedade.TypeUsage).EdmType;
                lstrOriginalStoreTypeName = ltypeUsage.Name;
            }

            var lstrStoreTypeName = lstrOriginalStoreTypeName;

            const string lstrSufixoMax = "(max)";

            if (lstrStoreTypeName.EndsWith(lstrSufixoMax, StringComparison.Ordinal))
            {
                lstrStoreTypeName = lstrStoreTypeName.Substring(0, lstrStoreTypeName.Length - lstrSufixoMax.Length) + lstrSufixoMax;
            }

            switch (lstrOriginalStoreTypeName.ToLowerInvariant())
            {
            case "decimal":
            case "numeric":
                lstrStoreTypeName += "(" + (propModeloPropriedade.Precision ?? pintDefaultPrecisaoNumerica)
                                     + ", " + (propModeloPropriedade.Scale ?? pintDefaultEscala) + ")";
                break;

            case "datetime":
            case "time":
                lstrStoreTypeName += "(" + (propModeloPropriedade.Precision ?? pbytDefaultPrecisaoTempo) + ")";
                break;

            case "blob":
            case "varchar2":
            case "varchar":
            case "char":
            case "nvarchar":
            case "nvarchar2":
                lstrStoreTypeName += "(" + (propModeloPropriedade.MaxLength ?? pintDefaultStringMaxLength) + ")";
                break;
            }

            return(lstrStoreTypeName);
        }
Exemplo n.º 13
0
            /// <summary>
            ///     Builds a SQL property type fragment from the specified <see cref="ColumnModel" />.
            /// </summary>
            /// <param name="column"></param>
            /// <returns></returns>
            private string BuildPropertyType(ColumnModel column)
            {
                var originalStoreType = column.StoreType;

                if (string.IsNullOrWhiteSpace(originalStoreType))
                {
                    var typeUsage = _providerManifest.GetStoreType(column.TypeUsage).EdmType;
                    originalStoreType = typeUsage.Name;
                }

                var storeType = originalStoreType;

                const string maxSuffix = "(max)";

                if (storeType.EndsWith(maxSuffix, StringComparison.Ordinal))
                {
                    storeType = storeType.Substring(0, storeType.Length - maxSuffix.Length) + maxSuffix;
                }

                switch (originalStoreType.ToLowerInvariant())
                {
                case "decimal":
                case "numeric":
                    storeType += "(" + (column.Precision ?? DefaultNumericPrecision)
                                 + ", " + (column.Scale ?? DefaultNumericScale) + ")";
                    break;

                case "datetime":
                case "time":
                    storeType += "(" + (column.Precision ?? DefaultTimePrecision) + ")";
                    break;

                case "blob":
                case "varchar2":
                case "varchar":
                case "char":
                case "nvarchar":
                case "nvarchar2":
                    storeType += "(" + (column.MaxLength ?? DefaultStringMaxLength) + ")";
                    break;
                }

                return(storeType);
            }
Exemplo n.º 14
0
        private void ConfigureColumnType(
            DbProviderManifest providerManifest,
            System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration existingConfiguration,
            EdmProperty discriminatorColumn)
        {
            if (existingConfiguration != null && existingConfiguration.ColumnType != null || this._configuration != null && this._configuration.ColumnType != null)
            {
                return;
            }
            PrimitiveType primitiveType;

            this.Value.GetType().IsPrimitiveType(out primitiveType);
            PrimitiveType edmType = (PrimitiveType)providerManifest.GetStoreType(primitiveType == PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String) ? DatabaseMappingGenerator.DiscriminatorTypeUsage : TypeUsage.Create((EdmType)PrimitiveType.GetEdmPrimitiveType(primitiveType.PrimitiveTypeKind))).EdmType;

            if (existingConfiguration != null && !discriminatorColumn.TypeName.Equals(edmType.Name, StringComparison.OrdinalIgnoreCase))
            {
                throw Error.ConflictingInferredColumnType((object)discriminatorColumn.Name, (object)discriminatorColumn.TypeName, (object)edmType.Name);
            }
            discriminatorColumn.PrimitiveType = edmType;
        }
Exemplo n.º 15
0
        private void GenerateDiscriminators(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            foreach (var entitySetMapping in databaseMapping.GetEntitySetMappings())
            {
                if (entitySetMapping.EntityTypeMappings.Count() == 1)
                {
                    continue;
                }

                var typeUsage
                    = _providerManifest.GetStoreType(DiscriminatorTypeUsage);

                var discriminatorColumn
                    = new EdmProperty(DiscriminatorColumnName, typeUsage)
                    {
                    Nullable = false
                    };

                entitySetMapping
                .EntityTypeMappings
                .First()
                .MappingFragments
                .Single()
                .Table
                .AddColumn(discriminatorColumn);

                foreach (var entityTypeMapping in entitySetMapping.EntityTypeMappings)
                {
                    var entityTypeMappingFragment = entityTypeMapping.MappingFragments.Single();

                    entityTypeMappingFragment.SetDefaultDiscriminator(discriminatorColumn);

                    entityTypeMappingFragment
                    .AddDiscriminatorCondition(discriminatorColumn, entityTypeMapping.EntityType.Name);
                }
            }
        }
Exemplo n.º 16
0
 private void ConfigureRowsAffectedParameter(
     ModificationFunctionMapping modificationStoredProcedureMapping,
     DbProviderManifest providerManifest)
 {
     if (string.IsNullOrWhiteSpace(this._rowsAffectedParameter))
     {
         return;
     }
     if (modificationStoredProcedureMapping.RowsAffectedParameter == null)
     {
         FunctionParameter functionParameter = new FunctionParameter("_RowsAffected_", providerManifest.GetStoreType(TypeUsage.CreateDefaultTypeUsage((EdmType)PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32))), ParameterMode.Out);
         modificationStoredProcedureMapping.Function.AddParameter(functionParameter);
         modificationStoredProcedureMapping.RowsAffectedParameter = functionParameter;
     }
     modificationStoredProcedureMapping.RowsAffectedParameter.Name = this._rowsAffectedParameter;
     this._configuredParameters.Add(modificationStoredProcedureMapping.RowsAffectedParameter);
 }
Exemplo n.º 17
0
        protected virtual string Generate(ColumnModel op)
        {
            TypeUsage     typeUsage = _providerManifest.GetStoreType(op.TypeUsage);
            StringBuilder sb        = new StringBuilder();
            string        type      = MySqlProviderServices.Instance.GetColumnType(typeUsage);

            sb.Append(type);

            if (!type.EndsWith(")", StringComparison.InvariantCulture))
            {
                if ((op.ClrType == typeof(string)) ||
                    ((op.ClrType == typeof(byte)) && (op.ClrType.IsArray)))
                {
                    if (op.MaxLength.HasValue)
                    {
                        sb.AppendFormat("({0}) ", op.MaxLength.Value);
                    }
                }
                if (op.Precision.HasValue && op.Scale.HasValue)
                {
                    sb.AppendFormat("( {0}, {1} ) ", op.Precision.Value, op.Scale.Value);
                }
                else
                {
                    if (type == "datetime" || type == "timestamp" || type == "time")
                    {
                        if (op.Precision.HasValue && op.Precision.Value >= 1)
                        {
                            sb.AppendFormat("({0}) ", op.Precision.Value <= 6 ? op.Precision.Value : 6);
                        }
                        if (op.IsIdentity && (String.Compare(type, "datetime", true) == 0 || String.Compare(type, "timestamp", true) == 0))
                        {
                            sb.AppendFormat(" DEFAULT CURRENT_TIMESTAMP{0}", op.Precision.HasValue && op.Precision.Value >= 1 ? "( " + op.Precision.Value.ToString() + " )" : "");
                        }
                    }
                }
            }

            if (!(op.IsNullable ?? true))
            {
                sb.Append(string.Format("{0} not null ", ((!primaryKeyCols.Contains(op.Name) && op.IsIdentity) ? " unsigned" : "")));
            }
            if (op.IsIdentity && (new string[] { "tinyint", "smallint", "mediumint", "int", "bigint" }).Contains(type.ToLower()))
            {
                sb.Append(" auto_increment ");
                autoIncrementCols.Add(op.Name);
            }
            else
            {
                if (op.IsIdentity && String.Compare(type, "CHAR(36) BINARY", true) == 0)
                {
                    var createTrigger = new StringBuilder();
                    createTrigger.AppendLine(string.Format("DROP TRIGGER IF EXISTS `{0}_IdentityTgr`;", TrimSchemaPrefix(_tableName)));
                    createTrigger.AppendLine(string.Format("CREATE TRIGGER `{0}_IdentityTgr` BEFORE INSERT ON `{0}`", TrimSchemaPrefix(_tableName)));
                    createTrigger.AppendLine("FOR EACH ROW BEGIN");
                    createTrigger.AppendLine(string.Format("SET NEW.{0} = UUID();", op.Name));
                    createTrigger.AppendLine(string.Format("DROP TEMPORARY TABLE IF EXISTS tmpIdentity_{0};", TrimSchemaPrefix(_tableName)));
                    createTrigger.AppendLine(string.Format("CREATE TEMPORARY TABLE tmpIdentity_{0} (guid CHAR(36))ENGINE=MEMORY;", TrimSchemaPrefix(_tableName)));
                    createTrigger.AppendLine(string.Format("INSERT INTO tmpIdentity_{0} VALUES(New.{1});", TrimSchemaPrefix(_tableName), op.Name));
                    createTrigger.AppendLine("END");
                    var sqlOp = new SqlOperation(createTrigger.ToString());
                    _specialStmts.Add(Generate(sqlOp));
                }
            }
            if (!string.IsNullOrEmpty(op.DefaultValueSql))
            {
                sb.Append(string.Format(" default {0}", op.DefaultValueSql));
            }
            return(sb.ToString());
        }
Exemplo n.º 18
0
 public void GetStoreType_returns_correct_default_type_usages_for_all_primitive_types()
 {
     // SqlProvider does not support SByte
     foreach (var legacyEdmPrimitiveType in LegacyEdmPrimitiveTypes.Where(t => t.Key != "SByte"))
     {
         TypeUsageVerificationHelper.VerifyTypeUsagesEquivalent(
             LegacyProviderManifest.GetStoreType(
                 LegacyMetadata.TypeUsage.CreateDefaultTypeUsage(legacyEdmPrimitiveType.Value)),
             ProviderManifestWrapper.GetStoreType(
                 TypeUsage.CreateDefaultTypeUsage(EdmPrimitiveTypes[legacyEdmPrimitiveType.Key])));
     }
 }
Exemplo n.º 19
0
        internal void Configure(
            DbDatabaseMapping databaseMapping,
            StorageMappingFragment fragment,
            EntityType entityType,
            DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(fragment);
            DebugCheck.NotNull(providerManifest);

            var discriminatorColumn
                = fragment.Table.Properties
                  .SingleOrDefault(c => string.Equals(c.Name, Discriminator, StringComparison.Ordinal));

            if (discriminatorColumn == null)
            {
                var typeUsage
                    = providerManifest.GetStoreType(DatabaseMappingGenerator.DiscriminatorTypeUsage);

                discriminatorColumn
                    = new EdmProperty(Discriminator, typeUsage)
                    {
                    Nullable = false
                    };

                TablePrimitiveOperations.AddColumn(fragment.Table, discriminatorColumn);
            }

            if (AnyBaseTypeToTableWithoutColumnCondition(
                    databaseMapping, entityType, fragment.Table, discriminatorColumn))
            {
                discriminatorColumn.Nullable = true;
            }

            var existingConfiguration
                = discriminatorColumn.GetConfiguration() as Properties.Primitive.PrimitivePropertyConfiguration;

            if (Value != null)
            {
                ConfigureColumnType(providerManifest, existingConfiguration, discriminatorColumn);

                fragment.AddDiscriminatorCondition(discriminatorColumn, Value);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(discriminatorColumn.TypeName))
                {
                    var typeUsage
                        = providerManifest.GetStoreType(DatabaseMappingGenerator.DiscriminatorTypeUsage);

                    discriminatorColumn.PrimitiveType = (PrimitiveType)typeUsage.EdmType;
                    discriminatorColumn.MaxLength     = DatabaseMappingGenerator.DiscriminatorMaxLength;
                    discriminatorColumn.Nullable      = false;
                }

                GetOrCreateConfiguration <Properties.Primitive.PrimitivePropertyConfiguration>().IsNullable = true;

                fragment.AddNullabilityCondition(discriminatorColumn, true);
            }

            if (_configuration == null)
            {
                return;
            }

            if (existingConfiguration != null)
            {
                string errorMessage;
                if ((existingConfiguration.OverridableConfigurationParts &
                     OverridableConfigurationParts.OverridableInCSpace) !=
                    OverridableConfigurationParts.OverridableInCSpace &&
                    !existingConfiguration.IsCompatible(
                        _configuration, inCSpace: true, errorMessage: out errorMessage))
                {
                    throw Error.ConflictingColumnConfiguration(discriminatorColumn, fragment.Table, errorMessage);
                }
            }

            if (_configuration.IsNullable != null)
            {
                discriminatorColumn.Nullable = _configuration.IsNullable.Value;
            }

            _configuration.Configure(discriminatorColumn, fragment.Table, providerManifest);
        }