Ejemplo n.º 1
0
        public IEnumerable <Migration> BuildMigrations(int version)
        {
            Console.WriteLine($"Running migrations from version {version}.");

            foreach (var migration in migrationFactory.BuildMigrations(version))
            {
                Console.WriteLine(migration.Sql);

                yield return(migration);
            }
        }
Ejemplo n.º 2
0
        public async Task MigrateAsync(IMigrationFactory migrationFactory, CancellationToken cancellationToken)
        {
            if (migrationFactory == null)
            {
                throw new ArgumentNullException(nameof(migrationFactory));
            }

            cancellationToken.ThrowIfCancellationRequested();

            using (var connection = await connectionFactory(cancellationToken))
                using (var transaction = connection.BeginTransaction(IsolationLevel.Serializable))
                {
                    var version = await connection.QuerySingleAsync <int>(
                        "PRAGMA user_version;",
                        transaction : transaction
                        ).ConfigureAwait(false);

                    var migrations = migrationFactory.BuildMigrations(version);

                    foreach (var migration in migrations)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        await connection.ExecuteAsync(
                            sql : migration.Sql,
                            param : migration.Parameter,
                            commandType : migration.CommandType,
                            commandTimeout : migration.CommandTimeout,
                            transaction : transaction
                            ).ConfigureAwait(false);

                        // Bump version; Dapper does not support parameters with PRAGMAs.
                        // SQL injection is not an issue here, since we use integers for version.
                        await connection.ExecuteAsync(
                            $"PRAGMA user_version = {++version};",
                            transaction : transaction
                            ).ConfigureAwait(false);
                    }

                    cancellationToken.ThrowIfCancellationRequested();
                    transaction.Commit();
                }
        }