Exemple #1
0
        public virtual async void Foreign_key_to_unique_index()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("FkToAltKey" + DbSuffix).AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS User (
    Id INTEGER PRIMARY KEY,
    AltId INTEGER NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS Comment (
    Id INTEGER PRIMARY KEY,
    UserAltId INTEGER NOT NULL,
    Contents TEXT,
    FOREIGN KEY (UserAltId) REFERENCES User (AltId)
);");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    ConnectionString     = testStore.ConnectionString,
                    ContextClassName     = "FkToAltKeyContext",
                    ProjectPath          = TestProjectPath,
                    ProjectRootNamespace = "E2E.Sqlite",
                    UseFluentApiOnly     = UseFluentApiOnly,
                    TableSelectionSet    = TableSelectionSet.All
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "FkToAltKey"))
                {
                    Files =
                    {
                        "FkToAltKeyContext.expected",
                        "Comment.expected",
                        "User.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, TestProjectFullPath)
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public async void It_uses_templates()
        {
            var dbContextFileName  = "EntityFramework.Sqlite.Design." + ReverseEngineeringGenerator.DbContextTemplateFileName;
            var entityTypeFileName = "EntityFramework.Sqlite.Design." + ReverseEngineeringGenerator.EntityTypeTemplateFileName;
            var entityTemplate     = "This is an entity type template! (For real)";
            var contextTemplate    = "Also a 100% legit template";
            var outputDir          = "gen";
            var templatesDir       = "templates";

            using (var testStore = SqliteTestStore.CreateScratch())
            {
                testStore.ExecuteNonQuery("CREATE TABLE RealMccoy ( Col1 text PRIMARY KEY); ");

                InMemoryFiles.OutputFile(templatesDir, dbContextFileName, contextTemplate);
                InMemoryFiles.OutputFile(templatesDir, entityTypeFileName, entityTemplate);

                var config = new ReverseEngineeringConfiguration
                {
                    ConnectionString   = testStore.Connection.ConnectionString,
                    Provider           = MetadataModelProvider,
                    Namespace          = "Test",
                    OutputPath         = outputDir,
                    CustomTemplatePath = templatesDir
                };
                var filePaths = await Generator.GenerateAsync(config);

                var expectedLog = new LoggerMessages
                {
                    Info =
                    {
                        "Using custom template " + Path.Combine(templatesDir, dbContextFileName),
                        "Using custom template " + Path.Combine(templatesDir, entityTypeFileName)
                    }
                };
                AssertLog(expectedLog);

                Assert.Equal(2, filePaths.Count);

                foreach (var fileName in filePaths.Select(Path.GetFileName))
                {
                    var fileContents = InMemoryFiles.RetrieveFileContents(outputDir, fileName);
                    var contents     = fileName.EndsWith("Context.cs") ? contextTemplate : entityTemplate;
                    Assert.Equal(contents, fileContents);
                }
            }
        }
        public MappingQuerySqliteFixture()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkSqlite()
                                  .AddSingleton <ILoggerFactory>(TestSqlLoggerFactory)
                                  .BuildServiceProvider(validateScopes: true);

            _testDatabase = SqliteTestStore.GetNorthwindStore();

            _options = new DbContextOptionsBuilder()
                       .UseModel(CreateModel())
                       .UseSqlite(
                _testDatabase.ConnectionString,
                b => b.SuppressForeignKeyEnforcement())
                       .UseInternalServiceProvider(serviceProvider)
                       .Options;
        }
        public async void It_handles_unsafe_names()
        {
            using (var testStore = SqliteTestStore.CreateScratch())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE 'Named with space' ( Id PRIMARY KEY );
CREATE TABLE '123 Invalid Class Name' ( Id PRIMARY KEY);
CREATE TABLE 'Bad characters `~!@#$%^&*()+=-[];''"",.<>/?|\ ' ( Id PRIMARY KEY);
CREATE TABLE ' Bad columns ' (
    'Space jam' PRIMARY KEY,
    '123 Go`',
    'Bad to the bone. `~!@#$%^&*()+=-[];''"",.<>/?|\ ',
    'Next one is all bad',
    '@#$%^&*()'
);
CREATE TABLE Keywords (
    namespace PRIMARY KEY,
    virtual,
    public,
    class,
    string,
    FOREIGN KEY (class) REFERENCES string (string)
);
CREATE TABLE String (
    string PRIMARY KEY,
    FOREIGN KEY (string) REFERENCES String (string)
);
");

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    Provider         = MetadataModelProvider,
                    ConnectionString = testStore.Connection.ConnectionString,
                    Namespace        = "E2E.Sqlite",
                    OutputPath       = "testout"
                });

                AssertLog(new LoggerMessages());

                var files = new FileSet(InMemoryFiles, "testout")
                {
                    Files = results.Select(Path.GetFileName).ToList()
                };
                AssertCompile(files);
            }
        }
        public async void Many_to_many()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("ManyToMany").AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE Users ( Id PRIMARY KEY);
CREATE TABLE Groups (Id PRIMARY KEY);
CREATE TABLE Users_Groups (
    Id PRIMARY KEY,
    UserId, 
    GroupId, 
    UNIQUE (UserId, GroupId), 
    FOREIGN KEY (UserId) REFERENCES Users (Id), 
    FOREIGN KEY (GroupId) REFERENCES Groups (Id)
);
");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    Provider         = MetadataModelProvider,
                    ConnectionString = testStore.Connection.ConnectionString,
                    Namespace        = "E2E.Sqlite",
                    OutputPath       = "testout"
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), "ReverseEngineering/Expected/ManyToMany")
                {
                    Files =
                    {
                        "ModelContext.expected",
                        "Groups.expected",
                        "Users.expected",
                        "Users_Groups.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = results.Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Exemple #6
0
        public async Task Many_to_many()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("ManyToMany" + DbSuffix))
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS Users ( Id PRIMARY KEY);
CREATE TABLE IF NOT EXISTS Groups (Id PRIMARY KEY);
CREATE TABLE IF NOT EXISTS Users_Groups (
    Id PRIMARY KEY,
    UserId,
    GroupId,
    UNIQUE (UserId, GroupId),
    FOREIGN KEY (UserId) REFERENCES Users (Id),
    FOREIGN KEY (GroupId) REFERENCES Groups (Id)
);
");

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    ConnectionString     = testStore.ConnectionString,
                    ProjectPath          = TestProjectPath,
                    ProjectRootNamespace = "E2E.Sqlite",
                    UseFluentApiOnly     = UseFluentApiOnly,
                    TableSelectionSet    = TableSelectionSet.All
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "ManyToMany"))
                {
                    Files =
                    {
                        "ManyToMany" + DbSuffix + "Context.expected",
                        "Groups.expected",
                        "Users.expected",
                        "UsersGroups.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, TestProjectFullPath)
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public async void One_to_one()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("OneToOne" + DbSuffix).AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS Principal (
    Id INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE IF NOT EXISTS Dependent (
    Id INT,
    PrincipalId INT NOT NULL UNIQUE,
    PRIMARY KEY (Id),
    FOREIGN KEY (PrincipalId) REFERENCES Principal (Id)
);
");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    ConnectionString     = testStore.Connection.ConnectionString,
                    ProjectPath          = "testout",
                    ProjectRootNamespace = "E2E.Sqlite",
                    UseFluentApiOnly     = UseFluentApiOnly,
                    TableSelectionSet    = TableSelectionSet.All
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "OneToOne"))
                {
                    Files =
                    {
                        "OneToOne" + DbSuffix + "Context.expected",
                        "Dependent.expected",
                        "Principal.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Exemple #8
0
        public SqliteScaffoldingModelFactoryTest()
        {
            _testStore = SqliteTestStore.CreateScratch();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging();
            new SqliteDesignTimeServices().ConfigureDesignTimeServices(serviceCollection);
            serviceCollection.AddSingleton <IFileService, FileSystemFileService>();

            var serviceProvider = serviceCollection
                                  .BuildServiceProvider();

            _logger = new TestLogger();
            serviceProvider.GetService <ILoggerFactory>().AddProvider(new TestLoggerProvider(_logger));

            _scaffoldingModelFactory = serviceProvider
                                       .GetService <IScaffoldingModelFactory>() as RelationalScaffoldingModelFactory;
        }
Exemple #9
0
        public SqliteMetadataModelProviderTest()
        {
            _testStore = SqliteTestStore.CreateScratch();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddLogging();
            new SqliteDesignTimeMetadataProviderFactory().AddMetadataProviderServices(serviceCollection);
            serviceCollection.AddSingleton <IFileService, FileSystemFileService>();

            var serviceProvider = serviceCollection
                                  .BuildServiceProvider();

            _logger = new TestLogger();
            serviceProvider.GetService <ILoggerFactory>().AddProvider(new TestLoggerProvider(_logger));

            _metadataModelProvider = serviceProvider
                                     .GetService <IDatabaseMetadataModelProvider>() as SqliteMetadataModelProvider;
        }
        public async void One_to_one()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("OneToOne").AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS Principal ( 
    Id INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE IF NOT EXISTS Dependent (
    Id INT,
    PrincipalId INT NOT NULL UNIQUE,
    PRIMARY KEY (Id),
    FOREIGN KEY (PrincipalId) REFERENCES Principal (Id)
);
");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    Provider         = MetadataModelProvider,
                    ConnectionString = testStore.Connection.ConnectionString,
                    Namespace        = "E2E.Sqlite",
                    OutputPath       = "testout"
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), "ReverseEngineering/Expected/OneToOne")
                {
                    Files =
                    {
                        "ModelContext.expected",
                        "Dependent.expected",
                        "Principal.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = results.Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public override TestStore CreateTestStore(Type testStoreType)
        {
            if (testStoreType == typeof(InMemoryTestStore))
            {
                return(new InMemoryTestStore());
            }

            if (testStoreType == typeof(SqlServerTestStore))
            {
                return(SqlServerTestStore.Create("SharedCrossStore"));
            }

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

            throw new NotImplementedException();
        }
Exemple #12
0
        public void Principal_missing_primary_key()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("NoPrincipalPk" + DbSuffix))
            {
                testStore.ExecuteNonQuery(@"CREATE TABLE IF NOT EXISTS Dependent (
    Id PRIMARY KEY,
    PrincipalId INT,
    FOREIGN KEY (PrincipalId) REFERENCES Principal(Id)
);
CREATE TABLE IF NOT EXISTS Principal ( Id INT);");

                var results = Generator.Generate(
                    testStore.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectPath,
                    outputPath: null,
                    rootNamespace: "E2E.Sqlite",
                    contextName: null,
                    useDataAnnotations: UseDataAnnotations,
                    overwriteFiles: false,
                    useDatabaseNames: false);

                Assert.Contains("warn: " + DesignStrings.MissingPrimaryKey("Principal"), _reporter.Messages);
                Assert.Contains("warn: " + DesignStrings.UnableToGenerateEntityType("Principal"), _reporter.Messages);
                Assert.Contains("warn: " + DesignStrings.ForeignKeyScaffoldErrorPrincipalTableScaffoldingError("Dependent(PrincipalId)", "Principal"), _reporter.Messages);

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "NoPrincipalPk"))
                {
                    Files =
                    {
                        "NoPrincipalPk" + DbSuffix + "Context.cs",
                        "Dependent.cs"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, TestProjectFullPath)
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
    public async Task Create_sets_journal_mode_to_wal(bool async)
    {
        using var testStore = SqliteTestStore.GetOrCreate("Create");
        using var context   = CreateContext(testStore.ConnectionString);
        var creator = context.GetService <IRelationalDatabaseCreator>();

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

        testStore.OpenConnection();
        var journalMode = testStore.ExecuteScalar <string>("PRAGMA journal_mode;");

        Assert.Equal("wal", journalMode);
    }
Exemple #14
0
        public SqliteDatabaseModelFactoryTest()
        {
            _testStore = SqliteTestStore.CreateScratch();

            var serviceCollection = new ServiceCollection().AddLogging();

            new SqliteDesignTimeServices().ConfigureDesignTimeServices(serviceCollection);

            serviceCollection
            .AddSingleton <ILoggingOptions, LoggingOptions>()
            .AddSingleton(typeof(IInterceptingLogger <>), typeof(InterceptingLogger <>));

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var logger = new TestLogger();

            serviceProvider.GetService <ILoggerFactory>().AddProvider(new TestLoggerProvider(logger));

            _factory = serviceProvider
                       .GetService <IDatabaseModelFactory>() as SqliteDatabaseModelFactory;
        }
Exemple #15
0
        public void Self_referencing()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("SelfRef" + DbSuffix))
            {
                testStore.ExecuteNonQuery(@"CREATE TABLE IF NOT EXISTS SelfRef (
    Id INTEGER PRIMARY KEY,
    SelfForeignKey INTEGER,
    FOREIGN KEY (SelfForeignKey) REFERENCES SelfRef (Id)
);");

                var results = Generator.Generate(
                    testStore.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectPath,
                    outputPath: null,
                    rootNamespace: "E2E.Sqlite",
                    contextName: null,
                    useDataAnnotations: UseDataAnnotations,
                    overwriteFiles: false,
                    useDatabaseNames: false);

                Assert.Empty(_reporter.Messages.Where(m => m.StartsWith("warn: ")));

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "SelfRef"))
                {
                    Files =
                    {
                        "SelfRef" + DbSuffix + "Context.cs",
                        "SelfRef.cs"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, TestProjectFullPath)
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public OwnedQuerySqliteFixture()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkSqlite()
                                  .AddSingleton(TestModelSource.GetFactory(OnModelCreating))
                                  .AddSingleton <ILoggerFactory>(TestSqlLoggerFactory)
                                  .BuildServiceProvider(validateScopes: true);

            _testStore = SqliteTestStore.CreateScratch();

            _options = new DbContextOptionsBuilder()
                       .UseSqlite(_testStore.ConnectionString)
                       .UseInternalServiceProvider(serviceProvider)
                       .Options;

            using (var context = new DbContext(_options))
            {
                context.Database.EnsureClean();

                AddTestData(context);
            }
        }
        public async void Self_referencing()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("SelfRef" + DbSuffix).AsTransient())
            {
                testStore.ExecuteNonQuery(@"CREATE TABLE SelfRef (
    Id INTEGER PRIMARY KEY,
    SelfForeignKey INTEGER,
    FOREIGN KEY (SelfForeignKey) REFERENCES SelfRef (Id)
);");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    ConnectionString     = testStore.Connection.ConnectionString,
                    ProjectPath          = "testout",
                    ProjectRootNamespace = "E2E.Sqlite",
                    UseFluentApiOnly     = UseFluentApiOnly,
                    TableSelectionSet    = TableSelectionSet.All
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "SelfRef"))
                {
                    Files =
                    {
                        "SelfRef" + DbSuffix + "Context.expected",
                        "SelfRef.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public async void Self_referencing()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("SelfRef").AsTransient())
            {
                testStore.ExecuteNonQuery(@"CREATE TABLE SelfRef (
    Id INTEGER PRIMARY KEY,
    SelfForeignKey INTEGER,
    FOREIGN KEY (SelfForeignKey) REFERENCES SelfRef (Id)
);");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    Provider         = MetadataModelProvider,
                    ConnectionString = testStore.Connection.ConnectionString,
                    Namespace        = "E2E.Sqlite",
                    OutputPath       = "testout"
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), "ReverseEngineering/Expected/SelfRef")
                {
                    Files =
                    {
                        "ModelContext.expected",
                        "SelfRef.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = results.Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Exemple #19
0
        public void Missing_primary_key()
        {
            using (var testStore = SqliteTestStore.CreateScratch())
            {
                testStore.ExecuteNonQuery("CREATE TABLE Alicia ( Keys TEXT );");

                var results = Generator.Generate(
                    testStore.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectPath,
                    outputPath: null,
                    rootNamespace: "E2E.Sqlite",
                    contextName: null,
                    useDataAnnotations: UseDataAnnotations,
                    overwriteFiles: false,
                    useDatabaseNames: false);

                var errorMessage = DesignStrings.UnableToGenerateEntityType("Alicia");
                Assert.Contains("warn: " + DesignStrings.MissingPrimaryKey("Alicia"), _reporter.Messages);
                Assert.Contains("warn: " + errorMessage, _reporter.Messages);
                Assert.Contains(errorMessage, InMemoryFiles.RetrieveFileContents(TestProjectFullPath, Path.GetFileName(results.ContextFile)));
            }
        }
Exemple #20
0
 public static SqliteTestStore GetSharedStore() => SqliteTestStore.GetOrCreateShared("northwind", () => { });
 public override TestStore GetOrCreate(string storeName)
 => SqliteTestStore.GetExisting("northwind");
 public SqliteDatabaseModelFactoryTest()
 {
     _testStore = SqliteTestStore.CreateScratch();
     _factory   = new SqliteDatabaseModelFactory();
 }
Exemple #23
0
 public override TestStore GetOrCreate(string storeName)
 => SqliteTestStore.GetOrCreate(storeName, sharedCache: false);