Skip to content

Commit

Permalink
Fix and test for Reset operation (#22)
Browse files Browse the repository at this point in the history
* test for reset

Signed-off-by: Piotr <[email protected]>

* fix for missing reset script

Signed-off-by: Piotr <[email protected]>

* Add auditing to reset.
Add additional test,

Signed-off-by: Piotr <[email protected]>
Co-authored-by: Piotr <[email protected]>
Co-authored-by: Eric Sibly <[email protected]>
  • Loading branch information
3 people committed Sep 8, 2022
1 parent 3c930d1 commit f88e254
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 11 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

Represents the **NuGet** versions.

## v1.0.15
- *Fixed:* `Reset` command updated to load embedded SQL resource correctly.

## v1.0.14
- *Enhancement:* Removed `DbUp` package dependencies and implemented equivalent (basics) that is compatible with `[dbo].[SchemaVersion]` journal management. Primary reason is related to the slow uptake of pull requests by the maintainers of `DbUp` that imposes limitations on `DbEx`.
- *Fixed:* `DbTypeMapper` updated to support `SMALLDATETIME` and `IMAGE` Microsoft Sql Server types.
Expand Down
2 changes: 1 addition & 1 deletion src/DbEx/DbEx.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<RootNamespace>DbEx</RootNamespace>
<Version>1.0.14</Version>
<Version>1.0.15</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>DbEx Developers</Authors>
<Company>Avanade</Company>
Expand Down
4 changes: 3 additions & 1 deletion src/DbEx/Migration/DatabaseMigrationScript.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ public DatabaseMigrationScript(string sql, string name)
/// <summary>
/// Gets the resource or file <see cref="System.IO.StreamReader"/>.
/// </summary>
public StreamReader GetStreamReader() =>_assembly is not null ? new StreamReader(_assembly!.GetManifestResourceStream(Name)!) : (_file is not null ? _file!.OpenText() : new StreamReader(new MemoryStream(Encoding.Default.GetBytes(_sql))));
public StreamReader GetStreamReader() => _assembly is not null
? new StreamReader(_assembly!.GetManifestResourceStream(Name)!)
: (_file is not null ? _file!.OpenText() : new StreamReader(new MemoryStream(Encoding.Default.GetBytes(_sql))));
}
}
13 changes: 9 additions & 4 deletions src/DbEx/Migration/SqlServer/SqlServerMigrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,13 @@ protected override async Task<bool> DatabaseSchemaAsync(List<DatabaseMigrationSc
/// <inheritdoc/>
protected override async Task<bool> DatabaseResetAsync()
{
Logger.LogInformation(" Deleting data from all tables (excludes schema 'dbo' and 'cdc').");
var ss = new DatabaseMigrationScript(typeof(DatabaseExtensions).Assembly, $"{typeof(IDatabase).Namespace}.SqlServer.DeleteAllAndReset.sql") { RunAlways = true };
return await ExecuteScriptsAsync(new DatabaseMigrationScript[] { ss }, false).ConfigureAwait(false);
Logger.LogInformation(" Deleting data from all tables (excludes schema 'dbo' and 'cdc')...");
using var sr = StreamLocator.GetResourcesStreamReader("SqlServer.DeleteAllAndReset.sql", new Assembly[] { typeof(DatabaseExtensions).Assembly }).StreamReader!;
var tables = await Database.SqlStatement(sr.ReadToEnd()).SelectQueryAsync(dr => { Logger.LogInformation("{Content}", $" [{dr.GetValue<string>("Schema")}].[{dr.GetValue<string>("Table")}]"); return 0; }).ConfigureAwait(false);
if (!tables.Any())
Logger.LogInformation(" None.");

return true;
}

/// <inheritdoc/>
Expand Down Expand Up @@ -196,7 +200,8 @@ public override async Task<bool> ExecuteScriptsAsync(IEnumerable<DatabaseMigrati

try
{
await Database.SqlStatement(script.GetStreamReader().ReadToEnd()).NonQueryAsync(default).ConfigureAwait(false);
using var sr = script.GetStreamReader();
await Database.SqlStatement(sr.ReadToEnd()).NonQueryAsync(default).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
9 changes: 8 additions & 1 deletion src/DbEx/Resources/SqlServer/DeleteAllAndReset.sql
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
-- Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/DbEx

CREATE TABLE #temp ([Schema] VARCHAR(256), [Table] VARCHAR(256))

DECLARE t_cursor
CURSOR LOCAL READ_ONLY STATIC SCROLL FOR
SELECT t.TABLE_SCHEMA, t.TABLE_NAME FROM (
SELECT TABLE_SCHEMA, TABLE_NAME, (SELECT OBJECTPROPERTY(OBJECT_ID(''+TABLE_SCHEMA+ '.'+ TABLE_NAME +''), 'TableTemporalType')) AS TABLE_HISTORY
FROM INFORMATION_SCHEMA.TABLES as i
WHERE i.TABLE_TYPE = 'BASE TABLE' AND i.TABLE_SCHEMA <> 'dbo' AND i.TABLE_SCHEMA <> 'cdc'
) AS [t] WHERE t.TABLE_HISTORY IN (0,2)
ORDER BY t.TABLE_SCHEMA, t.TABLE_NAME

DECLARE @TableSchema VARCHAR(256)
DECLARE @TableName VARCHAR(256)
Expand All @@ -31,6 +34,7 @@ BEGIN
SET @SqlCommand = 'SET QUOTED_IDENTIFIER ON; DELETE FROM [' + @TableSchema + '].[' + @TableName + ']'
PRINT @SqlCommand
EXECUTE (@SqlCommand)
INSERT INTO #temp ([Schema], [Table]) VALUES (@TableSchema, @TableName)
FETCH NEXT FROM t_cursor into @TableSchema, @TableName
END

Expand All @@ -45,4 +49,7 @@ BEGIN
END

CLOSE t_cursor
DEALLOCATE t_cursor
DEALLOCATE t_cursor

SELECT [Schema], [Table] FROM #temp
DROP TABLE #temp
43 changes: 39 additions & 4 deletions tests/DbEx.Test/SqlServerMigratorTest.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using CoreEx.Database;
using System;
using System.Linq;
using System.Threading.Tasks;
using CoreEx.Database;
using CoreEx.Database.SqlServer;
using DbEx.Migration.Data;
using DbEx.Migration.SqlServer;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace DbEx.Test
{
Expand Down Expand Up @@ -174,5 +174,40 @@ public async Task B100_Execute_Console_Error()
var r = await m.ExecuteSqlStatementsAsync("SELECT * FROM Test.Contact", "SELECT BANANAS").ConfigureAwait(false);
Assert.IsFalse(r);
}

[Test]
public async Task A140_Reset_None()
{
var cs = UnitTest.GetConfig("DbEx_").GetConnectionString("NoneDb");
var l = UnitTest.GetLogger<SqlServerMigratorTest>();
var m = new SqlServerMigrator(cs, Migration.MigrationCommand.Reset, l);
var r = await m.MigrateAsync().ConfigureAwait(false);

Assert.IsTrue(r);
}

[Test]
public async Task A150_Reset_Console()
{
var (cs, l, m) = await CreateConsoleDb().ConfigureAwait(false);
using var db = new SqlServerDatabase(() => new SqlConnection(cs));

// There should be data loaded in Test.Contact.
var c = await db.SqlStatement("SELECT COUNT(*) FROM Test.Contact").ScalarAsync<int>().ConfigureAwait(false);
Assert.That(c, Is.GreaterThanOrEqualTo(1));

// Execute Reset.
m = new SqlServerMigrator(cs, Migration.MigrationCommand.Reset, l);
var r = await m.MigrateAsync().ConfigureAwait(false);
Assert.IsTrue(r);

// There should now be no data in Test.Contact.
c = await db.SqlStatement("SELECT COUNT(*) FROM Test.Contact").ScalarAsync<int>().ConfigureAwait(false);
Assert.That(c, Is.EqualTo(0));

// Tables in dbo schema should not be touched.
c = await db.SqlStatement("SELECT COUNT(*) FROM [dbo].[SchemaVersions]").ScalarAsync<int>().ConfigureAwait(false);
Assert.That(c, Is.GreaterThanOrEqualTo(1));
}
}
}

0 comments on commit f88e254

Please sign in to comment.