예제 #1
0
        /// <summary>
        /// Generates Change Script
        /// </summary>
        /// <param name="connectionString">ConnectionString</param>
        /// <param name="execute">Run SQL script on the DB</param>
        /// <returns>Change Script</returns>
        public string CreateChangeScript(string connectionString, bool execute = false)
        {
            string        changeScript = string.Empty;
            List <string> sqlCommands  = new List <string>();

            if (saveScriptsInFilesystem)
            {
                if (File.Exists("Scripts\\ChangeScript.sql"))
                {
                    File.Delete("Scripts\\ChangeScript.sql");
                }
            }

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

            using (var connection = new OracleConnection(connectionString))
            {
                connection.Open();
                var schemaUpdateScript = configuration.GenerateSchemaUpdateScript(dialect, new DatabaseMetadata(connection, dialect));

                if (saveScriptsInFilesystem)
                {
                    using (var sw = new StreamWriter(string.Format("Scripts\\ChangeScript.sql"), true))
                    {
                        if (!schemaUpdateScript.Any())
                        {
                            var noChange = "-- No change";
                            sw.WriteLine(noChange);
                        }
                        else
                        {
                            foreach (var line in schemaUpdateScript)
                            {
                                sw.WriteLine("{0};", line);
                                sqlCommands.Add(line);
                            }
                        }
                    }
                }

                if (!schemaUpdateScript.Any())
                {
                    var noChange = "-- No change";
                    changeScript += noChange + Environment.NewLine;
                }
                else
                {
                    foreach (var line in schemaUpdateScript)
                    {
                        changeScript += string.Format("{0};{1}", line, Environment.NewLine);
                    }
                }

                if (schemaUpdateScript.Any() && execute)
                {
                    foreach (string sqlCommand in sqlCommands)
                    {
                        RunSqlCommand(connection, sqlCommand);
                    }
                }
            }

            return(changeScript);
        }