Ejemplo n.º 1
0
        /// <summary>
        /// Initiate NHibernate Manager
        /// </summary>
        /// <param name="connect">NHibernate dialect, driver and connection string separated by ';'</param>
        /// <param name="store">Name of the store</param>
        public NHibernateManager(string connect, string store)
        {
            try
            {
                ParseConnectionString(connect);

                //To create sql file uncomment code below and write the name of the file
                SchemaExport exp = new SchemaExport(configuration);
                exp.SetOutputFile("db_creation.sql");
                exp.Create(false, true);

                sessionFactory = configuration.BuildSessionFactory();

            }
            catch (MappingException mapE)
            {
                if (mapE.InnerException != null)
                    Console.WriteLine("[NHIBERNATE]: Mapping not valid: {0}, {1}, {2}", mapE.Message, mapE.StackTrace, mapE.InnerException.ToString());
                else
                    m_log.ErrorFormat("[NHIBERNATE]: Mapping not valid: {0}, {1}", mapE.Message, mapE.StackTrace);
            }
            catch (HibernateException hibE)
            {
                Console.WriteLine("[NHIBERNATE]: HibernateException: {0}, {1}", hibE.Message, hibE.StackTrace);
            }
            catch (TypeInitializationException tiE)
            {
                Console.WriteLine("[NHIBERNATE]: TypeInitializationException: {0}, {1}", tiE.Message, tiE.StackTrace);
            }
        }
 private SchemaExport CreateSchemaExport(Configuration config)
 {
     var result = new SchemaExport(config);
     if (!string.IsNullOrEmpty(this.delimiter)) result.SetDelimiter(this.delimiter);
     if (!string.IsNullOrEmpty(this.outputFile)) result.SetOutputFile(this.outputFile);
     return result;
 }
Ejemplo n.º 3
0
        /// <summary>Changes the raw NHibernate config.</summary>
        /// <param name="config">The configuration to change.</param>
        public void ChangeRawConfig(Configuration config)
        {
            var schemaExport = new SchemaExport(config);
            var path = string.Empty;
            if (_outputSql)
            {
                path = Path.Combine(Path.GetTempPath(), "NHibernate SQL");
                Directory.CreateDirectory(path);
                schemaExport.SetOutputFile(Path.Combine(path, "drop.sql"));
            }

            schemaExport.Drop(false, true);
            if (_outputSql)
                schemaExport.SetOutputFile(Path.Combine(path, "create.sql"));
            schemaExport.Create(false, true);
        }
Ejemplo n.º 4
0
 static void CreateSchema()
 {
     SchemaExport export = new SchemaExport(m_NHConfiguration);
     export.SetDelimiter(";");
     export.SetOutputFile(@"db.sql").Execute(false, false, false);
     Console.WriteLine("Schema Exported");
 }
Ejemplo n.º 5
0
        private void btnGenerateDBScript_Click(object sender, RoutedEventArgs e)
        {
            Assembly assembly = Assembly.LoadFrom(txtFileName.Text);

            IPersistenceConfigurer databaseConfig = null;
            string fileName = "Domain Database Script - {0}.sql";

            if (rdbSqlServer.IsChecked != null)
                if (rdbSqlServer.IsChecked.Value)
                {
                    databaseConfig = MsSqlConfiguration.MsSql2005;
                    fileName = string.Format(fileName, "Sql Server 2005");
                }
                else if (rdbOracle.IsChecked != null)
                    if (rdbOracle.IsChecked.Value)
                    {
                        databaseConfig = OracleDataClientConfiguration.Oracle9;
                        fileName = string.Format(fileName, "Oracle 9g");
                    }

            Fluently.Configure()
                .Mappings(m => m.FluentMappings.AddFromAssembly(assembly))
                .Database(databaseConfig)//.ConnectionString("Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                .ExposeConfiguration(config =>
                {
                    SchemaExport se = new SchemaExport(config);
                    se.SetOutputFile(fileName);
                    se.Create(false, false);
                    MessageBox.Show(string.Format("Script successful created! See the '{0}' file.", fileName));
                }).BuildConfiguration();
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Generate the database schema, apply it to the database and save the DDL used into a file.
 /// </summary>
 public static void CreateDatabase()
 {
     Configuration configuration = new Configuration();
     configuration.Configure();
     SchemaExport schemaExport = new SchemaExport(configuration);
     schemaExport.SetOutputFile("SQLite database schema.ddl");
     schemaExport.Create(true, true);
 }
Ejemplo n.º 7
0
 public void CreateSchema()
 {
     var nhConfig = new ConfigurationBuilder().Build();
     var schemaExport = new SchemaExport(nhConfig);
     schemaExport
         .SetOutputFile(@"db.sql")
         .Execute(false, false, false);
 }
        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);
        }
Ejemplo n.º 9
0
 public static void createDatabase()
 {
     var nhconfig = new Configuration().Configure();
     var sessionFactory = nhconfig.BuildSessionFactory();
     var schemaExport = new SchemaExport(nhconfig);
     schemaExport.SetOutputFile(@"concepts.sql")
         .Execute(true, true, false);
     Console.WriteLine("I created your database");
 }
Ejemplo n.º 10
0
 public void TestGenerationOfSchema()
 {
     Configuration configuration = new Configuration();
     configuration.Configure();
     configuration.AddAssembly(typeof(State).Assembly);
     SchemaExport schemaExport = new SchemaExport(configuration);
     schemaExport.SetOutputFile("schema.sql");
     schemaExport.Execute(false, true, false);
 }
Ejemplo n.º 11
0
        public void Create_Database()
        {
            Configuration config = sessionBuilder.GetConfiguration();

            var exporter = new SchemaExport(config);

            exporter.SetOutputFile(@"C:\temp\GroopSchema.ddl");
            exporter.Create(true, false);
        }
Ejemplo n.º 12
0
        private void DropAndRecreateSchema()
        {
            SchemaExport schemaExport = new SchemaExport(this.configuration);

            schemaExport.SetOutputFile(@"..\..\nhibernate-schema.txt");

            schemaExport.Drop(script: false, export: true);
            schemaExport.Create(script: false, export: true);
        }
Ejemplo n.º 13
0
 public static void CreatSchema(string OutputFile, string ConnString)
 {
     FNHMVC.Data.Infrastructure.ConnectionHelper.GetConfiguration(ConnString).ExposeConfiguration(cfg =>
     {
         var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
         if (!string.IsNullOrEmpty(OutputFile)) schemaExport.SetOutputFile(OutputFile);
         schemaExport.Drop(false, true);
         schemaExport.Create(false, true);
     }).BuildConfiguration();
 }
Ejemplo n.º 14
0
 public void Generate()
 {
     var databaseSchemaFileName = GetDatabaseSchemaFileName();
     File.Delete(databaseSchemaFileName);
     var nHibernateConfigurator = GetNhibernateConfigurator();
     var schemaExport = new SchemaExport(nHibernateConfigurator.GetConfiguration());
     schemaExport.SetOutputFile(databaseSchemaFileName);
     schemaExport.Create(true, false);
     if (!File.Exists(databaseSchemaFileName) || new FileInfo(databaseSchemaFileName).Length == 0) throw new Exception("Error generating database schema");
 }
        public void Should_save_schema_to_file()
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Product).Assembly);

            var schemaExport = new SchemaExport(cfg);
            schemaExport.SetOutputFile("../../GeneratedSchema/schema.sql");
            schemaExport.Create(true, true);
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            var nhConfig = new Configuration().Configure();
              var sessionFactory = nhConfig.BuildSessionFactory();

              var schemaExport = new SchemaExport(nhConfig);
              schemaExport
            .SetOutputFile(@"db.sql")
            .Execute(false, false, false);
        }
Ejemplo n.º 17
0
        private static void CreateSchema()
        {
            _log.Debug("Recreating DB...");
            InitializeFramework();

            SchemaExport export = new SchemaExport(_configuration);
            export.SetOutputFile("script.sql");
            export.Drop(true, true);
            export.Create(true, true);
            _log.Debug("Schema created...");
        }
Ejemplo n.º 18
0
        public void TestGenerateScriptFile()
        {
            string filePath = "D:\\NHibernateTest.sql";

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            var export = new SchemaExport(helper.Configuration);
            export.SetOutputFile(filePath).Create(true, false);
            Assert.True(File.Exists(filePath));
        }
Ejemplo n.º 19
0
 private void _createTables() {
     try {
         Configuration _cfg = new Configuration().Configure();
         SchemaExport export = new SchemaExport(_cfg);
         export.SetOutputFile("./db/create_tables.sql");
         export.Drop(true, true);
         export.Create(true, true);
     } catch (Exception e)
     {
         _log.Error("创建数据库语句发生异常。 {0}", e.StackTrace);
     }
 }
Ejemplo n.º 20
0
 public static void CreatSchema(string OutputFile, string ConnString)
 {
     FNHMVC.Data.Infrastructure.ConnectionHelper.GetConfiguration(ConnString).ExposeConfiguration(cfg =>
     {
         var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
         if (!string.IsNullOrEmpty(OutputFile))
         {
             schemaExport.SetOutputFile(OutputFile);
         }
         schemaExport.Drop(false, true);
         schemaExport.Create(false, true);
     }).BuildConfiguration();
 }
Ejemplo n.º 21
0
        public void Execute(QueryExecutor queryExecutor, string connectionString)
        {
            cfg.Properties[Environment.ConnectionString] = connectionString;

            var exporter = new SchemaExport(cfg)
                .SetDelimiter(delimiter);

            if (!string.IsNullOrEmpty(outputFile)) {
                exporter.SetOutputFile(outputFile);
            }

            exporter.Execute(script: false, export: true, justDrop: false);
        }
Ejemplo n.º 22
0
        public void DropAndRecreateSchema()
        {
            var config = ServiceLocator.Current.GetInstance<NHibernate.Cfg.Configuration>();

            var zephyrConfig = ServiceLocator.Current.GetInstance<ZephyrConfiguration>();

            var schemaExport = new SchemaExport(config);
            if (zephyrConfig.PersistenceConfig.DbSchemaExportEnabled)
            {
                var path = zephyrConfig.PersistenceConfig.DbSchemaExportPath;
                schemaExport.SetOutputFile(path + "/schema_" + DateTime.Now.ToString("yyyy-MM-dd_HH mm ss") + ".sql");
            }                
            schemaExport.Execute(true, false, false);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            var cfg = new Configuration()
                .DataBaseIntegration(db =>
                {
                    db.ConnectionString = "";
                    db.Dialect<MySQLDialect>();
                });

            /* Add the mapping we defined: */
            var mapper = new ModelMapper();
            mapper.AddMapping(typeof(Nuclear.EventSourcing.MySql.RecordedEventMap));

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            cfg.AddMapping(mapping);

            string outfile = System.Environment.CurrentDirectory + "\\Nuclear.EventSourcing.Schema.mysql";

            Console.WriteLine(outfile);

            StringBuilder data = new StringBuilder();

            SchemaExport schema = new SchemaExport(cfg);

            schema.SetOutputFile(outfile)
                .Create((a) =>
                {
                    data.AppendLine(a);
                }, false);

            System.IO.File.WriteAllText(outfile, data.ToString());

            schema.SetOutputFile(outfile).Create(false, false);
            // schema.Create(true, false);

            Console.ReadKey();
        }
Ejemplo n.º 24
0
        public void ExportToFileUsingSetOutputFileAndCreate()
        {
            var configuration = TestConfigurationHelper.GetDefaultConfiguration();

            configuration.AddResource("NHibernate.Test.Tools.hbm2ddl.SchemaMetadataUpdaterTest.HeavyEntity.hbm.xml",
                                                                GetType().Assembly);
            
            var outputFileName = Path.GetTempFileName();
            var export = new SchemaExport(configuration);
            export.SetOutputFile(outputFileName);

            export.Create(false, false);

            Assert.IsTrue(File.Exists(outputFileName));
            Assert.IsTrue(new FileInfo(outputFileName).Length > 0);
        }
Ejemplo n.º 25
0
        public static void GenerateDDL()
        {
            try
            {
                SchemaExport sch = new SchemaExport(nHibernateUtil.nhibernateConfiguration);
                string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                sch.SetOutputFile(path + @"\schema.sql");

                sch.Execute(true, true, false, true);
                System.Console.WriteLine("Generare cu success!");
                log.Debug("Creare fisier DDL: " + path + @"\schema.sql");
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
        public static void AddNHibernate(this IServiceCollection serviceCollection,
            string type, string connectionString) {
            var configuration = Fluently.Configure()
                .Database(GetDatabaseConfiguration(type, connectionString))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<AccountMap>());
#if DEBUG
            configuration = configuration.ExposeConfiguration(config => {
                var schemaExport = new SchemaExport(config);
                schemaExport.SetDelimiter(";");
                schemaExport.SetOutputFile("schema.sql").Execute(true, false, false);
            });
#endif

            var factory = configuration.BuildSessionFactory();

            serviceCollection.AddSingleton(factory);
            serviceCollection.AddScoped<IScopeFactory, ScopeFactory>();
        }
Ejemplo n.º 27
0
        public void DropAndRecreateSchema()
        {
            //
            // TODO: Add test logic here
            //
            NHibernateSession.Initialize(null);

            var config = NHibernateSession.Configuration;
            var zephyrConfig = new ZephyrConfig();

            var schemaExport = new SchemaExport(config);
            if (zephyrConfig.ExportDbSchema)
            {
                var path = zephyrConfig.DataConfig.DbSchemaExportPath;
                schemaExport.SetOutputFile(path + "/schema_" + DateTime.Now.ToString("yyyy-MM-dd_HH mm ss") + ".sql");
            }
            schemaExport.Execute(true, true, false);
        }
        public void RecreateDatabase()
        {
            var configuration = new ConfigurationFactory().CreateConfiguration();
            var schemaExport = new SchemaExport(configuration);

            // The current dir is the bin/Debug folder so we back out of there.
            schemaExport.SetOutputFile(@"..\..\..\database\create_schema.sql");
            schemaExport.Execute(true, true, false);

            // We expect two generator tables - the default one used by most of the model classes,
            // and the one with all params specified that uses a custom table and column.

            var sessionFactory = configuration.BuildSessionFactory();

            // Check default generator table
            VerifyGeneratorTable(sessionFactory, "hibernate_unique_key", "next_id", 1);
            // Check params generator table
            VerifyGeneratorTable(sessionFactory, "HibernateUniqueKey", "NextId", 1);
        }
Ejemplo n.º 29
0
        public void OutputSchemaTest()
        {
            var se = new SchemaExport(_configuration);
            se.SetOutputFile("Output.txt");
            se.Execute(true, true, true);
            se.Execute(true, true, false);

            var sf = this._configuration.BuildSessionFactory();
            using (var ses = sf.OpenSession())
            {
                using (var itx = ses.BeginTransaction())
                {
                    ses.Save(new Config() {RevCount = 3});
                    ses.Save(new Role() {RoleName = "UserRole"});
                    ses.Save(new Role() { RoleName = "ReviewerRole" });
                    ses.Save(new Role() { RoleName = "AdminRole" });
                    itx.Commit();
                }
            }
        }
        public void CreateDatabase(SchemaDefinition definition)
        {
            CheckDefinitionIsValid(definition);

            var schemaExport = new SchemaExport(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);
                schemaExport = schemaExport.SetOutputFile(filename);
            }

            if (definition.Session == null)
            {
                schemaExport.Execute(definition.ShowSql, true, false);
            }
            else
            {
                schemaExport.Execute(definition.ShowSql, true, false, definition.Session.Connection, null);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Exports the object model to the database schema
        /// </summary>
        /// <param name="updateDatabase">If true the schema is committed to the database</param>
        /// <param name="saveScript">If true saves the update script to a file</param>
        /// <param name="scriptFile">Path of the file to save the script to</param>
        /// <returns>true if export succeeded</returns>
        public static bool ExportObjectModel(bool updateDatabase, bool saveScript, string scriptFile = null)
        {
            _logger.Debug("ExportObjectModel(updateDatabase:{0}, saveScript:{1}, scriptFile:{2})", updateDatabase, saveScript, scriptFile);

            if (!updateDatabase && !saveScript)
            {
                _logger.Error("ExportObjectModel() requires either updateDatabase or saveScript to be true");
                return false;
            }
            else if (updateDatabase && !Configuration.Database.AllowSchemaUpdate)
            {
                _logger.Error("Update of database schema is prevented by configuration (Configuration.Database.AllowSchemaUpdate=false)");
                return false;
            }

            try
            {
                // Load NHibernate configuration
                FluentConfiguration config = Fluently.Configure()
                    .Database(Configuration.Database.NHibernateConfiguration())
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<BaseMapping<Object>>());

                // Setup SchemaExport
                var export = new SchemaExport(config.BuildConfiguration());
                if (!String.IsNullOrEmpty(scriptFile))
                {
                    export.SetOutputFile(scriptFile);
                }

                // Execute
                export.Execute(saveScript, updateDatabase, false);
                _logger.Debug("ExportObjectModel succeeded");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error("ExportObjectModel failed", ex);
                return false;
            }
        }
Ejemplo n.º 32
0
 public void CreateSchema(Configuration configuration, string filenameTarget)
 {
     var schemaExport = new SchemaExport(configuration);
     schemaExport.SetOutputFile(filenameTarget);
     schemaExport.Create(false, true);
 }