//Инициализация, version - версия Excel public static void Initialize(Application application, string version) { try { if (_isInitialized) { return; } IsActivated = new DbVersion().ACheck("Excel") >= 1; if (!IsActivated) { return; } General.Initialize(); Application = application; CommonBook = new ReportBook("", null); CommonBook.OpenHistory(General.ReporterDir + @"ReporterHistory\" + version + "History.accdb", General.HistryTemplateFile); _isInitialized = true; } catch (Exception ex) { ex.MessageError("Ошибка при инициализации построителя отчетов"); } }
public void DoTest2() { UiVersion v = new UiVersion() { ProductCode = "TEST", VersionCode = 2, VersionNumber = "0.0.2", VersionDesc = "测试版本2.", VersionFile = "Test2.exe" }; using (MyVersionManagerContext context = new MyVersionManagerContext()) { // 从数据库中查询数据. DbVersion dv = context.DbVersions.FirstOrDefault(p => p.ProductCode == "TEST" && p.VersionCode == 2); // UI 上面的数据, 更新到 数据库中. Mapper.Map <UiVersion, DbVersion>( source: v, destination: dv, opts: opt => { opt.AfterMap((src, dest) => dest.LastUpdateUser = "******"); }); // 物理保存. context.SaveChanges(); } }
public async Task <GameVersion> LoadVersionAsync(int id, int displayLanguage, CancellationToken token) { try { string query = String.Format(@" SELECT v.id, vn.name FROM versions AS v LEFT JOIN (SELECT e.version_id AS id, COALESCE(o.name, e.name) AS name FROM version_names e LEFT OUTER JOIN version_names o ON e.version_id = o.version_id AND o.local_language_id = {1} WHERE e.local_language_id = 9 GROUP BY e.version_id) AS vn ON v.id = vn.id WHERE v.id = {0} ", id, displayLanguage); IEnumerable <DbVersion> versions = await _connection.QueryAsync <DbVersion>(token, query, new object[0]).ConfigureAwait(false); DbVersion version = versions.FirstOrDefault(); if (version == null) { return(null); } return(new GameVersion { Generation = version.Generation, Id = version.Id, Name = version.Name, VersionGroup = version.VersionGroupId }); } catch (Exception) { return(null); } }
/// <inheritdoc /> public async Task <DbState> GetDbStateSafeAsync(DbVersion desireDbVersion) { try { var result = await ExecuteScalarScriptWithoutInitialCatalogAsync(String.Format(CheckDbExistQueryFormat, DbName)) .ConfigureAwait(false); if (result == null || (Int32)result != 1) { return(DbState.NotCreated); } AssertConnection(Connection); var dbVersion = await InternalGetDbVersionAsync() .ConfigureAwait(false); if (dbVersion == null) { return(DbState.Outdated); } if (dbVersion.Value == desireDbVersion) { return(DbState.Ok); } return(dbVersion.Value < desireDbVersion ? DbState.Outdated : DbState.Newer); } catch (Exception) { return(DbState.Unknown); } }
/// <summary> /// Returns all versions applied in the target database. /// </summary> /// <param name="schemaName">Schema name for schema versions table. When empty, uses the default schema in the target data platform. </param> /// <param name="tableName">Table name for schema versions table. When empty, uses __yuniqldbversion.</param> /// <param name="commandTimeout">Command timeout in seconds.</param> /// <returns>All versions applied in the target database.</returns> public List<DbVersion> GetAllVersions( string schemaName = null, string tableName = null, int? commandTimeout = null) { var sqlStatement = GetPreparedSqlStatement(_dataService.GetSqlForGetAllVersions(), schemaName, tableName); if (null != _traceService) _traceService.Debug($"Executing statement: {Environment.NewLine}{sqlStatement}"); var result = new List<DbVersion>(); using (var connection = _dataService.CreateConnection().KeepOpen()) { var command = connection.CreateCommand( commandText: sqlStatement, commandTimeout: commandTimeout, transaction: null); var reader = command.ExecuteReader(); while (reader.Read()) { var dbVersion = new DbVersion { SequenceId = reader.GetInt16(0), Version = reader.GetString(1), AppliedOnUtc = reader.GetDateTime(2), AppliedByUser = reader.GetString(3) }; result.Add(dbVersion); } } return result; }
private ProjectMetadata GetDbProjectMetadata(DbProjectInfo dbProjectInfo, EnvironmentInfo environmentInfo) { var projectVersions = new List <MachineSpecificProjectVersion>(); DbProjectConfiguration dbProjectConfiguration = environmentInfo.GetDbProjectConfiguration(dbProjectInfo); DatabaseServer databaseServer = environmentInfo.GetDatabaseServer(dbProjectConfiguration.DatabaseServerId); var dbVersions = _dbVersionProvider.GetVersions( dbProjectInfo.DbName, databaseServer.MachineName); DbVersion latestDbVersion = dbVersions .Select(s => DbVersion.FromString(s.Version)) .OrderByDescending(v => v) .FirstOrDefault(); if (latestDbVersion != null) { projectVersions.Add(new MachineSpecificProjectVersion(databaseServer.MachineName, latestDbVersion.ToString())); } return(new ProjectMetadata(dbProjectInfo.Name, environmentInfo.Name, projectVersions)); }
public virtual List <DbVersion> GetAllDbVersions(string connectionString) { _dataService.Initialize(connectionString); var sqlStatement = GetPreparedSqlStatement(_dataService.GetSqlForGetAllVersions(), _dataService.SchemaName, _dataService.TableName); var result = new List <DbVersion>(); using (var connection = _dataService.CreateConnection().KeepOpen()) { var command = connection.CreateCommand(commandText: sqlStatement); var reader = command.ExecuteReader(); while (reader.Read()) { var dbVersion = new DbVersion { SequenceId = reader.GetInt16(0), Version = reader.GetString(1), AppliedOnUtc = reader.GetDateTime(2), AppliedByUser = reader.GetString(3) }; result.Add(dbVersion); } } return(result); }
public void CompareTo_SimpleNumber() { DbVersion lowVersion = new DbVersion(0, 0, 0, 0); DbVersion highVersion = new DbVersion(0, 0, 0, 1); Assert.IsTrue(lowVersion.CompareTo(highVersion) < 0); }
public void CompareTo_HigherNumber() { DbVersion lowVersion = new DbVersion(0, 0, 0, 2); DbVersion highVersion = new DbVersion(0, 0, 0, 10); Assert.IsTrue(lowVersion.CompareTo(highVersion) < 0); }
public async Task MigrateAsync_UpgradeOnSpecifiedTarget_Ok() { var initialDbVersion = new DbVersion(1, 0); var targetDbVersion = new DbVersion(1, 2); var policy = MigrationPolicy.Major | MigrationPolicy.Minor; var dbVersionAfterUpdate = initialDbVersion; var provider = new Mock <IDbProvider>(); provider .Setup(x => x.UpdateCurrentDbVersionAsync(It.IsAny <DbVersion>())) .Callback <DbVersion>(version => dbVersionAfterUpdate = version) .Returns(() => Task.CompletedTask); provider .Setup(x => x.GetDbVersionSafeAsync()) .Returns(() => Task.FromResult(new DbVersion?(initialDbVersion))); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var firstMigration = new Mock <IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock <IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock <IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var migrations = new List <IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.True(result.IsSuccessfully); Assert.Equal(targetDbVersion, dbVersionAfterUpdate); }
public async Task MigrateAsync_NotEnoughMigrations_Error() { var initialDbVersion = new DbVersion(1, 0); var targetDbVersion = new DbVersion(3, 0); var policy = MigrationPolicy.All; var provider = new Mock <IDbProvider>(); provider .Setup(x => x.GetDbVersionSafeAsync()) .Returns(() => Task.FromResult(new DbVersion?(initialDbVersion))); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); var firstMigration = new Mock <IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock <IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock <IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var fourthMigration = new Mock <IMigration>(); fourthMigration .Setup(x => x.Version) .Returns(new DbVersion(2, 0)); var migrations = new List <IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object, fourthMigration.Object }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.False(result.IsSuccessfully); Assert.True(result.Error.HasValue); Assert.Equal(MigrationError.MigrationNotFound, result.Error.Value); }
public async Task MigrateAsync_UpgradeForbidden_Error() { var initialDbVersion = new DbVersion(1, 0); var targetDbVersion = new DbVersion(2, 0); var policy = MigrationPolicy.Forbidden; var provider = new Mock <IDbProvider>(); provider .Setup(x => x.BeginTransaction()) .Returns(() => new MockTransaction()); provider .Setup(x => x.GetAppliedMigrationVersionAsync(It.IsAny <CancellationToken>())) .Returns(() => Task.FromResult(new [] { initialDbVersion } as IReadOnlyCollection <DbVersion>)); var firstMigration = new Mock <IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock <IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock <IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var fourthMigration = new Mock <IMigration>(); fourthMigration .Setup(x => x.Version) .Returns(new DbVersion(2, 0)); var migrations = new List <IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object, fourthMigration.Object }; var migrator = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); var result = await migrator.MigrateSafeAsync(); Assert.False(result.IsSuccessfully); Assert.True(result.Error.HasValue); Assert.Equal(MigrationError.PolicyError, result.Error.Value); }
public DbScriptToRun(DbVersion dbVersion, string scriptPath) { Guard.NotNull(dbVersion); Guard.NotNullNorEmpty(scriptPath); this.DbVersion = dbVersion; this.ScriptPath = scriptPath; }
public void Test_CompareTo_equal(string dbVersionStr1, string dbVersionStr2) { DbVersion dbVersion1 = DbVersion.FromString(dbVersionStr1); DbVersion dbVersion2 = DbVersion.FromString(dbVersionStr2); Assert.AreEqual(0, dbVersion1.CompareTo(dbVersion2)); Assert.AreEqual(0, dbVersion2.CompareTo(dbVersion1)); }
public void TryParse_Numeric_Major_Version() { var parseResult = DbVersion.TryParse("1", out var version); parseResult.Should().BeTrue("it's correct version"); version.Major.Should().Be(1, "version contains only major version"); version.Minor.Should().Be(0, "version contains only minor version"); }
public void Pattern_Should_Handle_Yyymmdd_hhmm_minor_Version() { var parseResult = DbVersion.TryParse("20201208-1850.02", out var version); parseResult.Should().BeTrue("it's correct version"); version.Major.Should().Be(202012081850, "version contains major version"); version.Minor.Should().Be(2, "version contains minor version"); }
public void Pattern_Should_Handle_Numeric_Major_Minor_2_Version() { var parseResult = DbVersion.TryParse("10001.020", out var version); parseResult.Should().BeTrue("it's correct version"); version.Major.Should().Be(10001, "version contains major version"); version.Minor.Should().Be(20, "version contains minor version"); }
public void Test_CompareTo_first_smaller(string dbVersionStr1, string dbVersionStr2) { DbVersion dbVersion1 = DbVersion.FromString(dbVersionStr1); DbVersion dbVersion2 = DbVersion.FromString(dbVersionStr2); Assert.AreEqual(-1, dbVersion1.CompareTo(dbVersion2)); Assert.AreEqual(1, dbVersion2.CompareTo(dbVersion1)); }
public async Task BigBangIntegrationTest() { var provider = _fixture.DbProvider; var isDbExist = await provider.CheckIfDatabaseExistsAsync(_fixture.DbName); Assert.False(isDbExist); await provider.CreateDatabaseIfNotExistsAsync(); isDbExist = await provider.CheckIfDatabaseExistsAsync(_fixture.DbName); Assert.True(isDbExist); await provider.OpenConnectionAsync(); var isTableExist = await provider.CheckIfTableExistsAsync(_fixture.DbProvider.MigrationHistoryTableName); Assert.False(isTableExist); await provider.CreateHistoryTableIfNotExistsAsync(); isTableExist = await provider.CheckIfTableExistsAsync(_fixture.DbProvider.MigrationHistoryTableName); Assert.True(isTableExist); var desiredDbVersion = new DbVersion(1, 0); var state = await provider.GetDbStateSafeAsync(desiredDbVersion); Assert.Equal(DbState.Outdated, state); await provider.UpdateCurrentDbVersionAsync(desiredDbVersion); var currentDbVersion = await provider.GetDbVersionSafeAsync(); Assert.NotNull(currentDbVersion); Assert.Equal(desiredDbVersion, currentDbVersion.Value); var result = await provider.ExecuteScalarScriptWithoutInitialCatalogAsync( $"SELECT 1 AS result FROM pg_database WHERE datname='{provider.DbName}'"); Assert.True(result is int i && i == 1 || result is bool b && !b); await provider.ExecuteScriptAsync("CREATE TABLE dummy (id bigint, val varchar);"); for (var idx = 0; idx < 10; idx++) { var inserted = await provider.ExecuteNonQueryScriptAsync($"INSERT INTO dummy(id, val) VALUES ({idx}, '{idx}_text')"); Assert.True(inserted == 1); } var updated = await provider.ExecuteNonQueryScriptAsync("UPDATE dummy SET val = NULL WHERE id > 6"); Assert.True(updated == 3); await provider.CloseConnectionAsync(); }
private async Task UpdateVersion() { var versionRecord = new DbVersion { Version = Version, Description = Description, }; await _versionCollection.InsertOneAsync(versionRecord); }
//Вызов окна наcтройки public bool Check() { if (!DbVersion.IsImitFile(ImitDataFile)) { Logger.AddError("Не найден или неправильный файл имитационных данных", null, "", Context); return(IsConnected = false); } return(IsConnected = true); }
private static object RevisionRegex(DbVersion dbVersion) { if (dbVersion.Revision == 0 && dbVersion.Build == 0) { return "(\\.0)?"; } return "\\." + dbVersion.Revision; }
private static object BuildRegex(DbVersion dbVersion) { if (dbVersion.Build == 0) { return "(\\.0)?"; } return "\\." + dbVersion.Build; }
private static object BuildRegex(DbVersion dbVersion) { if (dbVersion.Build == 0) { return("(\\.0)?"); } return("\\." + dbVersion.Build); }
private static object RevisionRegex(DbVersion dbVersion) { if (dbVersion.Revision == 0 && dbVersion.Build == 0) { return("(\\.0)?"); } return("\\." + dbVersion.Revision); }
public async Task BigBangIntegrationTest() { var provider = _fixture.DbProvider; var isDbExist = await provider.CheckIfDatabaseExistsAsync(_fixture.DbName); Assert.False(isDbExist); await provider.CreateDatabaseIfNotExistsAsync(); isDbExist = await provider.CheckIfDatabaseExistsAsync(_fixture.DbName); Assert.True(isDbExist); await provider.OpenConnectionAsync(); var isTableExist = await provider.CheckIfTableExistsAsync(_fixture.DbProvider.AppliedMigrationsTableName); Assert.False(isTableExist); await provider.CreateAppliedMigrationsTableIfNotExistsAsync(); isTableExist = await provider.CheckIfTableExistsAsync(_fixture.DbProvider.AppliedMigrationsTableName); Assert.True(isTableExist); var desiredDbVersion = new DbVersion(1, 0); await provider.SaveAppliedMigrationVersionAsync($"Version {desiredDbVersion.Major}.{desiredDbVersion.Minor}", desiredDbVersion); var actualAppliedMigrations = await provider.GetAppliedMigrationVersionAsync(); Assert.NotNull(actualAppliedMigrations); Assert.Equal(1, actualAppliedMigrations.Count); Assert.Equal(desiredDbVersion, actualAppliedMigrations.First()); var result = await provider.ExecuteScalarScriptWithoutInitialCatalogAsync( $"SELECT 1 AS result FROM pg_database WHERE datname='{provider.DbName}'"); Assert.True(result is int i && i == 1 || result is bool b && !b); await provider.ExecuteScriptAsync("CREATE TABLE dummy (id bigint, val varchar);"); for (var idx = 0; idx < 10; idx++) { var inserted = await provider.ExecuteNonQueryScriptAsync($"INSERT INTO dummy(id, val) VALUES ({idx}, '{idx}_text')"); Assert.True(inserted == 1); } var updated = await provider.ExecuteNonQueryScriptAsync("UPDATE dummy SET val = NULL WHERE id > 6"); Assert.True(updated == 3); await provider.CloseConnectionAsync(); }
/// <summary> /// Returns all versions in the target database. /// </summary> /// <param name="schemaName">Schema name for schema versions table. When empty, uses the default schema in the target data platform. </param> /// <param name="tableName">Table name for schema versions table. When empty, uses __yuniqldbversion.</param> /// <param name="commandTimeout">Command timeout in seconds.</param> /// <returns>All versions in the target database.</returns> public List <DbVersion> GetAllVersions( string schemaName = null, string tableName = null, int?commandTimeout = null) { var sqlStatement = GetPreparedSqlStatement(_dataService.GetSqlForGetAllVersions(), schemaName, tableName); if (null != _traceService) { _traceService.Debug($"Executing statement: {Environment.NewLine}{sqlStatement}"); } var result = new List <DbVersion>(); using (var connection = _dataService.CreateConnection().KeepOpen()) { var command = connection.CreateCommand( commandText: sqlStatement, commandTimeout: commandTimeout, transaction: null); var reader = command.ExecuteReader(); while (reader.Read()) { DbVersion dbVersion; if (_dataService.IsAtomicDDLSupported) { dbVersion = new DbVersion { SequenceId = reader.GetInt16(0), Version = reader.GetString(1), AppliedOnUtc = reader.GetDateTime(2), AppliedByUser = reader.GetString(3) }; } else { dbVersion = new DbVersion { SequenceId = reader.GetInt16(0), Version = reader.GetString(1), AppliedOnUtc = reader.GetDateTime(2), AppliedByUser = reader.GetString(3), StatusId = (StatusId)reader.GetInt32(6), FailedScriptPath = reader.GetValue(7) as string, FailedScriptError = reader.GetValue(8) as string }; } result.Add(dbVersion); } } return(result); }
public void CompareTo_SimpleString() { DbVersion lowDbVersion = new DbVersion(0, 0, 0, 0); DbVersion highDbVersion = new DbVersion(0, 0, 0, 1); Version lowVersion = new Version(lowDbVersion.VersionString); Version highVersion = new Version(highDbVersion.VersionString); Assert.IsTrue(lowVersion.CompareTo(highVersion) < 0); }
// ReSharper disable UnusedParameter.Local /// <summary> /// Checks if script makes insert into version history table /// </summary> public static bool IsVersionInsertPresent(DbVersion dbVersion, string script) { var versionInsertRegexes = new[] { string.Format("insert\\s+(into)?\\s+\\[?version(history)?\\]?(.+?){0}\\.{1}{2}{3}", dbVersion.Major, dbVersion.Minor, RevisionRegex(dbVersion), BuildRegex(dbVersion)), string.Format("insert\\s+into\\s+#temp(.+?)VALUES(.*?){0}\\.{1}{2}{3}", dbVersion.Major, dbVersion.Minor, RevisionRegex(dbVersion), BuildRegex(dbVersion)), } .Select(pattern => new Regex(pattern, RegexOptions.IgnoreCase)); return versionInsertRegexes.Any(r => r.IsMatch(script)); }
///<inheritdoc/> public List <DbVersion> GetAllVersions( string metaSchemaName = null, string metaTableName = null, int?commandTimeout = null) { var sqlStatement = GetPreparedSqlStatement(_dataService.GetSqlForGetAllVersions(), metaSchemaName, metaTableName); _traceService?.Debug($"Executing statement: {Environment.NewLine}{sqlStatement}"); var result = new List <DbVersion>(); using (var connection = _dataService.CreateConnection().KeepOpen()) { var command = connection.CreateCommand( commandText: sqlStatement, commandTimeout: commandTimeout, transaction: null); var reader = command.ExecuteReader(); while (reader.Read()) { var dbVersion = new DbVersion { SequenceId = reader.GetInt16(0), Version = reader.GetString(1), AppliedOnUtc = reader.GetDateTime(2), AppliedByUser = reader.GetString(3), AppliedByTool = reader.GetString(4), AppliedByToolVersion = reader.GetString(5), Status = Enum.Parse <Status>(reader.GetString(6)), DurationMs = reader.GetInt32(7), Checksum = reader.GetString(8) }; dbVersion.FailedScriptPath = !reader.IsDBNull(9) ? reader.GetString(9).Unescape() : string.Empty; var failedScriptErrorBase64 = reader.GetValue(10) as string; if (!string.IsNullOrEmpty(failedScriptErrorBase64)) { dbVersion.FailedScriptError = Encoding.UTF8.GetString(Convert.FromBase64String(failedScriptErrorBase64)); } var additionalArtifactsBase64 = reader.GetValue(11) as string; if (!string.IsNullOrEmpty(additionalArtifactsBase64)) { dbVersion.AdditionalArtifacts = Encoding.UTF8.GetString(Convert.FromBase64String(additionalArtifactsBase64)); } result.Add(dbVersion); } } return(result); }
/// <inheritdoc /> public Task DeleteAppliedMigrationVersionAsync(DbVersion version, CancellationToken token = default) { AssertConnection(NpgsqlConnection); var script = $"DELETE FROM \"{_options.MigrationHistoryTableName}\" WHERE version = {version.ToString()}"; return(TryExecuteAsync( () => InternalExecuteScriptAsync(NpgsqlConnection, script, token), MigrationError.MigratingError, $"Can not delete applied migration version from database \"{DbName}\" (version = {version})")); }
private void Window_Loaded(object sender, RoutedEventArgs e) { try { using (var sys = new SysTabl(General.ConfigFile)) AppVersion.Text = sys.SubValue("InfoTask", "AppVersion"); var dbv = new DbVersion(); AppUserOrg.Text = dbv.AUser("Controller"); LicenseNumber.Text = dbv.ANumber("Controller"); } catch { } }
/// <inheritdoc /> public Task SaveAppliedMigrationVersionAsync(string migrationName, DbVersion version, CancellationToken token = default) { AssertConnection(NpgsqlConnection); var script = $"INSERT INTO \"{_options.MigrationHistoryTableName}\" (name, version) " + $"VALUES ('{migrationName}', '{version.ToString()}');"; return(TryExecuteAsync( () => InternalExecuteScriptAsync(NpgsqlConnection, script, token), MigrationError.MigratingError, $"Can not save applied migration version to database \"{DbName}\" (version = {version})")); }
// ReSharper disable UnusedParameter.Local /// <summary> /// Checks if script makes insert into version history table /// </summary> public static bool IsVersionInsertPresent(DbVersion dbVersion, string script) { var versionInsertRegexes = new[] { string.Format("insert\\s+(into)?\\s+\\[?version(history)?\\]?(.+?){0}\\.{1}{2}{3}", dbVersion.Major, dbVersion.Minor, RevisionRegex(dbVersion), BuildRegex(dbVersion)), string.Format("insert\\s+into\\s+#temp(.+?)VALUES(.*?){0}\\.{1}{2}{3}", dbVersion.Major, dbVersion.Minor, RevisionRegex(dbVersion), BuildRegex(dbVersion)), "(alter|create)\\s+procedure\\s+(\\[?init\\]?\\.)?\\[?(init)?version\\]?", } .Select(pattern => new Regex(pattern, RegexOptions.IgnoreCase)); return(versionInsertRegexes.Any(r => r.IsMatch(script))); }
public void MigrateAsync_NotEnoughMigrations_Error() { var targetDbVersion = new DbVersion(3, 0); var policy = MigrationPolicy.Allowed; var provider = new Mock <IDbProvider>(); var firstMigration = new Mock <IMigration>(); firstMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 0)); var secondMigration = new Mock <IMigration>(); secondMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 1)); var thirdMigration = new Mock <IMigration>(); thirdMigration .Setup(x => x.Version) .Returns(new DbVersion(1, 2)); var fourthMigration = new Mock <IMigration>(); fourthMigration .Setup(x => x.Version) .Returns(new DbVersion(2, 0)); var migrations = new List <IMigration> { firstMigration.Object, secondMigration.Object, thirdMigration.Object, fourthMigration.Object }; try { var _ = new DbMigrator( provider.Object, migrations, policy, policy, null, targetDbVersion); Assert.True(false); } catch (Exception) { Assert.True(true); } }
///<inheritdoc/> public List <DbVersion> GetAllVersions( string metaSchemaName = null, string metaTableName = null, int?commandTimeout = null) { var sqlStatement = GetPreparedSqlStatement(_dataService.GetSqlForGetAllVersions(), metaSchemaName, metaTableName); _traceService?.Debug($"Executing statement: {Environment.NewLine}{sqlStatement}"); var result = new List <DbVersion>(); using (var connection = _dataService.CreateConnection().KeepOpen()) { var command = connection.CreateCommand( commandText: sqlStatement, commandTimeout: commandTimeout, transaction: null); var reader = command.ExecuteReader(); while (reader.Read()) { var dbVersion = new DbVersion { SequenceId = reader.GetInt16(0), Version = reader.GetString(1), AppliedOnUtc = reader.GetDateTime(2), AppliedByUser = reader.GetString(3), AppliedByTool = reader.GetString(4), AppliedByToolVersion = reader.GetString(5) }; //capture additional artifacts when present present if (!reader.IsDBNull(6)) { var additionalArtifactsByteStream = reader.GetValue(6) as byte[]; dbVersion.AdditionalArtifacts = Encoding.UTF8.GetString(additionalArtifactsByteStream); } //fill up with information only available for platforms not supporting transactional ddl if (!_dataService.IsAtomicDDLSupported) { dbVersion.Status = Enum.Parse <Status>(reader.GetString(7)); dbVersion.FailedScriptPath = reader.GetValue(8) as string; //as string handles null values dbVersion.FailedScriptError = reader.GetValue(9) as string; //as string handles null values } result.Add(dbVersion); } } return(result); }
public void Add(DbVersion entity) { base.Add(entity); }
public int IndexOf(DbVersion entity) { return base.IndexOf(entity); }
public void Insert(int index, DbVersion entity) { base.Insert(index, entity); }
public bool Remove(DbVersion entity) { return base.Remove(entity); }
private static bool IsScriptSupported(DbVersion scriptVersion) { return string.IsNullOrEmpty(scriptVersion.Tail); }
protected virtual DbVersion GetDbVersionFromScript(SqlScript script) { //get the version numbers (search at end of string) Match match = Regex.Match(script.Name, VERSION_REGEX, RegexOptions.RightToLeft); short major = short.Parse(match.Groups["major"].Value); short minor = short.Parse(match.Groups["minor"].Value); short build = short.Parse(match.Groups["build"].Value); short revision = short.Parse(match.Groups["revision"].Value); //match on all the comments and build up a string StringBuilder sb = new StringBuilder(); Regex commentRegex = new Regex(@"<VersionComment>(?<comment>.*)</VersionComment>"); MatchCollection commentMatches = commentRegex.Matches(script.Contents); foreach (Match m in commentMatches) sb.Append(m.Groups["comment"].Value + "\r\n"); //i don't want to store blank strings. Turn them null if needed string comments = sb.ToString(); if (string.IsNullOrWhiteSpace(comments)) comments = null; DbVersion version = new DbVersion(major, minor, build, revision, Environment.UserName, comments); return version; }
public bool Contains(DbVersion entity) { return base.Contains(entity); }