-
-
Notifications
You must be signed in to change notification settings - Fork 29
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
base: master
Are you sure you want to change the base?
Custom schema #1 #38
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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(); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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) | ||
{ | ||
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) | ||
|
@@ -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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||
|
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); | ||
} | ||
} | ||
} |
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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
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.