Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom schema #1 #38

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion EfEnumToLookup/EfEnumToLookup.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
<Compile Include="LookupGenerator\EnumGeneratorException.cs" />
<Compile Include="LookupGenerator\EnumParser.cs" />
<Compile Include="LookupGenerator\EnumToLookup.cs" />
<Compile Include="LookupGenerator\Extensions\ContextExtensions.cs" />
<Compile Include="LookupGenerator\IDbHandler.cs" />
<Compile Include="LookupGenerator\IEnumToLookup.cs" />
<Compile Include="LookupGenerator\EnumReference.cs" />
Expand All @@ -74,7 +75,7 @@
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
Expand Down
3 changes: 1 addition & 2 deletions EfEnumToLookup/LookupGenerator/EnumToLookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// Makes up for a missing feature in Entity Framework 6.1
Expand Down Expand Up @@ -141,6 +139,7 @@ from enm in enums
{
Lookups = lookups,
References = enumReferences,
Schema = context.GetDefaultSchema()
};
return model;
}
Expand Down
49 changes: 49 additions & 0 deletions EfEnumToLookup/LookupGenerator/Extensions/ContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
namespace EfEnumToLookup.LookupGenerator
{
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text.RegularExpressions;

public static class ContextExtensions
{
public static string GetTableName<T>(this DbContext context) where T : class
{
var objectContext = ((IObjectContextAdapter)context).ObjectContext;

return objectContext.GetTableName<T>();
}

private static string GetTableName<T>(this ObjectContext context) where T : class
{
string sql = context.CreateObjectSet<T>().ToTraceString();
Regex regex = new Regex("FROM (?<table>.*) AS");
Match match = regex.Match(sql);

string table = match.Groups["table"].Value;

return table;
}

public static string GetDefaultSchema(this DbContext context)
{
var table = (((IObjectContextAdapter)context).ObjectContext).MetadataWorkspace.GetItemCollection(DataSpace.SSpace)
.GetItems<EntityContainer>()
.Single()
.BaseEntitySets
.OfType<EntitySet>()
.FirstOrDefault(
s => !s.MetadataProperties.Contains("Type")
|| s.MetadataProperties["Type"].ToString() == "Tables");

if (table == null)
{
return "dbo";
}

return table.MetadataProperties["Schema"].Value.ToString();
}
}
}
7 changes: 4 additions & 3 deletions EfEnumToLookup/LookupGenerator/LookupDbModel.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections.Generic;

namespace EfEnumToLookup.LookupGenerator
namespace EfEnumToLookup.LookupGenerator
{
using System.Collections.Generic;

/// <summary>
/// Not the best name ever. Everything you need to know
/// about a database to be able to generate lookup tables
Expand All @@ -11,5 +11,6 @@ internal class LookupDbModel
{
public IList<LookupData> Lookups { get; set; }
public IList<EnumReference> References { get; set; }
public string Schema { get; set; }
}
}
65 changes: 32 additions & 33 deletions EfEnumToLookup/LookupGenerator/SqlServerHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,59 +45,59 @@ private string BuildSql(LookupDbModel model)
sql.AppendLine("set nocount on;");
sql.AppendLine("set xact_abort on; -- rollback on error");
sql.AppendLine("begin tran;");
sql.AppendLine(CreateTables(model.Lookups));
sql.AppendLine(PopulateLookups(model.Lookups));
sql.AppendLine(AddForeignKeys(model.References));
sql.AppendLine(CreateTables(model));
sql.AppendLine(PopulateLookups(model));
sql.AppendLine(AddForeignKeys(model));
sql.AppendLine("commit;");

return sql.ToString();
}

private string CreateTables(IEnumerable<LookupData> enums)
private string CreateTables(LookupDbModel model)
{
var sql = new StringBuilder();
foreach (var lookup in enums)
foreach (var lookup in model.Lookups)
{
sql.AppendFormat(
@"IF OBJECT_ID('{0}', 'U') IS NULL
begin
CREATE TABLE [{0}] (Id {2} CONSTRAINT PK_{0} PRIMARY KEY, Name nvarchar({1}));
exec sys.sp_addextendedproperty @name=N'MS_Description', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'{0}', @value=N'Automatically generated. Contents will be overwritten on app startup. Table & contents generated by https://github.com/timabell/ef-enum-to-lookup';
end
",
TableName(lookup.Name), NameFieldLength, NumericSqlType(lookup.NumericType));
@"IF OBJECT_ID('{3}.{0}', 'U') IS NULL
begin
CREATE TABLE [{3}].[{0}] (Id {2} CONSTRAINT PK_{0} PRIMARY KEY, Name nvarchar({1}));
exec sys.sp_addextendedproperty @name=N'MS_Description', @level0type=N'SCHEMA', @level0name=N'{3}', @level1type=N'TABLE',
@level1name=N'{0}', @value=N'Automatically generated. Contents will be overwritten on app startup. Table & contents generated by https://github.com/timabell/ef-enum-to-lookup';
end{4}",
TableName(lookup.Name), NameFieldLength, NumericSqlType(lookup.NumericType), model.Schema, Environment.NewLine);
}

return sql.ToString();
}

private string AddForeignKeys(IEnumerable<EnumReference> refs)
private string AddForeignKeys(LookupDbModel model)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm uneasy about expanding the params to be the whole model, makes it harder to see what this method actually depends on. I need to give it some more thought.

{
var sql = new StringBuilder();
foreach (var enumReference in refs)
foreach (var enumReference in model.References)
{
var fkName = string.Format("FK_{0}_{1}", enumReference.ReferencingTable, enumReference.ReferencingField);

sql.AppendFormat(
" IF OBJECT_ID('{0}', 'F') IS NULL ALTER TABLE [{1}] ADD CONSTRAINT {0} FOREIGN KEY ([{2}]) REFERENCES [{3}] (Id);\r\n",
fkName, enumReference.ReferencingTable, enumReference.ReferencingField, TableName(enumReference.EnumType.Name)
);
" IF OBJECT_ID('{4}.{0}', 'F') IS NULL ALTER TABLE [{4}].[{1}] ADD CONSTRAINT {0} FOREIGN KEY ([{2}]) REFERENCES [{4}].[{3}] (Id);{5}",
fkName, enumReference.ReferencingTable, enumReference.ReferencingField, TableName(enumReference.EnumType.Name), model.Schema, Environment.NewLine);
}
return sql.ToString();
}

private string PopulateLookups(IEnumerable<LookupData> lookupData)
private string PopulateLookups(LookupDbModel model)
{
var sql = new StringBuilder();
sql.AppendLine(string.Format("CREATE TABLE #lookups (Id int, Name nvarchar({0}) COLLATE database_default);", NameFieldLength));
foreach (var lookup in lookupData)
foreach (var lookup in model.Lookups)
{
sql.AppendLine(PopulateLookup(lookup));
sql.AppendLine(PopulateLookup(lookup, model.Schema));
}
sql.AppendLine("DROP TABLE #lookups;");
return sql.ToString();
}

private string PopulateLookup(LookupData lookup)
private string PopulateLookup(LookupData lookup, string schema)
{
var sql = new StringBuilder();
foreach (var value in lookup.Values)
Expand All @@ -106,17 +106,16 @@ private string PopulateLookup(LookupData lookup)
}

sql.AppendLine(string.Format(@"
MERGE INTO [{0}] dst
USING #lookups src ON src.Id = dst.Id
WHEN MATCHED AND src.Name <> dst.Name collate Latin1_General_BIN2 THEN
UPDATE SET Name = src.Name
WHEN NOT MATCHED THEN
INSERT (Id, Name)
VALUES (src.Id, src.Name)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
;"
, TableName(lookup.Name)));
MERGE INTO [{1}].[{0}] dst
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was intentionally not indented to avoid unnecessary whitespace in the generated output

USING #lookups src ON src.Id = dst.Id
WHEN MATCHED AND src.Name <> dst.Name collate Latin1_General_BIN2 THEN
UPDATE SET Name = src.Name
WHEN NOT MATCHED THEN
INSERT (Id, Name)
VALUES (src.Id, src.Name)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;"
, TableName(lookup.Name), schema));

sql.AppendLine("TRUNCATE TABLE #lookups;");
return sql.ToString();
Expand Down
30 changes: 30 additions & 0 deletions EfEnumToLookupTests/Db/MagicCustomSchemaContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace EfEnumToLookupTests.Db
{
using System.Data.Entity;
using EfEnumToLookupTests.Model;

public class MagicCustomSchemaContext : DbContext
{
public DbSet<Rabbit> PeskyWabbits { get; set; }

// this one goes deeper
public DbSet<Warren> Warrens { get; set; }

public DbSet<Chicken> LittleChickens { get; set; }

public DbSet<Fox> CunningFoxes { get; set; }

// Table-per-Hierarchy (TPH)
public DbSet<Furniture> Furniture { get; set; }

// Table-per-Type (TPT)
public DbSet<Vehicle> Vehicles { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("myschema");
modelBuilder.Entity<Fox>().Map(f => f.ToTable("Foxies"));
base.OnModelCreating(modelBuilder);
}
}
}
4 changes: 3 additions & 1 deletion EfEnumToLookupTests/EfEnumToLookupTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Db\MagicCustomSchemaContext.cs" />
<Compile Include="Model\Category.cs" />
<Compile Include="Model\Fur.cs" />
<Compile Include="Model\Pedigree.cs" />
Expand Down Expand Up @@ -85,6 +86,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Db\TestInitializer.cs" />
<Compile Include="Tests\EnumParserTests.cs" />
<Compile Include="Tests\ModelCustomSchemaParsingTests.cs" />
<Compile Include="Tests\ModelParsingTests.cs" />
<Compile Include="Tests\TestConfiguration.cs" />
<Compile Include="Tests\TestStuff.cs" />
Expand All @@ -101,7 +103,7 @@
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
Expand Down
61 changes: 61 additions & 0 deletions EfEnumToLookupTests/Tests/ModelCustomSchemaParsingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
namespace EfEnumToLookupTests.Tests
{
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Db;
using EfEnumToLookup.LookupGenerator;
using Model;
using NUnit.Framework;

[TestFixture]
public class ModelCustomSchemaParsingTests
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm uneasy about this test being a copy-paste of the original, smells of DRY

{
private readonly EnumToLookup _enumToLookup = new EnumToLookup();

[SetUp]
public void SetUp()
{
Database.SetInitializer(new TestInitializer(new EnumToLookup()));
}

[Test]
public void FindsReferencesCustomSchema()
{
IList<EnumReference> references;
using (var context = new MagicCustomSchemaContext())
{
references = _enumToLookup.FindEnumReferences(context);
}

var legs = references.SingleOrDefault(r => r.ReferencingField == "SpeedyLegs");
Assert.IsNotNull(legs, "SpeedyLegs ref not found");
var ears = references.SingleOrDefault(r => r.ReferencingField == "TehEars");
Assert.IsNotNull(ears, "TehEars ref not found");
var echos = references.SingleOrDefault(r => r.ReferencingField == "EchoType");
Assert.IsNotNull(echos, "EchoType ref not found");
var eons = references.Count(r => r.EnumType == typeof(Eon));
Assert.AreEqual(2, eons, "Wrong number of Eon refs found");
Assert.IsTrue(references.All(r => r.EnumType.IsEnum), "Non-enum type found");
Assert.AreEqual(13, references.Count);
}

[Test]
public void FindsEnumOnTypeCustomSchema()
{
var enums = _enumToLookup.FindEnums(typeof (Rabbit));
var prop = enums.SingleOrDefault(p => p.Name == "TehEars");
Assert.IsNotNull(prop, "Enum property not found");
Assert.AreEqual(typeof (Ears), prop.PropertyType);
}

[Test]
public void FindsNullableEnumOnTypeCustomSchema()
{
var enums = _enumToLookup.FindEnums(typeof (Rabbit));
var prop = enums.SingleOrDefault(p => p.Name == "SpeedyLegs");
Assert.IsNotNull(prop, "Enum property not found");
Assert.AreEqual(typeof (Legs?), prop.PropertyType);
}
}
}
Loading