コード例 #1
0
        public FaustMigrationHistory RunMigrationScript(FaustMigrationScript script, UserContext userContext)
        {
            Logger.Log(string.Format("FaustEngine.RunMigrationScript: Running commands for script {0}.", script.ScriptName), TraceEventType.Verbose);

            FaustMigrationHistory migrationHistory = new FaustMigrationHistory();

            try
            {
                migrationHistory.ReleaseNumber = script.ReleaseNumber;
                migrationHistory.ScriptName    = script.ScriptName;
                migrationHistory.Committed     = true;
                migrationHistory.Successful    = true;
                migrationHistory.LastRun       = DateTime.Now;

                foreach (string sqlCommand in script.Commands)
                {
                    migrationHistory.Log = sqlCommand;

                    UnityCache.Resolve <IFaustAccessor>().ExecuteSqlCommand(sqlCommand, userContext);
                }

                return(migrationHistory);
            }
            catch (Exception ex)
            {
                migrationHistory.Successful = false;
                migrationHistory.Log        = string.Format("Error: {0}\r\nCommand: {1}", ex.Message, migrationHistory.Log);

                Logger.Log(string.Format("FaustEngine.RunMigrationScript: {0}", migrationHistory.Log), TraceEventType.Error);

                return(migrationHistory);
            }
        }
コード例 #2
0
        public void SaveMigrationsHistory(FaustMigrationHistory[] migrationHistories, UserContext userContext)
        {
            Logger.Log(string.Format("FaustEngine.SaveMigrationsHistory: Saving History for {0} scripts.", migrationHistories.Length), TraceEventType.Verbose);

            foreach (FaustMigrationHistory migration in migrationHistories)
            {
                FaustMigrationHistory searchCriteria = new FaustMigrationHistory
                {
                    ReleaseNumber = migration.ReleaseNumber,
                    ScriptName    = migration.ScriptName
                };

                using (TransactionScope loggingScope = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    FaustMigrationHistory existingHistory = UnityCache.Resolve <IFaustMigrationsHistoryAccessor>()
                                                            .FindMany(searchCriteria, userContext)
                                                            .FirstOrDefault();
                    if (existingHistory == null)
                    {
                        UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Create(migration, userContext);
                    }
                    else
                    {
                        existingHistory.LastRun    = migration.LastRun;
                        existingHistory.Committed  = migration.Committed;
                        existingHistory.Successful = migration.Successful;
                        existingHistory.Log        = migration.Log;

                        UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Update(existingHistory, userContext);
                    }

                    loggingScope.Complete();
                }
            }
        }
コード例 #3
0
        static void Main(string[] args)
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            UnityCache.Resolve <IDalManager>().CreateDataContracts();
            UnityCache.Resolve <IDalManager>().CreateFluentApiEntries();
            UnityCache.Resolve <IDalManager>().CreateDatabaseAccessors();
            UnityCache.Resolve <IDalManager>().CreateUnitTests();
        }
コード例 #4
0
        public void CreateDataContracts()
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            foreach (IncludedTablesElement table in config.IncludedTables)
            {
                InformationSchemaColumn[] columns = UnityCache.Resolve <IDatabaseAccessor>().GetColumnsForTable(table.Name, table.Schema);

                string tableName = columns.First().TABLE_NAME.TrimEnd(new char[] { 's' });

                UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DataContract.cshtml", config.DataContractsPath, tableName, columns);
            }
        }
コード例 #5
0
        public void CreateUnitTests()
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DatabaseAccessorTestBase.cshtml", config.UnitTestsPath, "DatabaseAccessorTestBase");

            foreach (IncludedTablesElement table in DalGeneratorConfigSection.current.IncludedTables)
            {
                List <InformationSchemaColumn> columns = UnityCache.Resolve <IDatabaseAccessor>()
                                                         .GetColumnsForTable(table.Name, table.Schema)
                                                         .ToList();

                string tableName    = columns.First().TABLE_NAME.TrimEnd(new char[] { 's' });
                string accessorFile = string.Format("{0}AccessorTests", tableName);

                UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DatabaseAccessorUnitTest.cshtml", config.UnitTestsPath, accessorFile, tableName);
            }
        }
コード例 #6
0
ファイル: FaustBaseClient.cs プロジェクト: dnsdurham/FAUST
 public static void RunMigrations(string[] args)
 {
     if (args.Length > 0)
     {
         if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[args[0]]))
         {
             UnityCache.Resolve <IFaustManager>().RunMigration(args[0]);
         }
         else
         {
             Console.WriteLine("##teamcity[message text='Specified database does not exist in App.config' errorDetails='' status='ERROR']");
             Console.WriteLine("##teamcity[buildProblem description='FAUST Failed.  See build log for details.']");
         }
     }
     else
     {
         UnityCache.Resolve <IFaustManager>().RunMigration(ConfigurationManager.AppSettings["DefaultDatabase"]);
     }
 }
コード例 #7
0
        public void CreateFluentApiEntries()
        {
            DalGeneratorConfigSection config = DalGeneratorConfigSection.current;

            // Create DbBase.cs File
            UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DbBase.cshtml", config.AccessorsPath, "DbBase");

            // Create DbContext class
            List <TableColumnContext> contexts = new List <TableColumnContext>();

            foreach (IncludedTablesElement table in DalGeneratorConfigSection.current.IncludedTables)
            {
                List <TablePrimaryKey> primaryKeys = UnityCache.Resolve <IDatabaseAccessor>()
                                                     .GetPrimaryKeysForTable(table.Name, table.Schema)
                                                     .ToList();

                List <InformationSchemaColumn> columns = UnityCache.Resolve <IDatabaseAccessor>()
                                                         .GetColumnsForTable(table.Name, table.Schema)
                                                         .ToList();

                List <String> allIdColumns = columns.Where(c => c.COLUMN_NAME.EndsWith("Id"))
                                             .Where(c => !primaryKeys.Any(k => k.COLUMN_NAME == c.COLUMN_NAME))
                                             .Select(c => c.COLUMN_NAME).ToList();

                contexts.Add(new TableColumnContext
                {
                    TableNamePlural   = table.Name,
                    TableNameSingular = table.Name.TrimEnd(new char[] { 's' }),
                    SchemaName        = table.Schema,
                    IdentityColumns   = columns.Where(c => c.IsIdentity).Select(c => c.COLUMN_NAME).ToList(),
                    PrimaryKeys       = primaryKeys,
                    AllIds            = allIdColumns
                });
            }

            UnityCache.Resolve <IDalEngine>().GenerateCodeFile(config.TemplatesPath, "DbContext.cshtml", config.AccessorsPath, config.DbContextClassName, contexts);
        }
コード例 #8
0
        public FaustMigrationScript[] GetReleaseMigrationScripts(DirectoryInfo release, UserContext userContext)
        {
            Logger.Log(string.Format("FaustEngine.GetReleaseMigrationScripts:  Getting migrationscripts for release {0}.", release.Name), TraceEventType.Verbose);

            IEnumerable <FileInfo> files = release.EnumerateFiles().Where(file => file.Extension == ".sql");

            return(files.Select(file => new FaustMigrationScript
            {
                ReleaseNumber = int.Parse(file.Directory.Name),
                ScriptName = file.Name,
                FilePath = file.FullName,
                Successful = null,
                Commands = GetSqlCommands(file),
            })
                   .Where(script => UnityCache.Resolve <IFaustMigrationsHistoryAccessor>()
                          .FindMany(new FaustMigrationHistory
            {
                ReleaseNumber = script.ReleaseNumber,
                ScriptName = script.ScriptName,
                Committed = true,
            }, userContext).Length == 0)
                   .OrderBy(s => GetScriptOrdinal(s.ScriptName))
                   .ToArray());
        }
コード例 #9
0
ファイル: FaustManager.cs プロジェクト: dnsdurham/FAUST
        public void RunMigration(string databaseName)
        {
            Logger.Log(string.Format("FaustManager.RunMigration:  Running Migrations for database {0}.", databaseName), TraceEventType.Verbose);
            Console.WriteLine("##teamcity[message text='FAUSTing Migrations']");

            UserContext userContext = UserContext.GetUserContext(databaseName);

            UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Initialize(userContext);

            List <DirectoryInfo> releaseDirs = Directory.GetDirectories(ConfigurationManager.AppSettings["MigrationsDirectory"] + databaseName)
                                               .Select(dir => new DirectoryInfo(dir))
                                               .Where(dir => int.Parse(dir.Name) > 0)
                                               .OrderBy(dir => int.Parse(dir.Name))
                                               .ToList();

            if (ConfigurationManager.AppSettings["RunDebugMigrations"] == "true")
            {
                List <DirectoryInfo> holdingDirs = Directory.GetDirectories(ConfigurationManager.AppSettings["MigrationsDirectory"] + databaseName)
                                                   .Select(dir => new DirectoryInfo(dir))
                                                   .Where(dir => int.Parse(dir.Name) < 0)
                                                   .OrderByDescending(dir => int.Parse(dir.Name))
                                                   .ToList();
                holdingDirs.ForEach(d => releaseDirs.Add(d));

                UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().DeleteDebugEntries(userContext);
            }

            foreach (DirectoryInfo release in releaseDirs)
            {
                FaustMigrationScript[] scripts = UnityCache.Resolve <IFaustEngine>().GetReleaseMigrationScripts(release, userContext);

                List <FaustMigrationHistory> migrationHistories = new List <FaustMigrationHistory>();

                TransactionScopeOption scopeOption = TransactionScopeOption.Required;

                if (release.EnumerateFiles().Any(file => file.Name == "no.transaction"))
                {
                    scopeOption = TransactionScopeOption.Suppress;
                }
                TimeSpan desiredTimeout = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["DefaultCommandTimeoutSecondsOverride"]));

                Settings.OverrideTransactionManagerMaximumTimeout(desiredTimeout);
                using (TransactionScope releaseScope = new TransactionScope(scopeOption, new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                }))
                {
                    foreach (FaustMigrationScript script in scripts)
                    {
                        FaustMigrationHistory migrationHistory = UnityCache.Resolve <IFaustEngine>().RunMigrationScript(script, userContext);

                        migrationHistories.Add(migrationHistory);

                        if (!migrationHistory.Successful ?? false)
                        {
                            releaseScope.Dispose();
                            migrationHistories.ForEach(m => m.Committed = false);
                            Console.WriteLine(string.Format("##teamcity[message text='{0}' errorDetails='' status='ERROR']", migrationHistory.Log));
                            Console.WriteLine("##teamcity[buildProblem description='FAUST Failed.  See build log for details.']");
                            Logger.Log(string.Format("FaustManager.RunMigration: {0}", migrationHistory.Log), TraceEventType.Error);
                            break;
                        }
                    }

                    if (Transaction.Current != null)
                    {
                        releaseScope.Complete();
                        Console.WriteLine("##teamcity[message text='FAUSTing completed without errors.']");
                    }

                    UnityCache.Resolve <IFaustEngine>().SaveMigrationsHistory(migrationHistories.ToArray(), userContext);
                }
            }
        }