chucknorris/roundhouse

Enhancement: Support SQLite database migrations

ferventcoder opened this issue · 4 comments

Enhancement: Support SQLite database migrations

Good old System.Data.SQLite.dll doesn't ILMerge. boo.

Wow, now that is some crazy code right there... lol

        public void enable_loading_from_merged_assembly()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => load_sqlite_data_assembly(e.Name);
        }
        private Assembly load_sqlite_data_assembly(string assembly_name)
        {
            if (assembly_name.to_lower().StartsWith("system.data.sqlite"))
            {
                string resources_path = Path.Combine(output_path, "resources");
                string sqlite_file = Path.Combine(resources_path, "System.Data.SQLite.dll");
                FileInfo sqlite_dll = new FileInfo(sqlite_file);
                Log.bound_to(this).log_a_debug_event_containing("Loading System.Data.SQLite.dll from '{0}'. If it doesn't exist then it will be created from '{1}'.", sqlite_file, ApplicationParameters.sqlite_dll_resource);

                if (!sqlite_dll.Exists)
                {
                    if (!Directory.Exists(resources_path)) Directory.CreateDirectory(resources_path);

                    Assembly executing_assembly = Assembly.GetExecutingAssembly();

                    using (FileStream fs = sqlite_dll.OpenWrite())
                    using (Stream resource_stream = executing_assembly.GetManifestResourceStream(ApplicationParameters.sqlite_dll_resource))
                    {
                        const int size = 4096;
                        byte[] bytes = new byte[size];
                        int number_of_bytes;
                        while ((number_of_bytes = resource_stream.Read(bytes, 0, size)) > 0)
                        {
                            fs.Write(bytes, 0, number_of_bytes);
                        }
                        fs.Flush();
                        fs.Close();
                        resource_stream.Close();
                    }
                }


                return Assembly.LoadFrom(sqlite_file);
            }

            return null;
        }