Exemple #1
0
        public void Downgrade(IRepository repository, int version)
        {
            int dbVersion = GetDbVersion(repository);
            if (dbVersion <= version)
            {
                // Already lower or same as current version.
                return;
            }

            if (version < 0)
            {
                throw new SectorException("Version cannot be less than 0");
            }

            // Example downgrade from 4 back to 0:
            // 4_downgrade set version to 3
            // 3_downgrade set version to 2,
            // 2_downgrade set version to 1
            // 1_downgrade set version = 0
            // Means we need to go over range 1, 4 in reverse order, here we iterate
            // over range 1, 4 reversed to { 4, 1 } == 4, 3, 2, 1 and end with dbVersion 0
            int steps = dbVersion - version;
            foreach (var downVersion in Enumerable.Range(version + 1, steps).Reverse())
            {
                using (var transaction = sectorDb.Connection.BeginTransaction())
                {
                    using (var sqlCommand = sectorDb.Connection.CreateCommand())
                    {
                        // Run the SQL for the next version.
                        sqlCommand.CommandText = repository.GetDowngradeSql(downVersion);
                        sqlCommand.ExecuteNonQuery();
                    }

                    // Now update the version table.
                    using (var sqlCommand = sectorDb.Connection.CreateCommand())
                    {
                        // Upgrade the version info.
                        const string templ = "UPDATE {0} SET version = @RepoVer WHERE repository_id = @RepoId";
                        sqlCommand.CommandText = string.Format(templ, SectorDb.TableName);

                        {
                            var param = sqlCommand.CreateParameter();
                            param.DbType = DbType.String;
                            param.ParameterName = "@RepoId";
                            param.Value = repository.RepositoryId;
                            sqlCommand.Parameters.Add(param);
                        }
                        {
                            var param = sqlCommand.CreateParameter();
                            param.DbType = DbType.Int32;
                            param.ParameterName = "@RepoVer";
                            param.Value = downVersion - 1;
                            sqlCommand.Parameters.Add(param);
                        }

                        sqlCommand.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }
            }
        }