Exemplo n.º 1
0
 /// <summary>
 /// Create a schema exporter for the given Configuration, with the given
 /// database connection properties
 /// </summary>
 /// <param name="cfg">The NHibernate Configuration to generate the schema from.</param>
 /// <param name="connectionProperties">The Properties to use when connecting to the Database.</param>
 public SchemaExport(Configuration cfg, IDictionary<string, string> connectionProperties)
 {
     this.connectionProperties = connectionProperties;
     dialect = Dialect.Dialect.GetDialect(connectionProperties);
     dropSQL = cfg.GenerateDropSchemaScript(dialect);
     createSQL = cfg.GenerateSchemaCreationScript(dialect);
 }
Exemplo n.º 2
0
		/// <summary>
		/// Create a schema exporter for the given Configuration, with the given
		/// database connection properties
		/// </summary>
		/// <param name="cfg">The NHibernate Configuration to generate the schema from.</param>
		/// <param name="configProperties">The Properties to use when connecting to the Database.</param>
		public SchemaExport(Configuration cfg, IDictionary<string, string> configProperties)
		{
			this.configProperties = configProperties;
			dialect = Dialect.Dialect.GetDialect(configProperties);
			dropSQL = cfg.GenerateDropSchemaScript(dialect);
			createSQL = cfg.GenerateSchemaCreationScript(dialect);
			formatter = (PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
		}
		public void ConfigurationIsOK()
		{
			Configuration cfg = new Configuration();
			cfg.AddResource("NHibernate.Test.NHSpecificTest.NH251.CustomAccessDO.hbm.xml",
			                Assembly.GetExecutingAssembly());

			ISessionFactoryImplementor factory = (ISessionFactoryImplementor)cfg.BuildSessionFactory();
			cfg.GenerateSchemaCreationScript(factory.Dialect);
		}
Exemplo n.º 4
0
		public void ManyToManyTableCreationScript()
		{
			Configuration cfg = new Configuration();
			Assembly assembly = Assembly.GetExecutingAssembly();
			cfg.AddResource( "NHibernate.Test.NHSpecificTest.NH257.Mappings.hbm.xml", assembly );
			
			string[] script = cfg.GenerateSchemaCreationScript(new Dialect.MsSql2000Dialect());
			string createManyToManyTable = script[1];
			Assert.AreEqual("create table users_in_groups (group_id INT not null, user_id INT not null, primary key (user_id, group_id))",
				createManyToManyTable);
		}
        public void BuildSchema(ISession session, Configuration configuration)
        {
            IDbConnection connection = session.Connection;

            Dialect dialect = Dialect.GetDialect(configuration.Properties);
            string[] drops = configuration.GenerateDropSchemaScript(dialect);
            ExecuteScripts(drops, connection);

            string[] scripts = configuration.GenerateSchemaCreationScript(dialect);
            ExecuteScripts(scripts, connection);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            Configuration cfg = new Configuration();
            
            cfg.Configure();
            
            string[] sqls = cfg.GenerateSchemaCreationScript(new MySQL5Dialect());

            File.WriteAllText("MySQL5SP.sql", string.Join(";\n", sqls));

            Console.WriteLine("OK");
        }
Exemplo n.º 7
0
        private void GenerateSchema(Configuration config)
        {
            logger.WriteLine("------------------------------");
            string[] scripts = config.GenerateSchemaCreationScript(new MsSql2012Dialect());

            foreach (var script in scripts)
            {
                logger.WriteLine(script);
            }

            string schemaPath = Path.Combine(TestUtils.GetBuildDirectory(), "schema.sql");

            File.WriteAllLines(schemaPath, scripts);
        }
Exemplo n.º 8
0
 static LiveSqliteSchema()
 {
     var config = new Configuration();
     config.SetProperty(Environment.Dialect, "NHibernate.Dialect.SQLiteDialect");
     config.AddInputStream(HbmSerializer.Default.Serialize(Assembly.Load("tanzer.lotto.core")));
     Dialect dialect = Dialect.GetDialect(config.Properties);
     // pause at critical moments; row COUNT; rollback journal; isolation level
     // @sa http://www.sqlite.org/pragma.html
     script = "PRAGMA synchronous=FALSE;PRAGMA count_changes=FALSE;PRAGMA journal_mode=FALSE;PRAGMA read_uncommitted=TRUE;";
     script += String.Join(";", config.GenerateDropSchemaScript(dialect));
     script += ";";
     script += String.Join(";", config.GenerateSchemaCreationScript(dialect));
     script += ";";
 }
Exemplo n.º 9
0
        public void Bug()
        {
            Configuration cfg = new Configuration();
            Assembly assembly = Assembly.GetExecutingAssembly();
            cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1594.Mappings.hbm.xml", assembly);

            string[] script = cfg.GenerateSchemaCreationScript(new MsSql2000Dialect());

            bool found = string.Compare(
                        script[0],
                        "create table A (id INT IDENTITY NOT NULL, Foo DECIMAL(4, 2) null, primary key (id))",
                        true) == 0;

            Assert.IsTrue(found, "when using decimal(precision,scale) Script should contain the correct create table statement");
        }
Exemplo n.º 10
0
        /// <summary>
        /// Execute schema creation script, determined by the Configuration object
        /// used for creating the SessionFactory. A replacement for NHibernate's
        /// SchemaExport class, to be invoked on application setup.
        /// </summary>
        /// <remarks>
        /// Fetch the LocalSessionFactoryObject itself rather than the exposed
        /// SessionFactory to be able to invoke this method, e.g. via
        /// <code>LocalSessionFactoryObject lsfo = (LocalSessionFactoryObject) ctx.GetObject("mySessionFactory");</code>.
        /// <p>
        /// Uses the SessionFactory that this bean generates for accessing a ADO.NET
        /// connection to perform the script.
        /// </p>
        /// </remarks>
        public void CreateDatabaseSchema()
        {
            log.Info("Creating database schema for Hibernate SessionFactory");
            HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);

            hibernateTemplate.Execute(
                new HibernateDelegate(delegate(ISession session)
            {
                IDbConnection con = session.Connection;
                Dialect dialect   = Dialect.GetDialect(Configuration.Properties);
                string[] sql      = Configuration.GenerateSchemaCreationScript(dialect);
                ExecuteSchemaScript(con, sql);
                return(null);
            }));
        }
Exemplo n.º 11
0
		public void ForeignKeyNames()
		{
			Configuration cfg = new Configuration();
			Assembly assembly = Assembly.GetExecutingAssembly();
			cfg.AddResource( "NHibernate.DomainModel.MasterDetail.hbm.xml",
				Assembly.GetAssembly( typeof( NHibernate.DomainModel.Master ) )
				);
			

			string script = string.Join( "\n",
					cfg.GenerateSchemaCreationScript( new Dialect.MsSql2000Dialect() ) );

			Assert.IsTrue( script.IndexOf( "add constraint AA" ) >= 0 );
			Assert.IsTrue( script.IndexOf( "add constraint BB" ) >= 0 );
			Assert.IsTrue( script.IndexOf( "add constraint CC" ) >= 0 );
		}
Exemplo n.º 12
0
		public void DuplicateConstraints()
		{
			Configuration cfg = new Configuration();
			cfg.AddResource(GetType().Namespace + ".Mappings.hbm.xml", GetType().Assembly);
			string[] script = cfg.GenerateSchemaCreationScript(new MsSql2000Dialect());

			int constraintCount = 0;
			foreach (string str in script)
			{
				if (str.IndexOf("foreign key (DependentVariableId) references NVariable") >= 0)
				{
					constraintCount++;
				}
			}
			Assert.AreEqual(1, constraintCount);
		}
Exemplo n.º 13
0
		public void TestMapElementElement()
		{
			var cfg = new Configuration().Configure();
			var mapper = new ModelMapper();

			mapper.Class<ClassWithMapElementElement>(c =>
				{
					c.Lazy(false);
					c.Id(id => id.Id, id =>
						{
							id.Generator(Generators.Identity);
						});

					c.Map(m => m.Map, col =>
						{
							col.Table("element_element");
							col.Key(k => k.Column("id"));
						}, key =>
						{
							key.Element(e =>
								{
									e.Column("key");
								});
						}, element =>
						{
							element.Element(e =>
								{
									e.Column("element");
								});
						});
				});

			cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

			var script = cfg.GenerateSchemaCreationScript(new MsSql2012Dialect());

			Assert.False(script.Any(x => x.Contains("idx")));
		}
Exemplo n.º 14
0
		public void ManyToManyTableCreationScript()
		{
			Configuration cfg = new Configuration();
			Assembly assembly = Assembly.GetExecutingAssembly();
			cfg.AddResource("NHibernate.Test.NHSpecificTest.NH257.Mappings.hbm.xml", assembly);

			string[] script = cfg.GenerateSchemaCreationScript(new MsSql2000Dialect());

			bool found = false;

			foreach (string line in script)
			{
				if (string.Compare(
				    	line,
				    	"create table users_in_groups (group_id INT not null, user_id INT not null, primary key (user_id, group_id))",
				    	true) == 0)
				{
					found = true;
				}
			}

			Assert.IsTrue(found, "Script should contain the correct create table statement");
		}
 public static string[] ExportCreateSchema(Dialect dialect)
 {
     Configuration cfg = new Configuration();
     cfg.Configure();
     return cfg.GenerateSchemaCreationScript(dialect);
 }
Exemplo n.º 16
0
        public static System.Data.IDbConnection CreateFile (string path)
        {
            lock (mutex)
                if (newSession == null)
                {
                    Configuration configuration = new Configuration()
                        .SetProperty("dialect", typeof(CustomSQLiteDialect).AssemblyQualifiedName)
                        .SetProperty("connection.connection_string", "Data Source=:memory:;Version=3;")
                        .SetProperty("connection.driver_class", typeof(NHibernate.Driver.SQLite20Driver).AssemblyQualifiedName)
                        .SetProperty("connection.provider", typeof(NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName)
                        .SetProperty("connection.release_mode", "on_close")
                        ;

                    ConfigureMappings(configuration);

                    var sessionFactory = configuration.BuildSessionFactory();
                    newSession = sessionFactory.OpenStatelessSession();
                    createSql = configuration.GenerateSchemaCreationScript(Dialect.GetDialect(configuration.Properties));
                }

            string uncCompatiblePath = Util.GetSQLiteUncCompatiblePath(path);
            bool pooling = false;// path == ":memory:";
            var conn = new SQLiteConnection(String.Format("Data Source={0};Version=3;{1}", uncCompatiblePath, (pooling ? "Pooling=True;Max Pool Size=1;" : "")));
            conn.Open();

            var journal_mode = conn.ExecuteQuery("PRAGMA journal_mode").Single()[0];
            var synchronous = conn.ExecuteQuery("PRAGMA synchronous").Single()[0];
            conn.ExecuteNonQuery(@"PRAGMA journal_mode=OFF;
                                   PRAGMA synchronous=OFF;
                                   PRAGMA automatic_indexing=OFF;
                                   PRAGMA cache_size=30000;
                                   PRAGMA temp_store=MEMORY;
                                   PRAGMA page_size=32768;
                                   PRAGMA mmap_size=70368744177664; -- 2^46");

            var transaction = conn.BeginTransaction();
            var cmd = conn.CreateCommand();
            foreach (string sql in createSql)
                cmd.ExecuteNonQuery(sql);

            cmd.ExecuteNonQuery(String.Format("INSERT INTO About VALUES (1, 'IDPicker', '{0}', datetime('now'), {1})",
                                              Util.Version, SchemaUpdater.CurrentSchemaRevision));

            cmd.ExecuteNonQuery(@"CREATE TABLE PeptideSpectrumMatchScoreName (Id INTEGER PRIMARY KEY, Name TEXT UNIQUE NOT NULL);
                                  CREATE TABLE DistinctMatchQuantitation (Id TEXT PRIMARY KEY, iTRAQ_ReporterIonIntensities BLOB, TMT_ReporterIonIntensities BLOB, PrecursorIonIntensity NUMERIC);
                                  CREATE TABLE IntegerSet (Value INTEGER PRIMARY KEY);");
            CreateIndexes(conn);
            transaction.Commit();

            conn.ExecuteNonQuery("PRAGMA journal_mode=" + journal_mode + ";" +
                                 "PRAGMA synchronous=" + synchronous);

            return conn;
        }
Exemplo n.º 17
0
        static int Main(string[] args)
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();
                string scriptDir = Settings.Default.ScriptsDir;
                if (!Path.IsPathRooted (scriptDir))
                {
                    scriptDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, scriptDir);
                }

                Console.WriteLine("Generating script...");

                Configuration cfg = new Configuration();
                cfg.Configure();

                Dialect dialect = Dialect.GetDialect(cfg.Properties);
                string[] dropStatements = cfg.GenerateDropSchemaScript(dialect);
                string[] createStatements = cfg.GenerateSchemaCreationScript(dialect);

                using (StreamWriter writer = new StreamWriter(Path.Combine(scriptDir, Settings.Default.ScriptToGenerate), false, Encoding.Default))
                {
                    foreach (string s in dropStatements)
                    {
                        string f = Format(ParseDropConstraint(s));
                        writer.WriteLine(f);
                    }

                    writer.WriteLine();

                    foreach (string s in createStatements)
                    {
                        string f = Format(ParseCreateTable(s));
                        writer.WriteLine(f);
                    }

                    foreach (string scriptToAppend in Settings.Default.ScriptsToAppend)
                    {
                        writer.WriteLine();
                        writer.WriteLine(File.ReadAllText(Path.Combine(scriptDir, scriptToAppend),Encoding.Default));
                    }
                }
                Console.WriteLine("Done");
            }
            catch (Exception e)
            {
                log.Error(e);
                Console.WriteLine(e);
                return 1;
            }

            return 0;
        }