Chris
Chris

Reputation: 28064

NHibernate 3.2: SchemaExport not working with SQLite

I'm using an in-memory db for some quick unit tests, using the following code:

public class MemoryDb
{
    private static Configuration configuration;
    private static ISessionFactory sessionFactory;

    static MemoryDb()
    {
        configuration = new NHibernate.Cfg.Configuration();

        configuration.DataBaseIntegration(x =>
        {
            x.Driver<SQLite20Driver>();
            x.Dialect<SQLiteDialect>();
            x.ConnectionProvider<DriverConnectionProvider>();
            x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            x.IsolationLevel = IsolationLevel.ReadCommitted;
            x.ConnectionString = "Data Source=:memory:;";
            x.Timeout = 255;
            x.BatchSize = 100;
            x.LogFormattedSql = true;
            x.LogSqlInConsole = true;
            x.AutoCommentSql = false;
        });

        configuration.AddMapping(DbHelper.GetAutoMappings());
        sessionFactory = configuration.BuildSessionFactory();
    }

    public static ISession GetSession()
    {
        var session = sessionFactory.OpenSession();
        new SchemaExport(configuration).Execute(true, true, false, session.Connection, null);
        return session;
    }
}

The problem is that the schema export doesn't seem to be working. On of my tests looks like this:

[Fact]
public void ShouldFindDuplicateByEmail()
{
    using (var session = MemoryDb.GetSession())
    {
        var repo = new NHibernateCustomerRepository(session);
        var customer = new Customer();
        customer.EmailAddress = "[email protected]";
        repo.Save(customer);

        var duplicates = repo.FindDuplicates(customer);
        Assert.Equal(1, duplicates.Length);
    }
}

The test fails with the error no such table: Customers. This all worked with Fluent NHibernate and NHibernate 3.1. I know it's not an issue with the mappings themselves, because the actual application works when I run it against an existing SQL Server db. It only fails when running the tests. Any thoughts?

Edit: If I change only the connection string such that it writes to a file (i.e. x.ConnectionString = "data source=" + Path.GetTempFileName();, the whole thing works. I'm guessing either the schema isn't run correctly against the in-memory db, or it's getting a new in-memory db each time I execute a session command, but have no clue how to figure this out.

Upvotes: 2

Views: 1387

Answers (1)

Chris
Chris

Reputation: 28064

I found the answer here: https://forum.hibernate.org/viewtopic.php?p=2397541#p2397541

I had to add the following to the db configuration:

x.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;

Otherwise, NHibernate releases the connection after each statement is flushed, thereby getting rid of the in-memory database with the schema.

Upvotes: 2

Related Questions