Пример #1
1
        public static void Initialize(TestContext context)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x => {
                x.ConnectionString = "Server=localhost;Database=test;Uid=root;Pwd=kmn23po;";
                x.Driver<MySqlDataDriver>();
                x.Dialect<MySQLDialect>();
                x.LogSqlInConsole = true;
                x.BatchSize = 30;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<ParentMap>();
            mapper.AddMapping<ParentWithGuidMap>();
            mapper.AddMapping<ChildMap>();

            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            sessionFactory = cfg.BuildSessionFactory();

            var schemaUpdate = new SchemaUpdate(cfg);
            schemaUpdate.Execute(false, true);

            InsertData();
        }
Пример #2
0
 public void TryAlterDbSchema()
 {
     var config = ServiceLocator.Current.GetInstance<NHibernate.Cfg.Configuration>();            
     
     var schemaUpdate = new SchemaUpdate(config);            
     schemaUpdate.Execute(true, true);
 }        
        protected override void Init()
        {
            var config = ConfigureNHibernate();

            var schemaExport = new SchemaUpdate(config);
            schemaExport.Execute(false, true);

            //var schemaCreator = new SchemaExport(config);
            //schemaCreator.Drop(false, true);
            //schemaCreator.Create(false, true);

            Kernel.Register(
                Component.For<ISessionFactory>().LifeStyle.Singleton
                    .UsingFactoryMethod(config.BuildSessionFactory));

            Kernel.Register(Component.For<ISession>().Named("PerThreadSession")
                                 .LifeStyle
                                 .PerThread
                                 .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
                                 .OnCreate((kernel, session) => { session.FlushMode = FlushMode.Commit; }));

            Kernel.Register(Component.For<ISession>().Named("PerWebRequestSession")
                                .LifeStyle
                                .PerWebRequest
                                .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
                                .OnCreate((kernel, session) => { session.FlushMode = FlushMode.Commit; }));
        }
Пример #4
0
 public BaseTest()
 {
     _configuration = SessionFactory.GetConfiguration();
     SchemaUpdate su = new SchemaUpdate(_configuration);
     //se.Execute(false, false, true);
     su.Execute(true, true);
 }
        public void UpdateExistingDatabase(SchemaDefinition definition)
        {
            CheckDefinitionIsValid(definition);

            var schemaUpdate = new SchemaUpdate(definition.Configuration);
            if (definition.FileDefinition != null && !string.IsNullOrWhiteSpace(definition.FileDefinition.FileName))
            {
                //output the sql to create the db to a file.
                string filename = Path.Combine(string.IsNullOrWhiteSpace(definition.FileDefinition.OutputFolder) ? "" : definition.FileDefinition.OutputFolder, definition.FileDefinition.FileName);

                Action<string> updateExport = x =>
                {
                    using (var file = new FileStream(filename, FileMode.Append, FileAccess.Write))
                    using (var sw = new StreamWriter(file))
                    {
                        sw.Write(x);
                        sw.Close();
                    }
                };

                schemaUpdate.Execute(updateExport, true);
            }
            else
            {
                schemaUpdate.Execute(false, true);
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            //var assemblyNames = ConfigurationManager.AppSettings["nhibernate.assemblies"];

            //if (assemblyNames.IsNullOrEmpty())
            //    throw new ConfigurationErrorsException("value required for nhibernate.assemblies, comma seperated list of assemblies");

            //var config = new NHibernate.Cfg.Configuration();
            //config.Configure();

            //foreach (MappingAssembly assembly in TitanConfiguration.Instance.MappingAssemblies)
            //    config.AddAssembly(assembly.Name);

            TitanFramework.Data.NHib.NHibernateHelper.InitialIze();

            var config = TitanFramework.Data.NHib.NHibernateHelper.Configuration;

            var rebuildDatabase = ConfigurationManager.AppSettings["nhibernate.rebuilddatabase"];
            if (TitanFramework.Extensions.StringExtensions.IsNullOrEmpty(rebuildDatabase))
                throw new ConfigurationErrorsException("value required for nhibernate.assemblies, comma seperated list of assemblies");

            switch (rebuildDatabase.ToLower())
            {
                case "rebuild":
                    var schemaExport = new SchemaExport(config);
                    schemaExport.Drop(false, true);
                    schemaExport.Execute(true, false, false);
                    break;
                case "update":
                    var schemaUpdate = new SchemaUpdate(config);
                    schemaUpdate.Execute(true, true);
                    break;
            }
        }
        private static void CreateSchema(Configuration cfg)
        {
            var schemaExport = new SchemaUpdate(cfg);

            schemaExport.Execute(true, true);

        }
        protected override void OnFixtureSetup()
        {
            Configuration configuration = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard
                              .ConnectionString(connstr =>
                                                connstr.Is("Data Source=:memory:;Version=3;New=True;"))
                              .Dialect<SQLiteDialect>()
                              .Driver<SQLite20Driver>()
                              .Provider<TestConnectionProvider>()
                              .ShowSql())
                .CurrentSessionContext("thread_static")
                .ProxyFactoryFactory<ProxyFactoryFactory>()
                .Mappings(m =>
                          m.AutoMappings
                              .Add(
                                  AutoMap.Assembly(
                                      Assembly.Load("Blog.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"))
                                      .Where(c => c.BaseType == typeof (Entity) || c.BaseType == typeof (StampedEntity))
                                      .Conventions
                                      .Add<CustomCollectionConvetion>()
                                      .Conventions
                                      .Add<CascadeAll>()
                                      .Conventions.Add<HiLoIndetityStrategy>()
                                      .Conventions.Add<TableNamePluralizeConvention>()
                                      .Conventions.Add<CustomForeignKeyConvention>()))
                                      
                .ExposeConfiguration(ConfigValidator)
                .BuildConfiguration();

            var schema = new SchemaUpdate(configuration);
            schema.Execute(true, true);

            SessionFactory = configuration.BuildSessionFactory();
        }
Пример #9
0
        static void Main(string[] args)
        {
            List<SongInfo> songProperties =  FileReader.GetProperties("music.txt");

            FluentConfiguration config = Fluently
                 .Configure()
                 .Database(MsSqlConfiguration
                               .MsSql2008
                               .ConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=Songs;Integrated Security=True;Pooling=False"))
                               .Mappings(configuration => configuration
                               .FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                              ;

            var export = new SchemaUpdate(config.BuildConfiguration());
            export.Execute(true, true);

            ISessionFactory sessionFactory = config.BuildSessionFactory();

            using (ISession session = sessionFactory.OpenSession())
            {
                var tracks = session.QueryOver<ArtistInfo>().List();

                foreach (var track in tracks)
                {
                    Console.WriteLine(track);
                    Console.WriteLine("=====");

                }

            }
        }
 private static void BuildSchema(Configuration config)
 {
     // This NHibernate tool takes a configuration (with mapping info in)
     // and exports a database schema from it.
     var dbSchemaExport = new SchemaUpdate(config);
     //dbSchemaExport.Drop(false, true);
     dbSchemaExport.Execute(false, true);
 }
Пример #11
0
 public static void UpdateSchema(string ConnString)
 {
     FNHMVC.Data.Infrastructure.ConnectionHelper.GetConfiguration(ConnString).ExposeConfiguration(cfg =>
     {
         var schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
         schemaUpdate.Execute(false, true);
     }).BuildConfiguration();
 }
        private static void TreatConfiguration(NHibernate.Cfg.Configuration configuration)
        {
            var update = new SchemaUpdate(configuration);
            update.Execute(false, true);
            //            configuration.SetProperty("current_session_context_class", "web");


        }
Пример #13
0
 public static void UpdateSchema(string ConnString)
 {
     FNHMVC.Data.Infrastructure.ConnectionHelper.GetConfiguration(ConnString).ExposeConfiguration(cfg =>
     {
         var schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
         schemaUpdate.Execute(false, true);
     }).BuildConfiguration();
 }
 public void Update_an_existing_database_schema()
 {
     _cfg = new Configuration();
     _cfg.Configure();
     _cfg.AddAssembly(Assembly.LoadFrom("DataLayer.dll"));
     var update = new SchemaUpdate(_cfg);
     update.Execute(true, false);
 }
Пример #15
0
        /// <summary>
        /// Creates/Updates the database schema.
        /// </summary>        
        private void BuildSchema()
        {
            // Build the schema.
            var schemaUpdate = new SchemaUpdate(_configuration);

            // Create/Update the schema.
            schemaUpdate.Execute(false, true);
        }
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            if (_configuration != null)
            {
                return(_configuration);
            }

            var cfg = new NHibernate.Cfg.Configuration();

            {
                cfg.Configure(@"OrmNhib/NHibernateConfig/hibernate.cfg.xml");

                foreach (var mapping in cfg.ClassMappings)
                {
                    string x = $"(1) {mapping.ClassName}, (2) {mapping.Discriminator}, (3) {mapping.DiscriminatorValue}, (4) {mapping.IsDiscriminatorValueNotNull}";
                    System.Diagnostics.Debug.WriteLine(x);
                }

                var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
                schemaExport.SetOutputFile(@"db.Postgre.sql").Execute(
                    useStdOut: true, execute: true, justDrop: false);

                // Alternately, we can use SchemaUpdate.Execute, as in done in 1P
                NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
                schemaUpdate.Execute(useStdOut: true, doUpdate: true);

                try
                {
                    SchemaValidator schemaValidator = new SchemaValidator(cfg);
                    schemaValidator.Validate();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Exception: {ex}");
                }


                // Note
                // SchemaUpdate.Execute is way cooler than SchemaExport.Filename.Execute
                // When I added a new property in Movie.hbm.xml (and in the .cs), SchemaUpdate automatically created statement
                // to tell the diff in schema, and only this got executed:

                /*
                 *  alter table Movie
                 *      add column NewProp VARCHAR(255)
                 *
                 * */
                //
                // However, it does not work as expected all the times, for eg,
                // if I rename a column in HBM, it just adds a new column with new name
                // if I change the sql-type from VARCHAR(255) to VARCHAR(100), nothing is executed and the column type remains unchanged
                // So we will need manual scripts for migration
                //
            }

            _configuration = cfg;
            return(_configuration);
        }
Пример #17
0
		public void SchemaUpdateAddsIndexesThatWerentPresentYet()
		{
			Configuration cfg = TestConfigurationHelper.GetDefaultConfiguration();
			cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1593.TestIndex.hbm.xml", GetType().Assembly);
			var su = new SchemaUpdate(cfg);
			var sb = new StringBuilder(500);
			su.Execute(x => sb.AppendLine(x), false);
			Assert.That(sb.ToString(), Is.StringContaining("create index test_index_name on TestIndex (Name)"));
		}
Пример #18
0
        private static void UpdateSchema()
        {
            _log.Debug("Updating DB...");
            InitializeFramework();

            SchemaUpdate update = new SchemaUpdate(_configuration);
            update.Execute(false, true);
            _log.Debug("Schema updated...");
        }
        public void CreateSchema()
        {
            DeleteDatabaseIfExists();

            var schemaUpdate = new SchemaUpdate(NHibernateHelper.Configuration);
            schemaUpdate.Execute(false, true);

            _personRepo = new NHibernatePersonRepository();
        }
Пример #20
0
 public override void UpdateSchema()
 {
     var session = this.Session;
     if (session != null)
     {
         var update = new SchemaUpdate(this.CreateSessionFactory(this.DefaultFactoryKey).Item2);
         update.Execute(false, true);
     }
 }
Пример #21
0
        private static void BuildSchema(Configuration config)
        {
            //SchemaExport schema = new SchemaExport(config);
            //schema.Drop(false, true);
            //schema.Create(false, true);

            SchemaUpdate schemaUpdate = new SchemaUpdate(config);
            schemaUpdate.Execute(true, true);
        }
Пример #22
0
 public static void update_schema(Configuration cfg)
 {
     SchemaUpdate s = new SchemaUpdate(cfg);
     StringBuilder sb = new StringBuilder();
     s.Execute(x => sb.Append(x), false);
     string updateScriptFileName = Path.Combine(PATH_TO_SCRIPTS, Path.Combine("up", NAME_OF_UPDATE_SCRIPT));
     if (File.Exists(updateScriptFileName)) { File.Delete(updateScriptFileName); }
     File.WriteAllText(updateScriptFileName, sb.ToString());
 }
		public string Update()
		{
			var schemaExport = new SchemaUpdate(configuration);

			var stringBuilder = new StringBuilder();
			schemaExport.Execute(x => stringBuilder.Append(x), false);

			var script = stringBuilder.ToString();

			return string.IsNullOrWhiteSpace(script) ? null : script;
		}
Пример #24
0
 public SessionWraperFactory(bool updateSchema)
 {
     var cfg = new Configuration();
     cfg.Configure();
     if (updateSchema)
     {
         SchemaUpdate updater = new SchemaUpdate(cfg);
         updater.Execute(true, true);
     }
     sessionFactory = cfg.BuildSessionFactory();
 }
Пример #25
0
		public void SchemaExport_Update_CreatesUpdateScript()
		{
			Configuration configuration = GetConfiguration();
			SchemaUpdate update = new SchemaUpdate(configuration);
			TextWriter tw = new StringWriter();
			update.Execute(tw.WriteLine, false);

			string s = tw.ToString();
			Assert.IsTrue(s.Contains("create table Home_Update"));
			Assert.IsTrue(s.Contains("create table Home_All"));
		}
Пример #26
0
 private static void Initialization(SessionFactoryParameters parameters, Configuration configuration)
 {
     if (parameters.CreateDatabase) {
         var export = new SchemaExport(configuration);
         export.Execute(false/*script*/, true/*export*/, false/*justDrop*/);
     }
     else if (parameters.UpdateSchema) {
         var update = new SchemaUpdate(configuration);
         update.Execute(false/*script*/, true /*doUpdate*/);
     }
 }
        protected virtual void ExportSchemaConfig(Configuration config)
        {
            //config.SetInterceptor(new TrackingInterceptor());
            //config.SetInterceptor(new NhInterceptor());
            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            var update = new SchemaUpdate(config);
            update.Execute(false, true);

            //new SchemaExport(config).Drop(false, true);
            //new SchemaExport(config).Create(false, true);
        }
Пример #28
0
        public static void ApplySchemaChanges()
        {
            Configuration cfg = GetConfiguration();

            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
            //NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            //schema.Create(false, true);
            var update = new SchemaUpdate(cfg);

            update.Execute(true, true);
        }
Пример #29
0
        public static ISessionFactory CreateSessionFactory()
        {
            var config = GetSqliteConfig();

            var sessionFactory = config.BuildSessionFactory();

            // Execute update
            // TODO: Make this optional - check for a flag or something
            var schemaUpdate = new SchemaUpdate(config);
            schemaUpdate.Execute(false, true);

            return sessionFactory;
        }
Пример #30
0
        protected override void Process(global::NHibernate.Cfg.Configuration configuration)
        {
            SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
            bool isUpdated = false;
            schemaUpdate.Execute(script => { Console.WriteLine(script); isUpdated = true; }, true);

            if (!isUpdated)
            {
                return;
            }

            InsertInitialData(configuration);
        }
Пример #31
0
 private static void CreateDbSchema(Configuration configuration) 
 {
    // var schemaExport = new SchemaExport(configuration);
    
     // Non-destructive update mechanism. Updates schema if possible
     // without losing data. Also creates the entire DB if necessary.
     var schemaUpdate = new SchemaUpdate(configuration);
     schemaUpdate.Execute(true, true);
     if (schemaUpdate.Exceptions.Count > 0)
     {
         throw schemaUpdate.Exceptions[0] as Exception;
     }
 }
        protected override void Process(NHibernate.Cfg.Configuration configuration)
        {
            if (environment != Environment.Local)
            {
                return;
            }

            bool showSql = perspective == Perspective.Debug;
            bool doUpdate = perspective == Perspective.Debug;

            SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
            schemaUpdate.Execute(showSql, doUpdate);
        }
Пример #33
0
        public static void UpdateSchema()
        {
            var configuration = new Configuration();

            configuration.Configure();
            configuration.AddAssembly("SkladtradeEntity");

            NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate
                = new NHibernate.Tool.hbm2ddl.SchemaUpdate(configuration);
            schemaUpdate.Execute(true, true);

            foreach (var item in schemaUpdate.Exceptions)
            {
                Console.WriteLine(item.Message + "\n\n" + item.Source + "\n\n" + item.StackTrace + "\n\n");
                if (item.InnerException != null)
                {
                    Console.WriteLine(item.InnerException.Message);
                }
            }
        }