In C # / nHibernate projects, I use SQLite to unit test my code using the method described here: http://ayende.com/blog/3983/nhibernate-unit-testing .
However, I found that creating and setting up a database in memory usually takes about 150 ms. I have a lot of unit test, so it adds up quickly.
I want to create and configure a database once, save it in a static variable and copy it every time a unit test needs a database.
How to back up a database in memory?
At first I tried to create a named database in memory. According to https://www.sqlite.org/inmemorydb.html this is possible. I used to have:
private const string ConnectionString = "Data Source=:memory:;Version=3;";
Connecting lines I tried:
private const string ConnectionString = "FullUri=file:memorydb.db?mode=memory&cache=shared"; private const string ConnectionString2 = "FullUri=file:memorydb2.db?mode=memory&cache=shared";
So now I just need to figure out how to quickly copy content from one to another? I am almost there: I can create two databases in memory and call "BackupDatabase" to copy the database.
However, unit test behaves like an instance database, has no tables, not even a prototype database.
private static ISessionFactory _prototypeSessionFactory; private const string InstanceConnectionString = "FullUri=file:memorydb.db?mode=memory&cache=shared"; private const string PrototypeConnectionString = "FullUri=file:memorydb2.db?mode=memory&cache=shared"; private SQLiteConnection _instanceConnection; private ISessionFactory _instanceSessionFactory; public DatabaseScope(Assembly assembly) { var prototyeConfiguration = SQLiteConfiguration.Standard.ConnectionString(PrototypeConnectionString); var cfg = Fluently .Configure() .Database(prototyeConfiguration) .Mappings(m => m.HbmMappings.AddFromAssembly(assembly)); cfg.ExposeConfiguration(BuildSchema); _prototypeSessionFactory = cfg.BuildSessionFactory(); var instanceConfiguration = SQLiteConfiguration.Standard.ConnectionString(InstanceConnectionString); _instanceSessionFactory = Fluently .Configure() .Database(instanceConfiguration) .BuildSessionFactory(); CopyDatabase(); } private void CopyDatabase() { var cnnIn = new SQLiteConnection(PrototypeConnectionString); var cnnOut = new SQLiteConnection(InstanceConnectionString); cnnIn.Open(); cnnOut.Open(); cnnIn.BackupDatabase(cnnOut, "main", "main", -1, null, -1); cnnIn.Close(); cnnOut.Close(); }