private static async Task Noop_when_database_does_not_exist_test(bool async, bool file)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false, useFileName: file))
            {
                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(context);

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    if (async)
                    {
                        Assert.False(await creator.EnsureDeletedAsync());
                    }
                    else
                    {
                        Assert.False(creator.EnsureDeleted());
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
        private static async Task Creates_physical_database_but_not_tables_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);

                Assert.False(creator.Exists());

                if (async)
                {
                    await creator.CreateAsync();
                }
                else
                {
                    creator.Create();
                }

                Assert.True(creator.Exists());

                if (testDatabase.Connection.State != ConnectionState.Open)
                {
                    await testDatabase.Connection.OpenAsync();
                }

                Assert.Equal(0, (await testDatabase.QueryAsync <string>(
                                     "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")).Count());

                Assert.True(
                    await testDatabase.ExecuteScalarAsync <bool>(
                        string.Concat(
                            "SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name='",
                            testDatabase.Connection.Database,
                            "'")));
            }
        }
 private static async Task Returns_false_when_database_exists_but_has_no_tables_test(bool async)
 {
     using (var testDatabase = SqlServerTestStore.CreateScratch())
     {
         var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);
         Assert.False(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase());
     }
 }
        private static async Task Returns_true_when_database_exists_and_has_any_tables_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch())
            {
                await testDatabase.ExecuteNonQueryAsync("CREATE TABLE SomeTable (Id uniqueidentifier)");

                var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);
                Assert.True(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase());
            }
        }
Esempio n. 5
0
        public MigrationsSqlServerFixture()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkSqlServer()
                                  .BuildServiceProvider();

            _testStore = SqlServerTestStore.CreateScratch();

            _options = new DbContextOptionsBuilder()
                       .UseInternalServiceProvider(serviceProvider)
                       .UseSqlServer(_testStore.ConnectionString, b => b.ApplyConfiguration()).Options;
        }
        public override TestStore CreateTestStore(Type testStoreType)
        {
            if (testStoreType == typeof(InMemoryTestStore))
            {
                return(new InMemoryTestStore());
            }

            if (testStoreType == typeof(SqlServerTestStore))
            {
                return(SqlServerTestStore.CreateScratch());
            }

            throw new NotImplementedException();
        }
        private static async Task Returns_true_when_database_exists_test(bool async, bool file)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: true, useFileName: file))
            {
                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(context);

                    Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
        public async Task Empty_Migration_Creates_Database()
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                using (var context = CreateContext(testDatabase))
                {
                    var creator = (SqlServerDatabaseCreator)context.GetService <IRelationalDatabaseCreator>();
                    creator.RetryTimeout = TimeSpan.FromMinutes(10);

                    await context.Database.MigrateAsync();

                    Assert.True(creator.Exists());
                }
            }
        }
        private static async Task Throws_if_database_already_exists_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch())
            {
                var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);

                var ex = async
                    ? await Assert.ThrowsAsync <SqlException>(() => creator.CreateAsync())
                    : Assert.Throws <SqlException>(() => creator.Create());

                Assert.Equal(
                    1801, // Database with given name already exists
                    ex.Number);
            }
        }
        private static async Task Throws_when_database_does_not_exist_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);

                if (async)
                {
                    await Assert.ThrowsAsync <SqlException>(() => creator.DeleteAsync());
                }
                else
                {
                    Assert.Throws <SqlException>(() => creator.Delete());
                }
            }
        }
        private static async Task Creates_schema_in_existing_database_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch())
            {
                using (var context = new SqlServerDatabaseCreatorTest.BloggingContext(testDatabase))
                {
                    var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(context);

                    if (async)
                    {
                        await creator.CreateTablesAsync();
                    }
                    else
                    {
                        creator.CreateTables();
                    }

                    if (testDatabase.Connection.State != ConnectionState.Open)
                    {
                        await testDatabase.Connection.OpenAsync();
                    }

                    var tables = (await testDatabase.QueryAsync <string>(
                                      "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")).ToList();
                    Assert.Equal(1, tables.Count);
                    Assert.Equal("Blogs", tables.Single());

                    var columns = (await testDatabase.QueryAsync <string>(
                                       "SELECT TABLE_NAME + '.' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Blogs'")).ToList();
                    Assert.Equal(14, columns.Count);
                    Assert.True(columns.Any(c => c == "Blogs.Key1"));
                    Assert.True(columns.Any(c => c == "Blogs.Key2"));
                    Assert.True(columns.Any(c => c == "Blogs.Cheese"));
                    Assert.True(columns.Any(c => c == "Blogs.ErMilan"));
                    Assert.True(columns.Any(c => c == "Blogs.George"));
                    Assert.True(columns.Any(c => c == "Blogs.TheGu"));
                    Assert.True(columns.Any(c => c == "Blogs.NotFigTime"));
                    Assert.True(columns.Any(c => c == "Blogs.ToEat"));
                    Assert.True(columns.Any(c => c == "Blogs.OrNothing"));
                    Assert.True(columns.Any(c => c == "Blogs.Fuse"));
                    Assert.True(columns.Any(c => c == "Blogs.WayRound"));
                    Assert.True(columns.Any(c => c == "Blogs.On"));
                    Assert.True(columns.Any(c => c == "Blogs.AndChew"));
                    Assert.True(columns.Any(c => c == "Blogs.AndRow"));
                }
            }
        }
Esempio n. 12
0
        public void PrimaryKeyWithSequence()
        {
            using (var scratch = SqlServerTestStore.CreateScratch())
            {
                scratch.ExecuteNonQuery(@"
CREATE SEQUENCE PrimaryKeyWithSequenceSequence
    AS int
    START WITH 1
    INCREMENT BY 1

CREATE TABLE PrimaryKeyWithSequence (
    PrimaryKeyWithSequenceId int DEFAULT(NEXT VALUE FOR PrimaryKeyWithSequenceSequence),
    PRIMARY KEY (PrimaryKeyWithSequenceId)
);
");

                var configuration = new ReverseEngineeringConfiguration
                {
                    ConnectionString     = scratch.ConnectionString,
                    ProjectPath          = TestProjectDir + Path.DirectorySeparatorChar,
                    ProjectRootNamespace = TestNamespace,
                    ContextClassName     = "PrimaryKeyWithSequenceContext",
                    UseFluentApiOnly     = true
                };
                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string> {
                        "PrimaryKeyWithSequenceContext.expected",
                        "PrimaryKeyWithSequence.expected"
                    }
                };

                var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        private static async Task Throws_if_database_does_not_exist_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);

                var errorNumber
                    = async
                        ? (await Assert.ThrowsAsync <SqlException>(() => creator.CreateTablesAsync())).Number
                        : Assert.Throws <SqlException>(() => creator.CreateTables()).Number;

                if (errorNumber != 233) // skip if no-process transient failure
                {
                    Assert.Equal(
                        4060, // Login failed error number
                        errorNumber);
                }
            }
        }
        private static async Task Deletes_database_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch())
            {
                testDatabase.Connection.Close();

                var creator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);

                Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                if (async)
                {
                    await creator.DeleteAsync();
                }
                else
                {
                    creator.Delete();
                }

                Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
            }
        }
        private static async Task Throws_when_database_does_not_exist_test(bool async)
        {
            using (var testDatabase = SqlServerTestStore.CreateScratch(createDatabase: false))
            {
                var databaseCreator = SqlServerDatabaseCreatorTest.GetDatabaseCreator(testDatabase);
                await databaseCreator.ExecutionStrategyFactory.Create().ExecuteAsync(
                    databaseCreator,
                    async creator =>
                {
                    var errorNumber = async
                                ? (await Assert.ThrowsAsync <SqlException>(() => creator.HasTablesAsyncBase())).Number
                                : Assert.Throws <SqlException>(() => creator.HasTablesBase()).Number;

                    if (errorNumber != 233)         // skip if no-process transient failure
                    {
                        Assert.Equal(
                            4060,         // Login failed error number
                            errorNumber);
                    }
                });
            }
        }
Esempio n. 16
0
 public ScratchDatabaseFixture()
 {
     _testStore = new LazyRef <SqlServerTestStore>(() => SqlServerTestStore.CreateScratch());
 }
Esempio n. 17
0
 public SqlServerDatabaseModelFixture()
 {
     TestStore = SqlServerTestStore.CreateScratch();
 }
Esempio n. 18
0
        public void Sequences()
        {
            using (var scratch = SqlServerTestStore.CreateScratch())
            {
                scratch.ExecuteNonQuery(@"
CREATE SEQUENCE CountByTwo
    START WITH 1
    INCREMENT BY 2;

CREATE SEQUENCE CyclicalCountByThree
    START WITH 6
    INCREMENT BY 3
    MAXVALUE 27
    MINVALUE 0
    CYCLE;

CREATE SEQUENCE TinyIntSequence
    AS tinyint
    START WITH 1;

CREATE SEQUENCE SmallIntSequence
    AS smallint
    START WITH 1;

CREATE SEQUENCE IntSequence
    AS int
    START WITH 1;

CREATE SEQUENCE DecimalSequence
    AS decimal;

CREATE SEQUENCE NumericSequence
    AS numeric;");

                var configuration = new ReverseEngineeringConfiguration
                {
                    ConnectionString     = scratch.ConnectionString,
                    ProjectPath          = TestProjectDir + Path.DirectorySeparatorChar,
                    ProjectRootNamespace = TestNamespace,
                    ContextClassName     = "SequenceContext"
                };
                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string> {
                        "SequenceContext.expected"
                    }
                };

                var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertLog(new LoggerMessages
                {
                    Warn =
                    {
                        RelationalDesignStrings.BadSequenceType("DecimalSequence", "decimal"),
                        RelationalDesignStrings.BadSequenceType("NumericSequence", "numeric")
                    }
                });

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }