Exemplo n.º 1
0
        /// <summary>
        /// Runs the <see cref="DatabaseExecutor"/> directly.
        /// </summary>
        /// <param name="command">The <see cref="DatabaseExecutorCommand"/>.</param>
        /// <param name="connectionString">The database connection string.</param>
        /// <param name="assemblies">The <see cref="Assembly"/> array whose embedded resources will be probed.</param>
        /// <param name="codeGenArgs">The <see cref="DatabaseExecutorCommand.CodeGen"/> arguments.</param>
        /// <returns>The return code; zero equals success.</returns>
        public static async Task <int> RunAsync(DatabaseExecutorCommand command, string connectionString, Assembly[] assemblies, CodeGenExecutorArgs?codeGenArgs = null)
        {
            using var em = ExecutionManager.Create(() => new DatabaseExecutor(command, connectionString, assemblies, codeGenArgs));
            await em.RunAsync().ConfigureAwait(false);

            return(HandleRunResult(em));
        }
Exemplo n.º 2
0
 /// <summary>
 /// Runs the <see cref="DatabaseExecutor"/> directly.
 /// </summary>
 /// <param name="command">The <see cref="DatabaseExecutorCommand"/>.</param>
 /// <param name="connectionString">The database connection string.</param>
 /// <param name="assemblies">The <see cref="Assembly"/> array whose embedded resources will be probed.</param>
 /// <param name="codeGenArgs">The <see cref="DatabaseExecutorCommand.CodeGen"/> arguments.</param>
 /// <returns>The return code; zero equals success.</returns>
 public static int Run(DatabaseExecutorCommand command, string connectionString, Assembly[] assemblies, CodeGenExecutorArgs codeGenArgs = null)
 {
     using (var em = ExecutionManager.Create(() => new DatabaseExecutor(command, connectionString, assemblies, codeGenArgs)))
     {
         return(HandleRunResult(em.Run()));
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Runs the <see cref="DatabaseExecutor"/> directly.
        /// </summary>
        /// <param name="command">The <see cref="DatabaseExecutorCommand"/>.</param>
        /// <param name="connectionString">The database connection string.</param>
        /// <param name="useBeefDbo">Indicates whether to use the standard <i>Beef</i> <b>dbo</b> schema objects.</param>
        /// <param name="assemblies">The <see cref="Assembly"/> array whose embedded resources will be probed.</param>
        /// <param name="codeGenArgs">The <see cref="DatabaseExecutorCommand.CodeGen"/> arguments.</param>
        /// <returns>The return code; zero equals success.</returns>
        public static async Task <int> RunAsync(DatabaseExecutorCommand command, string connectionString, bool useBeefDbo, Assembly[] assemblies, CodeGenExecutorArgs?codeGenArgs = null)
        {
            using var em = ExecutionManager.Create(() => new DatabaseExecutor(command, connectionString, useBeefDbo ? assemblies.Prepend(typeof(DatabaseExecutor).Assembly).ToArray() : assemblies, codeGenArgs));
            await em.RunAsync().ConfigureAwait(false);

            return(HandleRunResult(em));
        }
Exemplo n.º 4
0
 /// <summary>
 /// Runs the <see cref="DatabaseExecutor"/> directly.
 /// </summary>
 /// <param name="command">The <see cref="DatabaseExecutorCommand"/>.</param>
 /// <param name="connectionString">The database connection string.</param>
 /// <param name="assemblies">The <see cref="Assembly"/> array whose embedded resources will be probed.</param>
 /// <returns>The return code; zero equals success.</returns>
 public static int Run(DatabaseExecutorCommand command, string connectionString, params Assembly[] assemblies)
 {
     using (var em = ExecutionManager.Create(() => new DatabaseExecutor(command, connectionString, assemblies, null)))
     {
         return(HandleRunResult(em.Run()));
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Creates <see cref="ExecutionManager"/> and coordinates the run (overall execution).
        /// </summary>
        private async Task <int> RunRunAwayAsync() /* Inspired by https://www.youtube.com/watch?v=ikMiQZF-mAY */
        {
            var args = new CodeGenExecutorArgs(_assembliesOpt.HasValue() ? ((AssemblyValidator)_assembliesOpt.Validators.First()).Assemblies : _assemblies, CreateParamDict(_paramsOpt))
            {
                ConfigFile     = new FileInfo(_configArg.Value),
                ScriptFile     = new FileInfo(_scriptOpt.Value()),
                TemplatePath   = _templateOpt.HasValue() ? new DirectoryInfo(_templateOpt.Value()) : null,
                OutputPath     = new DirectoryInfo(_outputOpt.HasValue() ? _outputOpt.Value() : Environment.CurrentDirectory),
                ExpectNoChange = _expectNoChange.HasValue(),
            };

            WriteHeader(args);

            using (var em = ExecutionManager.Create(() => new CodeGenExecutor(args)))
            {
                if (args.ExpectNoChange)
                {
                    em.ExceptionHandling = ExceptionHandling.Stop;
                }

                var sw = Stopwatch.StartNew();

                await em.RunAsync().ConfigureAwait(false);

                sw.Stop();
                WriteFooter(sw);

                if (args.ExpectNoChange && (em.HadExecutionException || em.LastExecutor?.Result == ExecutorResult.Unsuccessful))
                {
                    return(-1);
                }
            }
            return(0);
        }
Exemplo n.º 6
0
        public void Run_NoArgs()
        {
            int i  = 0;
            var em = ExecutionManager.Create(async(x) => { i++; await Task.CompletedTask; }).Run();

            Assert.AreEqual(1, i);
            Assert.AreEqual(1, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.TriggerStop, em.StopReason);
        }
Exemplo n.º 7
0
        public void Run_NoArgs_Fast()
        {
            int i  = 0;
            var em = ExecutionManager.Create(async(x) => { i++; TestContext.WriteLine($"i: {i}"); await Task.CompletedTask; }, new TimerTrigger(10, iterations)).Run();

            Assert.AreEqual(iterations, i);
            Assert.AreEqual(iterations, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.TriggerStop, em.StopReason);
        }
Exemplo n.º 8
0
        public void OnStopped_Exception()
        {
            int i  = 0;
            var em = ExecutionManager.Create(async(x) => { i++; await Task.CompletedTask; }, new TestTrigger(2)).Run();

            Assert.AreEqual(1, i);
            Assert.AreEqual(1, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.TriggerException, em.StopReason);
            Assert.AreEqual(TriggerResult.Unsuccessful, em.Trigger.Result);
            Assert.IsNotNull(em.Trigger.Exception);
            Assert.IsInstanceOf(typeof(DivideByZeroException), em.Trigger.Exception);
        }
Exemplo n.º 9
0
        public void Run_NoArgs_Slow()
        {
            int i  = 0;
            var sw = Stopwatch.StartNew();
            var em = ExecutionManager.Create(async(x) => { i++; TestContext.WriteLine($"i: {i}"); await Task.Delay(200); }, new SlidingTimerTrigger(10, iterations)).Run();

            sw.Stop();
            Assert.IsTrue(sw.ElapsedMilliseconds > 2000, sw.ElapsedMilliseconds.ToString());
            Assert.AreEqual(iterations, i);
            Assert.AreEqual(iterations, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.TriggerStop, em.StopReason);
        }
Exemplo n.º 10
0
        public void Run_NoArgs_OnStarted_Exception_Continue()
        {
            var i  = 0;
            var em = ExecutionManager.Create(() => { i++; return(new TestNotArgsExe(100)); }, new TimerTrigger(10, 5));

            em.ExceptionHandling = ExceptionHandling.Continue;
            em.Run();
            Assert.AreEqual(5, i);
            Assert.AreEqual(5, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.TriggerStop, em.StopReason);
            Assert.AreEqual(TriggerResult.Successful, em.Trigger.Result);
            Assert.IsNull(em.StopExecutor);
        }
Exemplo n.º 11
0
        public void Run_NoArgs_OnStarted_Exception_Stop()
        {
            var i  = 0;
            var em = ExecutionManager.Create(() => { i++; return(new TestNotArgsExe(100)); }, new TimerTrigger(10, 5));

            em.ExceptionHandling = ExceptionHandling.Stop;
            em.Run();
            Assert.AreEqual(1, i);
            Assert.AreEqual(1, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.ExecutorExceptionStop, em.StopReason);
            Assert.AreEqual(TriggerResult.Successful, em.Trigger.Result);
            Assert.IsNotNull(em.StopExecutor);
            Assert.AreEqual(ExecutorResult.Unsuccessful, em.StopExecutor.Result);
            Assert.IsNotNull(em.StopExecutor.Exception);
            Assert.IsInstanceOf(typeof(NotSupportedException), em.StopExecutor.Exception);
        }
Exemplo n.º 12
0
        public void Run_NoArgs_OnStarted_StopOk_Stop()
        {
            Assert.Inconclusive("Need to investigate");

            var i  = 0;
            var em = ExecutionManager.Create(() => { i++; return(new TestNotArgsExe(101)); }, new TimerTrigger(10, 5));

            em.ExceptionHandling = ExceptionHandling.Stop;
            em.Run();
            Assert.AreEqual(5, i);
            Assert.AreEqual(5, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.TriggerStop, em.StopReason);
            Assert.AreEqual(TriggerResult.Successful, em.Trigger.Result);
            Assert.IsNull(em.StopExecutor);
            Assert.AreEqual(ExecutorResult.Successful, em.StopExecutor.Result);
            Assert.IsNull(em.StopExecutor.Exception);
        }
Exemplo n.º 13
0
        public void Run_NoArgs_OnRunException_Stop()
        {
            Assert.Inconclusive("Need to investigate");

            var i  = 0;
            var em = ExecutionManager.Create(() => { i++; return(new TestNotArgsExe(200)); }, new TimerTrigger(10, 5));

            em.ExceptionHandling = ExceptionHandling.Stop;
            em.Run();
            Assert.AreEqual(1, i);
            Assert.AreEqual(1, em.ExecutorCount);
            Assert.AreEqual(ExecutionManagerStopReason.ExecutorExceptionStop, em.StopReason);
            Assert.AreEqual(TriggerResult.Successful, em.Trigger.Result);
            Assert.IsNotNull(em.StopExecutor);
            Assert.AreEqual(ExecutorResult.Unsuccessful, em.StopExecutor.Result);
            Assert.IsNotNull(em.StopExecutor.Exception);
            Assert.IsInstanceOf(typeof(DivideByZeroException), em.StopExecutor.Exception);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates <see cref="ExecutionManager"/> and coordinates the run (overall execution).
        /// </summary>
        private async Task <int> RunRunAwayAsync() /* Inspired by https://www.youtube.com/watch?v=ikMiQZF-mAY */
        {
            var args = new CodeGenExecutorArgs(_assembliesOpt.HasValue() ? ((AssemblyValidator)_assembliesOpt.Validators.First()).Assemblies : _assemblies, CreateParamDict(_paramsOpt))
            {
                ConfigFile   = new FileInfo(_configArg.Value),
                ScriptFile   = new FileInfo(_scriptOpt.Value()),
                TemplatePath = _templateOpt.HasValue() ? new DirectoryInfo(_templateOpt.Value()) : null,
                OutputPath   = new DirectoryInfo(_outputOpt.HasValue() ? _outputOpt.Value() : Environment.CurrentDirectory),
            };

            WriteHeader(args);

            using (var em = ExecutionManager.Create(() => new CodeGenExecutor(args)))
            {
                var sw = Stopwatch.StartNew();

                await em.RunAsync().ConfigureAwait(false);

                sw.Stop();
                WriteFooter(sw);
            }
            return(0);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates <see cref="ExecutionManager"/> and coordinates the run (overall execution).
        /// </summary>
        private async Task <int> RunRunAwayAsync() /* Inspired by https://www.youtube.com/watch?v=ikMiQZF-mAY */
        {
            var args = new CodeGenExecutorArgs
            {
                ConfigFile   = new FileInfo(_configOpt.Value()),
                ScriptFile   = new FileInfo(_scriptOpt.Value()),
                TemplatePath = _templateOpt.HasValue() ? new DirectoryInfo(_templateOpt.Value()) : null,
                OutputPath   = new DirectoryInfo(_outputOpt.HasValue() ? _outputOpt.Value() : Environment.CurrentDirectory),
                Parameters   = CodeGenConsole.CreateParamDict(_paramsOpt),
                Assemblies   = _scriptAssemblies
            };

            WriteHeader(args);

            var em = ExecutionManager.Create(() => new DatabaseExecutor(_commandArg.ParsedValue, _connectionStringArg.Value, _scriptAssemblies.ToArray(), args));
            var sw = Stopwatch.StartNew();

            await em.RunAsync();

            sw.Stop();
            WriteFooter(sw);
            return(0);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Execute the database upgrade.
        /// </summary>
        protected override async Task OnRunAsync(ExecutorRunArgs args)
        {
            var ls = new LoggerSink();

            if (_command.HasFlag(DatabaseExecutorCommand.Drop))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB DROP: Checking database existence and dropping where found...");
                await TimeExecutionAsync(() => { DropDatabase.For.SqlDatabase(_connectionString, ls); return(Task.FromResult(true)); }).ConfigureAwait(false);
            }

            if (_command.HasFlag(DatabaseExecutorCommand.Create))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB CREATE: Checking database existence and creating where not found...");
                await TimeExecutionAsync(() => { EnsureDatabase.For.SqlDatabase(_connectionString, ls); return(Task.FromResult(true)); }).ConfigureAwait(false);
            }

            if (_command.HasFlag(DatabaseExecutorCommand.Migrate))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB MIGRATE: Migrating the database...");
                Logger.Default.Info($"Probing for embedded resources: {(string.Join(", ", GetNamespacesWithSuffix($"{MigrationsNamespace}.*.sql")))}");

                DatabaseUpgradeResult?result = null;
                await TimeExecutionAsync(() =>
                {
                    result = DeployChanges.To
                             .SqlDatabase(_connectionString)
                             .WithScripts(GetMigrationScripts(_assemblies))
                             .WithoutTransaction()
                             .LogTo(ls)
                             .Build()
                             .PerformUpgrade();

                    return(Task.FromResult(result.Successful));
                }).ConfigureAwait(false);

                if (!result !.Successful)
                {
                    Logger.Default.Exception(result.Error);
                    return;
                }
            }

            if (_command.HasFlag(DatabaseExecutorCommand.CodeGen))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB CODEGEN: Code-gen database objects...");
                CodeGenConsole.LogCodeGenExecutionArgs(_codeGenArgs);

                if (!await TimeExecutionAsync(async() =>
                {
                    var em = ExecutionManager.Create(() => new CodeGenExecutor(_codeGenArgs));
                    await em.RunAsync().ConfigureAwait(false);
                    return(em.StopExecutor?.Exception == null);
                }).ConfigureAwait(false))
                {
                    return;
                }
            }

            if (_command.HasFlag(DatabaseExecutorCommand.Schema))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB SCHEMA: Drops and creates the database objects...");

                if (!await TimeExecutionAsync(() => DropAndCreateAllObjectsAsync(new string[] { "dbo", "Ref" })).ConfigureAwait(false))
                {
                    return;
                }
            }

            if (_command.HasFlag(DatabaseExecutorCommand.Reset))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB RESET: Resets database by dropping data from all tables...");

                if (!await TimeExecutionAsync(() => DeleteAllAndResetAsync()).ConfigureAwait(false))
                {
                    return;
                }
            }

            if (_command.HasFlag(DatabaseExecutorCommand.Data))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB DATA: Insert or merge the embedded YAML data...");

                if (!await TimeExecutionAsync(() => InsertOrMergeYamlDataAsync()).ConfigureAwait(false))
                {
                    return;
                }
            }

            if (_command.HasFlag(DatabaseExecutorCommand.ScriptNew))
            {
                Logger.Default.Info(string.Empty);
                Logger.Default.Info(new string('-', 80));
                Logger.Default.Info("DB SCRIPTNEW: Creating a new SQL script from embedded template...");

                if (!await TimeExecutionAsync(() => CreateScriptNewAsync()).ConfigureAwait(false))
                {
                    return;
                }
            }

            ReturnCode = 0;
        }