Exemplo n.º 1
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="LiteMigration"/> class.
        /// </summary>
        /// <param name="databasePath">Path to the SQLite database.</param>
        /// <param name="baseNamespace">Namespace to scripts.</param>
        /// <param name="databaseType">Type of database connection.</param>
        public LiteMigration(string databasePath, string baseNamespace, DatabaseType databaseType, string baseAssembly = "")
        {
            ////RevisionTable = nameof(VersionInfo);  // FUTURE
            // Set to current namespace, it's a something
            DatabasePath = databasePath;
            DatabaseType = databaseType;

            // Create version info table here
            // Initialize().Wait();
            Migrations = new MigrationFactory();
            Migrations.BaseAssemblyFile = baseAssembly;
            Migrations.BaseNamespace    = baseNamespace;

            switch (databaseType)
            {
            case DatabaseType.SQLiteCipher:
                _sqlEngine = new Engines.SqlitePclEngine();

                // In-testing
                //// _sqlEngine = new Engines.SqlcipherEngine();
                break;

            case DatabaseType.SQLite:
            default:
                _sqlEngine = new Engines.SqlitePclEngine();
                break;
            }

            // The next operation may begin before this is finished being created
            VersionInitialize();

            //// Task.Run(async () => await VersionInitializeAsync().ConfigureAwait(false));

            _isInitialized = true;
        }
        /// <summary>
        /// Applies the provided migrations to the target system. The engine does not check
        /// if the specified migrations were already applied.
        /// PLEASE NOTE: this method will not throw. You must check the resulting summary for errors that might have occurred.
        /// </summary>
        /// <param name="pendingMigrations">The list of migrations that should be applied.</param>
        /// <param name="now">
        /// The current time when the migration engine starts to execute (optional). Please use a UTC time stamp if possible. If
        /// you do not provide a value, <see cref="DateTime.UtcNow" /> will be used.
        /// </param>
        /// <param name="cancellationToken">The token to cancel this asynchronous operation (optional).</param>
        /// <returns>A summary of all migrations that have been applied in this run.</returns>
        public virtual async Task <MigrationSummary <TMigrationInfo> > ApplyMigrationsAsync(List <PendingMigration <TMigrationVersion> >?pendingMigrations,
                                                                                            DateTime?now = null,
                                                                                            CancellationToken cancellationToken = default)
        {
            if (pendingMigrations.IsNullOrEmpty())
            {
                return(MigrationSummary <TMigrationInfo> .Empty);
            }

            var timeStamp         = now ?? DateTime.UtcNow;
            var appliedMigrations = new List <TMigrationInfo>(pendingMigrations.Count);

            for (var i = 0; i < pendingMigrations.Count; i++)
            {
                var pendingMigration = pendingMigrations[i];

                IMigrationSession <TMigrationContext, TMigrationInfo>?session = null;
                TMigration?migration = default;
                try
                {
                    migration = MigrationFactory.CreateMigration(pendingMigration.MigrationType);
                    session   = await SessionFactory.CreateSessionForMigrationAsync(migration, cancellationToken);

                    await migration.ApplyAsync(session.Context, cancellationToken);

                    var migrationInfo = CreateMigrationInfo(migration, timeStamp);
                    await session.StoreMigrationInfoAsync(migrationInfo, cancellationToken);

                    await session.SaveChangesAsync(cancellationToken);

                    appliedMigrations.Add(migrationInfo);
                }
                catch (Exception exception)
                {
                    var error = new MigrationError <TMigrationVersion>(pendingMigration.MigrationVersion, exception);
                    return(new MigrationSummary <TMigrationInfo>(error, appliedMigrations));
                }
                finally
                {
                    // ReSharper disable SuspiciousTypeConversion.Global -- clients of the library should be allowed to write disposable migrations
                    if (migration is IAsyncDisposable asyncDisposableMigration)
                    {
                        await asyncDisposableMigration.DisposeAsync();
                    }
                    else if (migration is IDisposable disposableMigration)
                    {
                        disposableMigration.Dispose();
                    }
                    // ReSharper restore SuspiciousTypeConversion.Global

                    if (session != null)
                    {
                        await session.DisposeAsync();
                    }
                }
            }

            return(new MigrationSummary <TMigrationInfo>(appliedMigrations));
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            var p                  = new Params(args);
            var tableName          = p.Get("table name", "-t");
            var idColumnName       = p.Get("id column name", "-i");
            var parentIdColumnName = p.Get("parent id column name", "-p");

            File.WriteAllText("out.sql", MigrationFactory.CreateScript(tableName, idColumnName, parentIdColumnName).ToString());
        }
Exemplo n.º 4
0
 public Runner(IDataClient dataClient,
               Assembly targetAssembly,
               IVersionRepository versionRepository)
 {
     _dataClient        = dataClient;
     _databaseKind      = _dataClient.Database.Provider.DatabaseKind;
     _targetAssembly    = targetAssembly;
     _versionRepository = versionRepository;
     _migrationFactory  = new MigrationFactory(_dataClient);
     _initialVersion    = -1;
 }
Exemplo n.º 5
0
        public void InstantiateNonMigrationClass_Skip()
        {
            var sut = new MigrationFactory();

            var result = sut.Create(new List <Type> {
                typeof(string)
            })
                         .ToList();

            Assert.Empty(result);
        }
Exemplo n.º 6
0
        public void InstantiateMigration()
        {
            var sut = new MigrationFactory();

            var result = sut.Create(new List <Type> {
                typeof(B1Migration)
            })
                         .ToList();

            Assert.IsType <B1Migration>(result.Single());
        }
Exemplo n.º 7
0
        protected async Task <LRTest> Test(string tree)
        {
            var tableName = CreateTableName();
            await CreateTable.New("[%_Node_%]", SqlStuff.Escape(tableName)).ExecuteAsync(_connection);

            await Arrange(tree, SqlStuff.Escape(tableName), _connection);

            await MigrationFactory.CreateScript(tableName, "Id", "Parent_Id").ExecuteAsync(_connection);

            return(new LRTest(tableName, tree, _connection));
        }
Exemplo n.º 8
0
 public void MigrateDataBase()
 {
     try
     {
         var migrater = MigrationFactory.Build(Connection);
         migrater.ExecuteCommand();
     }
     catch (Exception e)
     {
         throw new Exception("Database migration failed." + e.Message);
     }
 }
        public void UseActivatorToCreateFact()
        {
            // Arrange
            var factory = new MigrationFactory();

            // Act
            var migration = factory.Create(typeof(MigrationStub));

            // Assert
            migration.Should().NotBe(null);
            migration.Should().BeOfType <MigrationStub>();
        }
 public void Init()
 {
     _dataClient = new Mock <IDataClient>().Object;
     _factory    = new MigrationFactory(_dataClient);
 }
Exemplo n.º 11
0
 public MigrationFactoryTests()
 {
     _dataClient = new Mock <IDataClient>().Object;
     _factory    = new MigrationFactory(_dataClient);
 }