|
| 1 | +using System; |
| 2 | +using System.Data.Common; |
| 3 | +using System.Data.Entity; |
| 4 | +using System.Diagnostics; |
| 5 | +using System.IO; |
| 6 | +using System.Linq; |
| 7 | +using SQLite.CodeFirst.Utility; |
| 8 | + |
| 9 | +namespace SQLite.CodeFirst |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// An implementation of <see cref="IDatabaseInitializer{TContext}"/> that will always recreate and optionally re-seed the |
| 13 | + /// database the first time that a context is used in the app domain or if the model has changed. |
| 14 | + /// To seed the database, create a derived class and override the Seed method. |
| 15 | + /// <remarks> |
| 16 | + /// To detect model changes a new table (implementation of <see cref="IHistory"/>) is added to the database. |
| 17 | + /// There is one record in this table which holds the hash of the SQL-statement which was generated from the model |
| 18 | + /// executed to create the database. When initializing the database the initializer checks if the hash of the SQL-statement for the |
| 19 | + /// model is still the same as the hash in the database. If you use this initializer on a existing database, this initializer |
| 20 | + /// will interpret this as model change because of the new <see cref="IHistory"/> table. |
| 21 | + /// Notice that a database can be used by more than one context. Therefore the name of the context is saved as a part of the history record. |
| 22 | + /// </remarks> |
| 23 | + /// </summary> |
| 24 | + /// <typeparam name="TContext">The type of the context.</typeparam> |
| 25 | + public class SqliteDropCreateDatabaseWhenModelChanges<TContext> : SqliteInitializerBase<TContext> |
| 26 | + where TContext : DbContext |
| 27 | + { |
| 28 | + private readonly Type historyEntityType; |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Initializes a new instance of the <see cref="SqliteDropCreateDatabaseWhenModelChanges{TContext}"/> class. |
| 32 | + /// </summary> |
| 33 | + /// <param name="modelBuilder">The model builder.</param> |
| 34 | + public SqliteDropCreateDatabaseWhenModelChanges(DbModelBuilder modelBuilder) |
| 35 | + : base(modelBuilder) |
| 36 | + { |
| 37 | + historyEntityType = typeof(History); |
| 38 | + ConfigureHistoryEntity(); |
| 39 | + } |
| 40 | + |
| 41 | + /// <summary> |
| 42 | + /// Initializes a new instance of the <see cref="SqliteDropCreateDatabaseWhenModelChanges{TContext}"/> class. |
| 43 | + /// </summary> |
| 44 | + /// <param name="modelBuilder">The model builder.</param> |
| 45 | + /// <param name="historyEntityType">Type of the history entity (must implement <see cref="IHistory"/> and provide an parameterless constructor).</param> |
| 46 | + public SqliteDropCreateDatabaseWhenModelChanges(DbModelBuilder modelBuilder, Type historyEntityType) |
| 47 | + : base(modelBuilder) |
| 48 | + { |
| 49 | + this.historyEntityType = historyEntityType; |
| 50 | + ConfigureHistoryEntity(); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + protected void ConfigureHistoryEntity() |
| 55 | + { |
| 56 | + HistoryEntityTypeValidator.EnsureValidType(historyEntityType); |
| 57 | + ModelBuilder.RegisterEntityType(historyEntityType); |
| 58 | + } |
| 59 | + |
| 60 | + /// <summary> |
| 61 | + /// Initialize the database for the given context. |
| 62 | + /// Generates the SQLite-DDL from the model and executs it against the database. |
| 63 | + /// After that the <see cref="Seed" /> method is executed. |
| 64 | + /// All actions are be executed in transactions. |
| 65 | + /// </summary> |
| 66 | + /// <param name="context">The context.</param> |
| 67 | + public override void InitializeDatabase(TContext context) |
| 68 | + { |
| 69 | + string databseFilePath = GetDatabasePathFromContext(context); |
| 70 | + |
| 71 | + bool dbExists = File.Exists(databseFilePath); |
| 72 | + if (dbExists) |
| 73 | + { |
| 74 | + if (IsSameModel(context)) |
| 75 | + { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + DeleteDatabase(context, databseFilePath); |
| 80 | + base.InitializeDatabase(context); |
| 81 | + SaveHistory(context); |
| 82 | + } |
| 83 | + else |
| 84 | + { |
| 85 | + base.InitializeDatabase(context); |
| 86 | + SaveHistory(context); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + private void DeleteDatabase(TContext context, string databseFilePath) |
| 91 | + { |
| 92 | + context.Database.Connection.Close(); |
| 93 | + GC.Collect(); |
| 94 | + |
| 95 | + // TODO: Comment |
| 96 | + for (int i = 0; i < 5; i++) |
| 97 | + { |
| 98 | + try |
| 99 | + { |
| 100 | + File.Delete(databseFilePath); |
| 101 | + // TODO: Throw exception if 5 tries.. |
| 102 | + break; |
| 103 | + } |
| 104 | + catch (Exception) |
| 105 | + { |
| 106 | + System.Threading.Thread.Sleep(1); |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private void SaveHistory(TContext context) |
| 112 | + { |
| 113 | + var hash = GetHashFromModel(context.Database.Connection); |
| 114 | + var history = GetHistoryRecord(context); |
| 115 | + EntityState entityState; |
| 116 | + if (history == null) |
| 117 | + { |
| 118 | + history = (IHistory)Activator.CreateInstance(historyEntityType); |
| 119 | + entityState = EntityState.Added; |
| 120 | + } |
| 121 | + else |
| 122 | + { |
| 123 | + entityState = EntityState.Modified; |
| 124 | + } |
| 125 | + |
| 126 | + history.Context = context.GetType().FullName; |
| 127 | + history.Hash = hash; |
| 128 | + history.CreateDate = DateTime.UtcNow; |
| 129 | + |
| 130 | + context.Set(historyEntityType).Attach(history); |
| 131 | + context.Entry(history).State = entityState; |
| 132 | + context.SaveChanges(); |
| 133 | + } |
| 134 | + |
| 135 | + private bool IsSameModel(TContext context) |
| 136 | + { |
| 137 | + try |
| 138 | + { |
| 139 | + var hash = GetHashFromModel(context.Database.Connection); |
| 140 | + var history = GetHistoryRecord(context); |
| 141 | + return history?.Hash == hash; |
| 142 | + } |
| 143 | + catch (Exception) |
| 144 | + { |
| 145 | + return false; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + private IHistory GetHistoryRecord(TContext context) |
| 150 | + { |
| 151 | + return context.Set(historyEntityType) |
| 152 | + .AsNoTracking() |
| 153 | + .ToListAsync() |
| 154 | + .Result |
| 155 | + .Cast<IHistory>() |
| 156 | + .SingleOrDefault(); |
| 157 | + } |
| 158 | + |
| 159 | + private string GetHashFromModel(DbConnection connection) |
| 160 | + { |
| 161 | + var sql = GetSqlFromModel(connection); |
| 162 | + string hash = HashCreator.CreateHash(sql); |
| 163 | + return hash; |
| 164 | + } |
| 165 | + |
| 166 | + private string GetSqlFromModel(DbConnection connection) |
| 167 | + { |
| 168 | + var model = ModelBuilder.Build(connection); |
| 169 | + var sqliteSqlGenerator = new SqliteSqlGenerator(model.StoreModel); |
| 170 | + return sqliteSqlGenerator.Generate(); |
| 171 | + } |
| 172 | + } |
| 173 | +} |
0 commit comments