Beispiel #1
0
        public void CreateDb()
        {
            var cfg    = DbService.Configure();
            var schema = new SchemaExport(cfg);

            schema.Create(false, false);
            schema.Drop(false, true);
            schema.Create(false, true);
        }
Beispiel #2
0
        protected override void CreateSchema()
        {
            var script = new StringBuilder();

            SchemaExport.Create(sl => script.Append(sl), true);
            Assert.That(script.ToString(), Does.Not.Contain("LatestMessage"));
        }
Beispiel #3
0
        public static NhDalFactory Create(string connectionString, bool expose)
        {
            var dbConfig = MsSqlConfiguration.MsSql2012
                           .Dialect <MsSql2012Dialect>()
                           .Driver <SqlClientDriver>()
                           .ConnectionString(connectionString);
            var cfg = Fluently.Configure()
                      .Mappings(_ => _.FluentMappings
                                .Add <AuthorMapping>()
                                .Add <LikeTargetMapping>()
                                .Add <AuthCookieMapping>()
                                .Add <ThemeMapping>()
                                .Add <CommentMapping>())
                      .Database(dbConfig)
                      .ExposeConfiguration(_ =>
            {
                if (expose)
                {
                    var export = new SchemaExport(_);
                    export.Drop(false, true);
                    export.Create(false, true);
                }
            });
            var sessionFactory = cfg.BuildSessionFactory();

            return(new NhDalFactory(sessionFactory));
        }
        /// <summary>
        /// Export generated database schema to DB.
        /// </summary>
        protected void SchemaExport(NHibernate.Cfg.Configuration config, ISessionFactory sessionFactory)
        {
            if (rebuildDB)
            {
                SchemaExport se = new SchemaExport(config);
                se.SetOutputFile(Path.Combine(appPath, sqlExportDumpFile));
                se.Create(true, true);
            }

            if (doInserts)
            {
                // Use sql insertstatements to populate your DB!
                ISession sess = null;
                try
                {
                    // open a session just for populating the db, it will be closed when done....
                    sess = sessionFactory.OpenSession();
                    IDbCommand com = sess.Connection.CreateCommand();
                    com.CommandText = ReadInsertStatementsToStream(insertsFile).ToString();
                    com.ExecuteNonQuery();
                }
                catch (ReadInsertStatementsFromFileToStreamException e) { throw e; }
                catch (Exception e) { throw e; }
                finally { if (sess != null)
                          {
                              sess.Close();
                          }
                }
            }
        }
Beispiel #5
0
        static void Main()
        {
            Console.WriteLine("App started");

            var configuration = new Configuration().Configure();

            configuration.AddAssembly(typeof(Program).Assembly);

            var schemaExport = new SchemaExport(configuration);

            schemaExport.Create(true, true);

            Console.WriteLine();
            Console.WriteLine("Database created");

            using (var sessionFactory = configuration.BuildSessionFactory())
            {
                //var postId = SavePost(sessionFactory);
                //GetPost(sessionFactory, postId);

                InsertData(sessionFactory);

                //// Enable profiling
                //XmlConfigurator.Configure();
                NHibernateProfiler.Initialize();

                RunQueries(sessionFactory);
            }

            Console.WriteLine();
            Console.WriteLine("Press any key to quit the application");
            Console.ReadLine();
        }
Beispiel #6
0
        private static void build_schema(Configuration cfg)
        {
            SchemaExport s = new SchemaExport(cfg);

            s.SetOutputFile(Path.Combine(PATH_TO_SCRIPTS, Path.Combine("Up", NAME_OF_SCRIPT)));
            s.Create(true, false);
        }
        public static void BuildSchema(NHibernate.Cfg.Configuration config, BuildSchemaType buildSchemaType)
        {
            switch (buildSchemaType)
            {
            case BuildSchemaType.CreateSchema:
            {
                var schemaExport = new SchemaExport(config);
                schemaExport.Create(false, true);
                break;
            }

            case BuildSchemaType.UpdateSchema:
            {
                var schemaUpdate = new SchemaUpdate(config);
                schemaUpdate.Execute(false, true);
                break;
            }

            case BuildSchemaType.DropSchema:
            {
                var schemaExport = new SchemaExport(config);
                schemaExport.Drop(false, true);
                break;
            }
            }
        }
        public void First_we_need_a_schema_to_test()
        {
            var schemaExport = new SchemaExport(_cfg);

            schemaExport.Drop(true, true);
            schemaExport.Create(true, true);
        }
        public void ShouldVerifySameTableTurkish()
        {
            //NH-3063

            // Turkish have unusual casing rules for the letter 'i'. This test verifies that
            // code paths executed by the SchemaValidator correctly handles case insensitive
            // comparisons for this.

            // Just make sure that we have an int property in the mapped class. This is
            // the 'i' we rely on for the test.
            var v = new Version();

            Assert.That(v.Id, Is.TypeOf <int>());

            var cfg = BuildConfiguration(_version1Resource);

            var export = new SchemaExport(cfg);

            export.Create(true, true);
            try
            {
                var validator = new Tool.hbm2ddl.SchemaValidator(cfg);
                validator.Validate();
            }
            finally
            {
                export.Drop(true, true);
            }
        }
        /// <summary>
        ///     Generates the database schema.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        private void GenerateSchema(NHibernate.Cfg.Configuration configuration)
        {
            var schemaExport = new SchemaExport(configuration);

            schemaExport.Drop(false, true);
            schemaExport.Create(true, true);
        }
Beispiel #11
0
        private static void BuildSchema(Configuration configuration)
        {
            var schemaExport = new SchemaExport(configuration);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }
        public static void Configure(string connectionStringKey = null, bool generateTables = false)
        {
            if (string.IsNullOrWhiteSpace(connectionStringKey))
            {
                connectionStringKey = System.Configuration.ConfigurationManager.AppSettings["DefaultConnectionStringKey"] ?? "MySQL";
            }

            var cfg = Fluently.Configure()
                      .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .ConnectionString(c => c.FromConnectionStringWithKey(connectionStringKey))
                                .Driver <MySqlDataDriver>()
                                .Dialect <MySQL57SpatialDialect>())
                      .Mappings(x => x.FluentMappings.AddFromAssemblyOf <MunicipalityMap>())
                      .BuildConfiguration();

            cfg.AddAuxiliaryDatabaseObject(new SpatialAuxiliaryDatabaseObject(cfg));

            if (generateTables)
            {
                var exporter = new SchemaExport(cfg);
                exporter.Drop(false, true);
                exporter.Create(true, true);
            }

            SessionManager.SessionFactory = cfg.BuildSessionFactory();
        }
Beispiel #13
0
        /// <summary>
        /// Creates database schema from scratch.
        /// </summary>
        /// <param name="databaseConfiguration">The database configuration.</param>
        private static void CreateDatabaseSchema(NHibernate.Cfg.Configuration databaseConfiguration)
        {
            var schemaExport = new SchemaExport(databaseConfiguration);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }
Beispiel #14
0
        public static ISessionFactory CreateSessionFactory(IPersistenceConfigurer persistenceConfigurer = null, NHibernateConfigurationConfigurationOptions configurationOptions = NHibernateConfigurationConfigurationOptions.UpdateDB)
        {
            return(Fluently.Configure()
                   .Database(persistenceConfigurer)
                   .Mappings(m => m.FluentMappings.AddFromAssemblyOf <VisitMap>())

                   //.Mappings(m => m.FluentMappings.AddFromAssemblyOf<WayMap>())
                   //.Mappings(m => m.FluentMappings.AddFromAssemblyOf<PeriodMap>())

                   .ExposeConfiguration(cfg =>
            {
                Config = cfg;
                switch (configurationOptions)
                {
                case NHibernateConfigurationConfigurationOptions.RecreateDB:
                    var export = new SchemaExport(cfg);
                    export.Drop(false, true);
                    export.Create(false, true);
                    break;

                case NHibernateConfigurationConfigurationOptions.UpdateDB:
                    new SchemaUpdate(cfg).Execute(false, true);
                    break;

                case NHibernateConfigurationConfigurationOptions.None:
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(configurationOptions), configurationOptions, "unexpected");
                }
            })
                   .BuildSessionFactory());
        }
Beispiel #15
0
        static UnitOfWork()
        {
            // Initialise singleton instance of ISessionFactory, static constructors are only executed once during the
            // application lifetime - the first time the UnitOfWork class is used
            const string databaseName = "TravelBuddy.db";
            var          fluentConfig = Fluently.Configure()
                                        .Database(SQLiteConfiguration.Standard.ConnectionString("Data Source=" + databaseName + ";Version=3").AdoNetBatchSize(1)
                                                  .ShowSql().FormatSql())
                                        .Mappings(m =>
            {
                m.FluentMappings.Add <UserMap>();
                m.FluentMappings.Add <TravelMap>();
                m.FluentMappings.Add <ActivityMap>();
                m.FluentMappings.Add <PreliminaryActivityMap>();
                m.FluentMappings.Add <TravelActivityMap>();
                m.FluentMappings.Add <TravelActivityWithCostMap>();
                m.FluentMappings.Add <TravelItemMap>();
                m.FluentMappings.Add <CurrencyMap>();
            });
            var nhConfiguration = fluentConfig.BuildConfiguration();

            if (!File.Exists(databaseName))
            {
                var schemaExport = new SchemaExport(nhConfiguration);
                schemaExport.Create(false, true);
            }
            _sessionFactory = nhConfiguration.BuildSessionFactory();
        }
        public NHibernate.Cfg.Configuration BuildConfiguration(string connectionString, bool debug = false)
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.SetProperty(Environment.ShowSql, "false");
            //configure NH to use ISet from .NET instead of from Iesi.Collections
            //configuration.SetProperty(Environment.CollectionTypeFactoryClass, typeof (Net4CollectionTypeFactory).AssemblyQualifiedName);

            var builder = Fluently
                          .Configure(configuration)
                          .ProxyFactoryFactory <DefaultProxyFactoryFactory>()
                          .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)
                                    //.ShowSql()
                                    //.FormatSql()
                                    .Dialect <MsSql2008Dialect>()
                                    )
                          .ExposeConfiguration(c =>
            {
                c.SetProperty(Environment.BatchSize, BatchSize.ToString(CultureInfo.InvariantCulture));
                c.SetProperty("hbm2ddl.keywords", "auto-quote");

                if (debug)
                {
                    c.SetProperty(Environment.ShowSql, "true");
                    c.SetProperty(Environment.FormatSql, "true");
                    c.SetProperty("LogSqlInConsole", "true");
                }
                else
                {
                    c.SetProperty(Environment.ShowSql, "false");
                    c.SetProperty(Environment.FormatSql, "false");
                    c.SetProperty("LogSqlInConsole", "false");
                }
                c.SetProperty("nhibernate-logger", typeof(NLogFactory).AssemblyQualifiedName);
            })
                          .Mappings(m =>
            {
                var model = AutoMap.Assemblies(new AppAutomappingCfg(), _assemblies);
                m.AutoMappings.Add(model);
            })
            ;

            if (debug)
            {
                builder = builder.ExposeConfiguration(cfg =>
                {
                    const string schemaPath = @"c:\temp\nh_mappings_export\schema.sql";
                    using (var file = File.Open(schemaPath, FileMode.CreateNew))
                        using (var writer = new StreamWriter(file))
                        {
                            var se = new SchemaExport(cfg);
                            se.Create(writer, false);
                        }
                });
            }
            _config = builder
                      .BuildConfiguration();

            return(_config);
        }
Beispiel #17
0
        private void BuildSchema()
        {
            var cfg          = NHConfigurator.Configuration;
            var schemaExport = new SchemaExport(cfg);

            schemaExport.Create(false, true);
        }
Beispiel #18
0
        /// <summary>
        /// Generate the database schema, apply it to the database and save the DDL used into a file.
        /// </summary>
        /// <param name="schemaOutputFileName"></param>
        public void CreateDatabaseTables(string schemaOutputFileName = null)
        {
            SchemaExport schemaExport = new SchemaExport(configuration);

            schemaExport.SetOutputFile(string.IsNullOrWhiteSpace(schemaOutputFileName) ? "Create database schema.ddl" : schemaOutputFileName);
            schemaExport.Create(true, true);
        }
Beispiel #19
0
        private static void CreateSchema(Configuration cfg)
        {
            var schemaExport = new SchemaExport(cfg);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }
Beispiel #20
0
        private static void BuildSchema()
        {
            var cfg          = SessionFactoryProvider.Configuration;
            var schemaExport = new SchemaExport(cfg);

            schemaExport.Create(false, true);
        }
Beispiel #21
0
        public void Initialize()
        {
            var schema = new SchemaExport(NHConfig.Configuration);

            schema.Drop(false, true);
            schema.Create(false, true);
        }
Beispiel #22
0
        private static void CreateDatabase()
        {
            var cfg    = DbService.Configure();
            var export = new SchemaExport(cfg);

            export.Create(true, true);
        }
Beispiel #23
0
    protected void CreateSchema_Click(object sender, EventArgs e)
    {
        SchemaExport export = new SchemaExport(ExampleApplication.Configuration);

        export.Create(false, true);

        ISession session = ExampleApplication.SessionFactory.GetCurrentSession();

        session.BeginTransaction();
        Item item1 = new Item();

        item1.Description = "First item";
        item1.Price       = 100m;
        session.Save(item1);

        Item item2 = new Item();

        item2.Description = "Second item";
        item2.Price       = 150m;
        session.Save(item2);

        session.Transaction.Commit();

        Status.Text = "Schema created";
    }
Beispiel #24
0
        public void SchemaExport_Export_CreatesExportScript()
        {
            Configuration configuration = GetConfiguration();
            SchemaExport  export        = new SchemaExport(configuration);
            TextWriter    tw            = new StringWriter();

            export.Create(tw, false);
            string s = tw.ToString();

            var dialect = Dialect.Dialect.GetDialect(configuration.Properties);

            if (dialect.SupportsIfExistsBeforeTableName)
            {
                Assert.IsTrue(s.Contains("drop table if exists Home_Drop"));
                Assert.IsTrue(s.Contains("drop table if exists Home_All"));
            }
            else
            {
                Assert.IsTrue(s.Contains("drop table Home_Drop"));
                Assert.IsTrue(s.Contains("drop table Home_All"));
            }

            Assert.IsTrue(s.Contains("create table Home_All"));
            Assert.IsTrue(s.Contains("create table Home_Export"));
        }
        private static ISessionFactory BuildTestSessionFactory()
        {
            var testDatabaseConnectionString = "LocalDB";
            var config = DatabaseConfiguration.Configure(testDatabaseConnectionString);

            /*
             * Need to comment these out when not needed because session factory can only be created once.
             * Database schemas need to be created BEFORE NHibernate schema export.
             * This needs to be run only once.
             */
            /*
             * var fac = DatabaseConfiguration.BuildSessionFactory(config);
             *
             * CreateSchemas(fac);*/

            // Drop old database if any, create new schema
            config.ExposeConfiguration(cfg => {
                var export = new SchemaExport(cfg);
                //export.SetOutputFile(@"C:\Temp\vdb.sql");
                export.Drop(false, true);
                export.Create(false, true);
            });

            var fac = DatabaseConfiguration.BuildSessionFactory(config);

            FinishDatabaseConfig(fac);

            return(fac);
        }
        /// <summary>
        /// Builds the database schema.
        /// </summary>
        public void BuildSchema()
        {
            // Build the schema.
            var createSchemaSql = new StringWriter();
            var schemaExport    = new SchemaExport(this._configuration);

            // Drop the existing schema.
            schemaExport.Drop(true, true);

            // Print the Sql that will be used to build the schema.
            schemaExport.Create(createSchemaSql, false);
            Debug.Print(createSchemaSql.ToString());

            // Create the schema.
            schemaExport.Create(false, true);
        }
        private static void CreateDataBase(Configuration cfg)
        {
            var schema = new SchemaExport(cfg);

            //schema.Drop(true, true);
            schema.Create(true, true);
        }
        //Cria um novo schema
        public static void CreateSchema(bool execute = false)
        {
            var cfg    = GetFluentConfiguration().BuildConfiguration();
            var schema = new SchemaExport(cfg);

            schema.Create(true, true);
        }
        private void generate_the_schema(Configuration cfg)
        {
            var s = new SchemaExport(cfg);

            s.SetOutputFile(Path.Combine(path_to_sql_scripts_up_folder, name_of_script_to_create));
            s.Create(true, false);
        }
Beispiel #30
0
        static UnitOfWork()
        {
            var basePath = $"{Directory.GetCurrentDirectory()}/../Hotel.Api";

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(basePath)
                                .AddJsonFile("appsettings.json")
                                .Build();

            var connectionString = configuration.GetConnectionString("DefaultConnection");

            var entities = GetAssemblyByName("Hotel.Persistence");

            var fluentConfiguration = Fluently.Configure()
                                      .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString).ShowSql())
                                      .Mappings(m => m.FluentMappings.AddFromAssembly(entities))
                                      .BuildConfiguration();

            var exporter = new SchemaExport(fluentConfiguration);

            exporter.Create(false, true);

            _sessionFactory = fluentConfiguration.BuildSessionFactory();

            Seeds();
        }