Exemplo n.º 1
0
        public void TestAddPrimaryKeyNoEscapeNames()
        {
            //arrange
            var migration = new DdlGeneratorFactory(SqlType.SqlServer).MigrationGenerator();

            migration.EscapeNames = false;

            var schema = new DatabaseSchema(null, SqlType.SqlServer);
            var table  = schema.AddTable("Test")
                         .AddColumn <int>("Id")
                         .AddColumn <string>("Name")
                         .Table;
            var pk = new DatabaseConstraint
            {
                Name           = "Test_PK",
                ConstraintType = ConstraintType.PrimaryKey
            };

            pk.Columns.Add("Id");

            //act
            var sql = migration.AddConstraint(table, pk);

            //assert
            Assert.IsTrue(sql.IndexOf("ADD CONSTRAINT Test_PK PRIMARY KEY (Id)", StringComparison.OrdinalIgnoreCase) != -1, "adding a primary key");
        }
        public void GivenUniqueConstraintWithChangedColumn()
        {
            //arrange
            DatabaseSchema     schema1    = CreateSchema();
            DatabaseConstraint constraint = GetUniqueConstraint();

            schema1.Tables[0].AddConstraint(constraint);

            DatabaseSchema     schema2     = CreateSchema();
            DatabaseConstraint constraint2 = GetUniqueConstraint();

            constraint2.Columns[0] = "Desc";
            schema2.Tables[0].AddConstraint(constraint2);

            //act
            var comparison = new CompareSchemas(schema1, schema2);
            var result     = comparison.ExecuteResult();

            //assert
            var changeConstraint = result.FirstOrDefault(x =>
                                                         x.ResultType == ResultType.Change &&
                                                         x.SchemaObjectType == SchemaObjectType.Constraint &&
                                                         x.TableName == "Orders" &&
                                                         x.Name == "UK_NAME");

            Assert.IsNotNull(changeConstraint);
        }
        private static DatabaseSchema Arrange()
        {
            const string key1 = "OriginKey1";
            const string key2 = "OriginKey2";

            var schema = new DatabaseSchema(null, null);
            var table  = schema.AddTable("Products")
                         .AddColumn("ProductId", "INT").AddPrimaryKey().AddIdentity()
                         .AddColumn("ProductName", "NVARCHAR")
                         .AddColumn(key1, "NVARCHAR").AddForeignKey("Origin")
                         .AddColumn(key2, "NVARCHAR")
                         .Table;

            table.ForeignKeys.Single().AddColumn(table.FindColumn(key2));

            var pk = new DatabaseConstraint {
                ConstraintType = ConstraintType.PrimaryKey,
            };

            pk.Columns.Add(key1);
            pk.Columns.Add(key2);
            schema.AddTable("Origin")
            .AddColumn <string>(key1).AddPrimaryKey()
            .AddColumn <string>(key2)
            .Table.AddConstraint(pk);

            schema.DataTypes.Add(new DataType("INT", "System.Int32"));
            schema.DataTypes.Add(new DataType("NVARCHAR", "System.String"));
            DatabaseSchemaFixer.UpdateDataTypes(schema);
            //make sure .Net names are assigned
            PrepareSchemaNames.Prepare(schema, new Namer());

            return(schema);
        }
Exemplo n.º 4
0
        public virtual string AddConstraint(DatabaseTable databaseTable, DatabaseConstraint constraint)
        {
            //we always use the named form.
            var constraintName = constraint.Name;

            if (string.IsNullOrEmpty(constraintName))
            {
                throw new InvalidOperationException("Constraint must have a name");
            }
            //primary, unique and foreign key constraints must have columns
            if (constraint.Columns.Count == 0 && constraint.ConstraintType != ConstraintType.Check)
            {
                throw new InvalidOperationException("Constraint has no columns");
            }

            //use the standard constraint writer for the database
            var constraintWriter = _ddlFactory.ConstraintWriter(databaseTable);

            if (constraintWriter == null)
            {
                return(null);
            }
            constraintWriter.IncludeSchema = IncludeSchema; //cascade setting
            constraintWriter.EscapeNames   = EscapeNames;
            return(constraintWriter.WriteConstraint(constraint));
        }
        public void TestSqlServerAddDefaultConstraint()
        {
            //arrange
            var migration = new DdlGeneratorFactory(SqlType.SqlServer).MigrationGenerator();

            var table = MigrationCommon.CreateTestTable("Orders");

            table.SchemaOwner = "dbo";
            var column = table.FindColumn("NAME");

            column.Length       = 40;
            column.DefaultValue = "'?'";
            //add a default constraint
            var df = new DatabaseConstraint {
                ConstraintType = ConstraintType.Default, Name = "DF_Orders_Name", Expression = "'?'"
            };

            df.Columns.Add("NAME");
            table.AddConstraint(df);

            //act
            var sql = migration.AddConstraint(table, df);

            //assert
            //ALTER TABLE [dbo].[Orders] ADD CONSTRAINT [DF_Orders_Name] DEFAULT '?' FOR [NAME];

            Assert.IsTrue(sql.Contains("ADD CONSTRAINT [DF_Orders_Name] DEFAULT '?' FOR [NAME]"), "add constraint");
        }
Exemplo n.º 6
0
        public override string WritePrimaryKey(DatabaseConstraint constraint)
        {
            if (constraint == null)
            {
                return(null);
            }
            var columnList = GetColumnList(constraint.Columns);

            var pkName       = ConstraintName(constraint);
            var nonClustered = "";

            if (constraint.Columns.Count == 1)
            {
                //UNIQUEIDENTIFIERs may have NON CLUSTERED indexes
                //the pk index will have IndexType of PRIMARY NONCLUSTERED
                var pkIndex = Table.Indexes.Find(x => x.IndexType?.IndexOf("PRIMARY", StringComparison.OrdinalIgnoreCase) != -1);
                if (pkIndex != null &&
                    pkIndex.IndexType?.IndexOf("NONCLUSTERED", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    nonClustered = "NONCLUSTERED";
                }
            }

            return(string.Format(CultureInfo.InvariantCulture,
                                 @"ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY {2}({3})",
                                 TableName(Table),
                                 EscapeName(pkName),
                                 nonClustered,
                                 columnList) + SqlFormatProvider().LineEnding());
        }
Exemplo n.º 7
0
        /// <summary>
        /// KL:
        /// Similar to WriteColumn. Will send the appropriate dataType and propertyName to
        /// _cb.AppendAutomaticProperty to be written.
        ///
        /// This method was needed to support composite foreign keys.
        /// </summary>
        /// <param name="fKey"></param>
        private void WriteForeignKey(DatabaseConstraint fKey)
        {
            var propertyName = "Unknown";

            // get the reference table
            var refTable = _table.DatabaseSchema.FindTableByName(fKey.RefersToTable);

            // get the parent table
            var parentTable = _table.DatabaseSchema.FindTableByName(fKey.TableName);

            if (refTable != null)
            {
                propertyName = refTable.NetName;
            }

            var dataType = propertyName;

            // Check whether the referenced table is used in any other key. This ensures that the property names
            // are unique.
            if (parentTable.ForeignKeys.Count(x => x.RefersToTable == fKey.RefersToTable) > 1)
            {
                // Append the key name to the property name. In the event of multiple foreign keys to the same table
                // This will give the consumer context.
                propertyName += fKey.Name;
            }

            // Ensures that property name cannot be the same as class name
            if (propertyName == parentTable.NetName)
            {
                propertyName += "Key";
            }

            _cb.AppendAutomaticProperty(dataType, propertyName);
        }
        public void TestSqlServerDropColumnWithDefault()
        {
            //arrange
            var migration = new DdlGeneratorFactory(SqlType.SqlServer).MigrationGenerator();

            var table = MigrationCommon.CreateTestTable("Orders");

            table.SchemaOwner = "dbo";
            var column = table.FindColumn("NAME");

            column.Length       = 40;
            column.DefaultValue = "'?'";
            //add a default constraint
            var df = new DatabaseConstraint {
                ConstraintType = ConstraintType.Default, Name = "DF_Orders_Name"
            };

            df.Columns.Add("NAME");
            table.AddConstraint(df);

            //act
            var sql = migration.DropColumn(table, column);

            //assert
            // No longer true for SQL server - DROP CONSTRAINT is done by constraint deltas
            //ALTER TABLE [dbo].[Orders] DROP CONSTRAINT [DF_Orders_Name];
            //ALTER TABLE [dbo].[Orders] DROP COLUMN [NAME];

            //Assert.IsTrue(sql.Contains("DROP CONSTRAINT [DF_Orders_Name]"), "drop constraint");
            Assert.IsTrue(sql.Contains("DROP COLUMN [NAME]"), "drop column");
        }
Exemplo n.º 9
0
        /// <summary>
        /// KL:
        /// Similar to WriteColumn. Will send the appropriate dataType and propertyName to
        /// _cb.AppendAutomaticProperty to be written.
        ///
        /// This method was needed to support composite foreign keys.
        /// </summary>
        /// <param name="foreignKey"></param>
        private void WriteForeignKey(DatabaseConstraint foreignKey)
        {
            // get the reference table
            var refTable = foreignKey.ReferencedTable(_table.DatabaseSchema);

            //we inherit from it instead (problem with self-joins)
            if (Equals(refTable, _inheritanceTable))
            {
                return;
            }

            if (refTable == null)
            {
                //we can't find the foreign key table, so just write the columns
                WriteForeignKeyColumns(foreignKey, "");
                return;
            }

            var propertyName = _codeWriterSettings.Namer.ForeignKeyName(_table, foreignKey);
            var dataType     = refTable.NetName;

            _cb.AppendAutomaticProperty(dataType, propertyName);

            if (IsEntityFramework() && _codeWriterSettings.UseForeignKeyIdProperties)
            {
                WriteForeignKeyColumns(foreignKey, propertyName);
            }
        }
Exemplo n.º 10
0
        public void TestCompositeKeys()
        {
            //arrange
            var schema = new DatabaseSchema(null, null);

            schema.AddTable("Store")
            .AddColumn <int>("Store_Id").AddPrimaryKey("Store_PK")
            .AddColumn <string>("Name").AddLength(10)

            .AddTable("StoreSale")
            .AddColumn <int>("Store_Id").AddForeignKey("Store_FK", "Store")
            .AddColumn <int>("StoreSale_Id")

            .AddTable("StoreSaleDetail")
            .AddColumn <int>("Store_Id").AddForeignKey("Store_FK", "Store")
            .AddColumn <int>("StoreSale_Id")
            .AddColumn <int>("StoreSaleDetail_Id")
            ;
            var store           = schema.FindTableByName("Store");
            var storeSale       = schema.FindTableByName("StoreSale");
            var storeSaleDetail = schema.FindTableByName("StoreSaleDetail");
            var pk1             = new DatabaseConstraint {
                ConstraintType = ConstraintType.PrimaryKey
            };

            pk1.Columns.Add("Store_Id");
            pk1.Columns.Add("StoreSale_Id");
            storeSale.AddConstraint(pk1);

            var pk2 = new DatabaseConstraint {
                ConstraintType = ConstraintType.PrimaryKey
            };

            pk2.Columns.Add("Store_Id");
            pk2.Columns.Add("StoreSale_Id");
            pk2.Columns.Add("StoreSaleDetail_Id");
            storeSaleDetail.AddConstraint(pk2);

            var fk = new DatabaseConstraint {
                ConstraintType = ConstraintType.ForeignKey, RefersToTable = "StoreSale"
            };

            fk.Columns.Add("Store_Id");
            fk.Columns.Add("StoreSale_Id");
            storeSaleDetail.AddConstraint(fk);

            //act
            DatabaseSchemaFixer.UpdateReferences(schema);

            //assert
            Assert.AreEqual(2, store.ForeignKeyChildren.Count, "Store is target of foreign keys from StoreSale and StoreSaleDetail");
            Assert.AreEqual(1, storeSale.ForeignKeyChildren.Count, "StoreSale is target of foreign key from StoreSaleDetail");

            var storeId = storeSaleDetail.FindColumn("Store_Id");

            Assert.AreEqual(2, storeId.ForeignKeyTableNames.Count, "StoreSaleDetail.StoreId is fk to both Store and StoreSale");
            var storeSaleId = storeSaleDetail.FindColumn("StoreSale_Id");

            Assert.AreEqual(1, storeSaleId.ForeignKeyTableNames.Count, "StoreSaleDetail.StoreSale_Id is fk to StoreSale");
        }
        public void TestAddPrimaryKeyWithGuid()
        {
            //arrange
            var migration = new DdlGeneratorFactory(SqlType.SqlServer).MigrationGenerator();

            var schema = new DatabaseSchema(null, SqlType.SqlServer);
            var table  = schema.AddTable("Test")
                         .AddColumn <Guid>("Id")
                         .AddColumn <string>("Name")
                         .Table;
            var pk = new DatabaseConstraint
            {
                Name           = "Test_PK",
                ConstraintType = ConstraintType.PrimaryKey
            };

            pk.Columns.Add("Id");
            table.Indexes.Add(new DatabaseIndex
            {
                IndexType = "PRIMARY NONCLUSTERED",
                Columns   = { new DatabaseColumn {
                                  Name = "Id"
                              } }
            });

            //act
            var sql = migration.AddConstraint(table, pk);

            //assert
            Assert.IsTrue(sql.IndexOf("ADD CONSTRAINT [Test_PK] PRIMARY KEY NONCLUSTERED([Id])", StringComparison.OrdinalIgnoreCase) != -1, "adding a primary key");
        }
		public void Ctor_StringStringString_Success()
		{
			DatabaseConstraint c = new DatabaseConstraint(Constants.EntityName, Constants.KeyName, Constants.DisplayName);
			Assert.AreEqual(Constraint.DatabaseConstraintName, c.Name);
			Assert.AreEqual(Constants.DisplayName, c.DisplayProperty);
			Assert.AreEqual(Constants.EntityName, c.Entity);
			Assert.AreEqual(Constants.KeyName, c.KeyProperty);
		}
		public void Ctor_NullNullNull_Success()
		{
			DatabaseConstraint c = new DatabaseConstraint(null, null, null);
			Assert.AreEqual(Constraint.DatabaseConstraintName, c.Name);
			Assert.AreEqual(string.Empty, c.DisplayProperty);
			Assert.AreEqual(string.Empty, c.Entity);
			Assert.AreEqual(string.Empty, c.KeyProperty);
		}
Exemplo n.º 14
0
        private string ForeignKeyTableName(DatabaseConstraint foreignKey)
        {
            var foreignKeyTable = foreignKey.ReferencedTable(_table.DatabaseSchema);

            return((foreignKeyTable != null)
                                          ? TableName(foreignKeyTable)
                                          : EscapeName(foreignKey.RefersToTable));
        }
Exemplo n.º 15
0
 private static bool ExcludeCheckConstraint(DatabaseConstraint check)
 {
     //don't allow SYSDATE in check constraints
     if (check.Expression.IndexOf("getDate()", StringComparison.OrdinalIgnoreCase) != -1)
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 16
0
        public MsSqlTable(string tableName, IEnumerable <SqlColumnSchema> columns, DatabaseConstraint tableSchemaPrimaryKey, List <DatabaseConstraint> tableSchemaUniqueKeys)
        {
            Name     = tableName;
            _columns = columns.ToDictionary(column => column.Name);

            var primaryKey = tableSchemaPrimaryKey?.Columns;
            var uniqueKeys = tableSchemaUniqueKeys.Select(x => x.Columns).ToList();

            Keys = new[] { primaryKey }.Union(uniqueKeys).Where(x => x != null).ToArray();
        }
Exemplo n.º 17
0
        public static DatabaseTable CreateTestTable(string tableName)
        {
            //we only need a schema because MySQL foreign key references do not allow just the foreign key table name- they need the columns too
            var schema = new DatabaseSchema(null, null);

            var testTable = new DatabaseTable {
                Name = tableName, Description = "This is a test table"
            };

            schema.Tables.Add(testTable);
            testTable.DatabaseSchema = schema; //the migration will discover this and know how to link the self referencing table

            var intDataType = new DataType("INT", "System.Int32");
            var idColumn    = new DatabaseColumn
            {
                Name        = "Id",
                DbDataType  = "int",
                DataType    = intDataType,
                Nullable    = false,
                Description = "Primary key",
            };

            testTable.Columns.Add(idColumn);

            var parentColumn = new DatabaseColumn
            {
                Name        = "Parent", //for a self-referencing foreign key
                DbDataType  = "int",
                DataType    = intDataType,
                Nullable    = true,
                Description = "Self referencing foreign key",
            };

            testTable.Columns.Add(parentColumn);

            var nameColumn = new DatabaseColumn
            {
                Name        = "NAME",
                DbDataType  = "VARCHAR",
                Length      = 10,
                DataType    = new DataType("VARCHAR", "string"),
                Description = "Simple varchar column",
            };

            testTable.Columns.Add(nameColumn);

            var primaryKey = new DatabaseConstraint {
                ConstraintType = ConstraintType.PrimaryKey, Name = "PK_" + tableName
            };

            primaryKey.Columns.Add("Id");
            testTable.PrimaryKey = primaryKey;

            return(testTable);
        }
Exemplo n.º 18
0
        public static DatabaseConstraint CreateUniqueConstraint(DatabaseColumn column)
        {
            var constraint = new DatabaseConstraint
            {
                Name           = "UK_COUNTRY",
                ConstraintType = ConstraintType.UniqueKey,
            };

            constraint.Columns.Add(column.Name);
            return(constraint);
        }
Exemplo n.º 19
0
        protected override string WriteDefaultConstraint(DatabaseConstraint constraint)
        {
            var column = EscapeName(constraint.Columns.FirstOrDefault());

            return(string.Format(CultureInfo.InvariantCulture,
                                 @"ALTER TABLE {0} ADD CONSTRAINT {1} DEFAULT {2} FOR {3}",
                                 TableName(Table),
                                 EscapeName(constraint.Name),
                                 constraint.Expression,
                                 column) + SqlFormatProvider().LineEnding());
        }
Exemplo n.º 20
0
        private static DatabaseConstraint GetUniqueConstraint()
        {
            var constraint = new DatabaseConstraint
            {
                Name           = "UK_NAME",
                ConstraintType = ConstraintType.UniqueKey,
            };

            constraint.Columns.Add("Name");
            return(constraint);
        }
        protected virtual string ConstraintName(DatabaseConstraint constraint)
        {
            var name = constraint.Name;

            if (string.IsNullOrEmpty(name))
            {
                return("CON");
            }
            name = LimitNameToMaximumLength(name);
            return(name);
        }
Exemplo n.º 22
0
        public static DatabaseConstraint CreateForeignKey(DatabaseTable databaseTable)
        {
            var constraint = new DatabaseConstraint
            {
                Name           = "FK_" + databaseTable.Name,
                ConstraintType = ConstraintType.ForeignKey,
                RefersToTable  = databaseTable.Name
            };

            constraint.Columns.Add("Parent");
            return(constraint);
        }
Exemplo n.º 23
0
        private string WriteUniqueKey(DatabaseConstraint uniqueKey)
        {
            var columnList = GetColumnList(uniqueKey.Columns);

            var name = ConstraintName(uniqueKey.Name);

            return(string.Format(CultureInfo.InvariantCulture,
                                 AddUniqueConstraintFormat,
                                 TableName(_table),
                                 EscapeName(name),
                                 columnList) + SqlFormatProvider().LineEnding());
        }
Exemplo n.º 24
0
 public void BuildDropConstraint(DatabaseTable databaseTable, DatabaseConstraint constraint)
 {
     try
     {
         var txt = _migrationGenerator.DropConstraint(databaseTable, constraint);
         Clipboard.SetText(txt, TextDataFormat.UnicodeText);
     }
     catch (Exception exception)
     {
         Debug.WriteLine(exception.Message);
     }
 }
Exemplo n.º 25
0
 private static bool ConstraintColumnsEqual(DatabaseConstraint first, DatabaseConstraint second)
 {
     if (first.Columns == null && second.Columns == null)
     {
         return(true);                                                 //same, both null
     }
     if (first.Columns == null || second.Columns == null)
     {
         return(false);                                                 //one is null, they are different
     }
     return(first.Columns.SequenceEqual(second.Columns));
 }
Exemplo n.º 26
0
        protected virtual string ConstraintName(DatabaseConstraint constraint)
        {
            var name = constraint.Name;

            if (string.IsNullOrEmpty(name))
            {
                return(" PK_" + constraint.TableName);
            }
            //if (string.IsNullOrEmpty(name)) return constraint.TableName+"_CON";
            name = LimitNameToMaximumLength(name);
            return(name);
        }
Exemplo n.º 27
0
        private void WriteForeignKey(DatabaseTable table, DatabaseConstraint foreignKey, StringBuilder sb)
        {
            sb.AppendLine("ALTER TABLE [" + table.Name + "]");
            var cols = string.Join(", ", foreignKey.Columns.ToArray());
            var referencedTableName = foreignKey.RefersToTable;
            //find the referenced table's primary key
            var refTable      = _schema.Tables.Find(t => t.Name == referencedTableName);
            var refPrimaryKey = refTable.PrimaryKey;
            var refcols       = string.Join(", ", refPrimaryKey.Columns.ToArray());

            sb.AppendLine(" ADD CONSTRAINT [" + foreignKey.Name +
                          "] FOREIGN KEY (" + cols + ") REFERENCES " + referencedTableName + "(" + refcols + ")");
        }
Exemplo n.º 28
0
        public string BuildAddConstraint(DatabaseTable databaseTable, DatabaseConstraint constraint)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                sb.Append(m_migrationGenerator.AddConstraint(databaseTable, constraint));
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
            }
            return(sb.ToString());
        }
Exemplo n.º 29
0
        public void WriteWith(DatabaseConstraint foreignKey)
        {
            // TODO: refactor this method to be consistent with approach taken for other overload
            var refTable = foreignKey.ReferencedTable(table.DatabaseSchema);
            var dataType = refTable.NetName;

            if (foreignKey.Columns.Count != foreignKey.ReferencedColumns(table.DatabaseSchema).Count())
            {
                throw new InvalidOperationException("Number of foreign key columns does not match number of columns referenced!");
            }

            classBuilder.BeginNest($"public virtual {CodeWriterUtils.GetWithMethodSignature(table, foreignKey, codeWriterSettings)}");

            var methodCallParameters = new List <string>();

            var propertyName = codeWriterSettings.Namer.ForeignKeyName(table, foreignKey);

            foreach (var fkc in foreignKey.Columns)
            {
                var tc        = table.Columns.Single(_tc => _tc.Name == fkc);
                var parameter = $"{CodeWriterUtils.GetPropertyNameForDatabaseColumn(tc)}";
                if (tc.Nullable && CodeWriterUtils.FindDataType(tc).EndsWith("?")) // KE: need the check for the "?" so that we correctly handle reference types like string
                {
                    using (classBuilder.BeginNest($"if (!{parameter}.HasValue)"))
                    {
                        classBuilder.AppendLine($"{propertyName} = null;");
                        classBuilder.AppendLine("return this;");
                    }

                    classBuilder.AppendLine("");
                    parameter += ".Value";
                }

                methodCallParameters.Add(parameter);
            }

            var s = string.Join(", ", methodCallParameters);
            var referencedColumnNames = foreignKey.ReferencedColumns(table.DatabaseSchema).ToList();

            referencedColumnNames.Sort();
            var referencedColumns             = referencedColumnNames.Select(c => foreignKey.ReferencedTable(table.DatabaseSchema).FindColumn(c));
            var methodParameters              = CodeWriterUtils.GetMethodParametersForColumns(referencedColumns, codeWriterSettings);
            var methodName                    = CodeWriterUtils.GetMethodName(methodParameters, codeWriterSettings, true, CodeWriterUtils.BaseMethodNameGet);
            var fieldNameForFkTableRepository = NameFixer.ToCamelCase(CodeWriterUtils.GetRepositoryImplementationName(refTable));

            classBuilder.AppendLine($"{propertyName} = _{fieldNameForFkTableRepository}.{methodName}({s});");
            classBuilder.AppendLine("return this;");
            classBuilder.EndNest();
            classBuilder.AppendLine("");
        }
        private void WriteForeignKey(DatabaseConstraint foreignKey)
        {
            var propertyName = _codeWriterSettings.Namer.ForeignKeyName(_table, foreignKey);

            if (string.IsNullOrEmpty(propertyName))
            {
                return;
            }

            var columnName = foreignKey.Columns.FirstOrDefault();
            var columns    = foreignKey.Columns.Select(colName => _table.FindColumn(colName)).ToList();
            var optional   = columns.All(col => col.Nullable);
            //foreign key is a primary key = shared with another table
            var isPrimaryKey = columns.All(col => col.IsPrimaryKey);

            var sb = new StringBuilder();

            sb.AppendFormat(CultureInfo.InvariantCulture, "Has{0}(x => x.{1})",
                            optional ? "Optional" : "Required",
                            propertyName);

            //1:1 shared primary key
            if (isPrimaryKey)
            {
                sb.Append(";");
                _cb.AppendLine(sb.ToString());
                return;
            }

            //then map the inverse with our foreign key children convention
            var fkPropertyName = _codeWriterSettings.Namer.ForeignKeyCollectionName(foreignKey.RefersToTable, _table, foreignKey);

            sb.AppendFormat(CultureInfo.InvariantCulture, ".WithMany(c => c.{0})", fkPropertyName);
            if (_codeWriterSettings.UseForeignKeyIdProperties)
            {
                //for pk/fk we have a mirror property
                //TODO: don't use Id here
                var fkIdName = propertyName + "Id";
                _cb.AppendFormat("Property(x => x.{0}).HasColumnName(\"{1}\");", fkIdName, columnName);
                sb.AppendFormat(CultureInfo.InvariantCulture, ".HasForeignKey(c => c.{0})", fkIdName);
            }
            else
            {
                //otherwise specify the underlying column name
                sb.AppendFormat(CultureInfo.InvariantCulture, ".Map(m => m.MapKey(\"{0}\"))", columnName);
            }
            //could look up cascade rule here
            sb.Append(";");
            _cb.AppendLine(sb.ToString());
        }
Exemplo n.º 31
0
 public virtual string DropConstraint(DatabaseTable databaseTable, DatabaseConstraint constraint)
 {
     if (constraint.ConstraintType == ConstraintType.UniqueKey)
     {
         return(string.Format(CultureInfo.InvariantCulture,
                              DropUniqueFormat,
                              TableName(databaseTable),
                              Escape(constraint.Name)) + LineEnding());
     }
     return(string.Format(CultureInfo.InvariantCulture,
                          DropForeignKeyFormat,
                          TableName(databaseTable),
                          Escape(constraint.Name)) + LineEnding());
 }
Exemplo n.º 32
0
        private A GetInFkLink(string sourceTable, DatabaseConstraint fk, IDictionary <string, object> o)
        {
            var filters = fk.Columns
                          .Select(c => KeyValuePair.Create(c, (object)_dbInspector.GetId(sourceTable, o)))
                          .ToList();
            var name = $"Search '{fk.TableName}' where {filters.Select(kvp => kvp.Key + "=" + kvp.Value).JoinToString()}";
            var rel  = fk.TableName;
            var url  = _linkManager.LinkToQuery(fk.TableName, filters);

            return(new A(url, name, rel)
            {
                Itemscope = true,
            });
        }
		public void SetParameters_TooManyFewParams_Error()
		{
			CustomAssert.ThrowsException<ConstraintConfigurationException>(() =>
			{
				DatabaseConstraint c = new DatabaseConstraint();
				c.SetParametersInternal(new string[0], ParameterDataType.Int32);
			});
			CustomAssert.ThrowsException<ConstraintConfigurationException>(() =>
			{
				DatabaseConstraint c = new DatabaseConstraint();
				c.SetParametersInternal(new string[] { "1", "2", "3", "4" }, ParameterDataType.Int32);
			});
		}
		public void SetParameters_Null_Success()
		{
			DatabaseConstraint c = new DatabaseConstraint();
			c.SetParametersInternal(new string[] { null, null, null }, ParameterDataType.Int32);
			Assert.AreEqual(string.Empty, c.DisplayProperty);
			Assert.AreEqual(string.Empty, c.Entity);
			Assert.AreEqual(string.Empty, c.KeyProperty);
		}
		public void SetParameters_Success()
		{
			DatabaseConstraint c = new DatabaseConstraint();
			c.SetParametersInternal(new string[] { Constants.EntityName, Constants.KeyName, Constants.DisplayName }, ParameterDataType.Int32);
			Assert.AreEqual(Constants.DisplayName, c.DisplayProperty);
			Assert.AreEqual(Constants.EntityName, c.Entity);
			Assert.AreEqual(Constants.KeyName, c.KeyProperty);
		}
		public void ToString_Success()
		{
			DatabaseConstraint c = new DatabaseConstraint(Constants.EntityName, Constants.KeyName, Constants.DisplayName);
			Assert.AreEqual(string.Format("[Database({0},{1},{2})]", Constants.EntityName, Constants.KeyName, Constants.DisplayName), c.ToString());
		}
		public void Ctor_SerializationInfo_Success()
		{
			DatabaseConstraint c = new DatabaseConstraint(Constants.EntityName, Constants.KeyName, Constants.DisplayName);
			System.IO.MemoryStream Buffer = SerializationHelper.Serialize(c);
			DatabaseConstraint c2 = SerializationHelper.Deserialize<DatabaseConstraint>(Buffer);

			Assert.AreEqual(Constraint.DatabaseConstraintName, c2.Name);
			Assert.AreEqual(Constants.DisplayName, c2.DisplayProperty);
			Assert.AreEqual(Constants.EntityName, c2.Entity);
			Assert.AreEqual(Constants.KeyName, c2.KeyProperty);
		}
		private Constraint FindConstraint(string name, ParameterDataType type)
		{
			Constraint ReturnValue = null;
			bool IsConstraintNameUnknown = false;

			switch (name)
			{
				case Constraint.AllowedSchemeConstraintName:
					ReturnValue = CreateAllowedSchemeConstraint(type);
					break;
				case Constraint.CharacterSetConstraintName:
					ReturnValue = CreateCharacterSetConstraint(type);
					break;
				case Constraint.DatabaseConstraintName:
					ReturnValue = new DatabaseConstraint();
					break;
				case Constraint.DecimalPlacesConstraintName:
					ReturnValue = CreateDecimalPlacesConstraint(type);
					break;
				case Constraint.EncryptedConstraintName:
					ReturnValue = new EncryptedConstraint();
					break;
				case Constraint.EndpointConstraintName:
					ReturnValue = CreateEndpointConstraint(type);
					break;
				case Constraint.EnumValuesConstraintName:
					ReturnValue = CreateEnumValuesConstraint(type);
					break;
				case Constraint.FileNameConstraintName:
					ReturnValue = CreateFileNameConstraint(type);
					break;
				case Constraint.HostNameConstraintName:
					ReturnValue = CreateHostnameConstraint(type);
					break;
				case Constraint.LengthConstraintName:
					ReturnValue = CreateLengthConstraint(type);
					break;
				case Constraint.LowercaseConstraintName:
					ReturnValue = CreateLowerCaseConstraint(type);
					break;
				case Constraint.MaximumLengthConstraintName:
					ReturnValue = CreateMaximumLengthConstraint(type);
					break;
				case Constraint.MaximumValueConstraintName:
					ReturnValue = CreateMaximumValueConstraint(type);
					break;
				case Constraint.MinimumLengthConstraintName:
					ReturnValue = CreateMinimumLengthConstraint(type);
					break;
				case Constraint.MinimumValueConstraintName:
					ReturnValue = CreateMinimumValueConstraint(type);
					break;
				case Constraint.NullConstraintName:
					ReturnValue = new NullConstraint();
					break;
				case Constraint.PasswordConstraintName:
					ReturnValue = CreatePasswordConstraint(type);
					break;
				case Constraint.PathConstraintName:
					ReturnValue = CreatePathConstraint(type);
					break;
				case Constraint.RegexConstraintName:
					ReturnValue = CreateRegexConstraint(type);
					break;
				case Constraint.StepConstraintName:
					ReturnValue = CreateStepConstraint(type);
					break;
				case Constraint.TypeConstraintName:
					ReturnValue = CreateTypeConstraint(type);
					break;
				case Constraint.UppercaseConstraintName:
					ReturnValue = CreateUpperCaseConstraint(type);
					break;
				default:
					// Constraint name is unknown
					IsConstraintNameUnknown = true;
					break;
			}

			if (ReturnValue == null)
			{
				ReturnValue = HandleUnknownConstraint(name, type, IsConstraintNameUnknown);
			}

			return ReturnValue;
		}