ソースを参照

QConsole Engine.ResultCode support (add Code to Result)

DbInstallCmd with (-latest) complete
Dalibor Votruba 3 年 前
コミット
2cdc542b54

+ 3 - 0
Common/qdr.fnd.core.qconsole/Engine.cs

@@ -27,6 +27,7 @@ namespace Quadarax.Foundation.Core.QConsole
         public ISelectionEntry[] Selections => _selections.ToArray();
 
         public IEngineContext Context { get; }
+        public int ReturnCode { get; private set; }
         #endregion
 
         #region *** Constructor ***
@@ -34,6 +35,7 @@ namespace Quadarax.Foundation.Core.QConsole
         {
             _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
             Context = context ?? throw new ArgumentNullException(nameof(context));
+            ReturnCode = 0;
 
             if (args == null)
                 args = new string[0];
@@ -136,6 +138,7 @@ namespace Quadarax.Foundation.Core.QConsole
                     }
 
                     var result = command.Execute(input);
+                    ReturnCode = result.Code;
                     if (result.IsSuccess)
                     {
                         using (var writerSucc = new ConsoleWriter(ConsoleColor.Green))

+ 2 - 2
Common/qdr.fnd.core.qconsole/qdr.fnd.core.qconsole.csproj

@@ -7,8 +7,8 @@
     <DelaySign>false</DelaySign>
     <RootNamespace>Quadarax.Foundation.Core.QConsole</RootNamespace>
     <ApplicationIcon>..\quadarax_dll.ico</ApplicationIcon>
-    <AssemblyVersion>1.0.6.0</AssemblyVersion>
-    <FileVersion>1.0.6.0</FileVersion>
+    <AssemblyVersion>1.0.7.0</AssemblyVersion>
+    <FileVersion>1.0.7.0</FileVersion>
   </PropertyGroup>
 
   <ItemGroup>

+ 11 - 2
Common/qdr.fnd.core/Value/Result.cs

@@ -8,17 +8,26 @@ namespace Quadarax.Foundation.Core.Value
     
         public bool IsSuccess { get; }
         public Exception ThrownException { get; }
+        public int Code { get; }
 
 
-        public Result(Exception e)
+        public Result(Exception e):this (e,100)
+        {
+        }
+        public Result(Exception e, int code)
         {
             ThrownException = e;
             IsSuccess = false;
+            Code = code;
         }
         
-        public Result()
+        public Result():this(0)
+        {
+        }
+        public Result(int code)
         {
             IsSuccess = true;
+            Code = code;
         }
     }
 }

+ 39 - 0
qdr.app.qlbrc.console/Commands/Base/DbContextCommand.cs

@@ -0,0 +1,39 @@
+using Quadarax.Application.QLiberace.Base;
+using Quadarax.Foundation.Core.QConsole.Command.Base;
+using Quadarax.Foundation.Core.QConsole;
+using Quadarax.Foundation.Core.Value;
+using Microsoft.EntityFrameworkCore;
+
+namespace Quadarax.Application.QLiberace.Console.Commands.Base
+{
+    internal abstract class DbContextCommand : AbstractCommand
+    {
+        #region *** Properties ***
+
+        #endregion
+
+        #region *** Constructor ***
+
+        public DbContextCommand(Engine engine) : base(engine)
+        {
+        }
+        #endregion
+        
+        #region *** EXECUTE ***
+        protected override Result OnExecute()
+        {
+            var options = new DbContextOptions<QlbrcDbContext>();
+            using (var context = new QlbrcDbContext(options))
+            {
+                return OnExecute(context);
+            }
+        }
+
+        protected abstract Result OnExecute(QlbrcDbContext context);
+        #endregion
+
+        #region *** Private operations ***
+
+        #endregion
+    }
+}

+ 50 - 0
qdr.app.qlbrc.console/Commands/Base/DbMigrationCommand.cs

@@ -0,0 +1,50 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.Extensions.DependencyInjection;
+using Quadarax.Application.QLiberace.Base;
+using Quadarax.Foundation.Core.QConsole;
+
+namespace Quadarax.Application.QLiberace.Console.Commands.Base
+{
+    internal abstract class DbMigrationCommand : DbContextCommand
+    {
+        #region *** Properties ***
+
+        #endregion
+
+        #region *** Constructor ***
+        protected DbMigrationCommand(Engine engine) : base(engine)
+        {
+        }
+        #endregion
+        
+        #region *** EXECUTE ***
+        #endregion
+
+        #region *** Private operations ***
+        //src: https://makolyte.com/ef-core-apply-migrations-programmatically/
+        protected void ApplyMigration(QlbrcDbContext context, string? migrationCode = null)
+        {
+            var migrator = context.GetInfrastructure().GetService<IMigrator>();
+            if (migrator == null)
+                throw new InvalidOperationException($"Cannot obtain service IMigrator from EFC6 infrastructure.");
+            
+            migrator.Migrate(migrationCode);
+            var lastAppliedMigration = (context.Database.GetAppliedMigrations()).Last();
+            WriteInfo($"You're now on schema version: {lastAppliedMigration}");
+        }
+
+        protected bool CheckPendingMigrations(QlbrcDbContext context)
+        {
+            return context.Database.GetPendingMigrations().Any();
+        }
+        #endregion
+
+    }
+}

+ 48 - 7
qdr.app.qlbrc.console/Commands/DbInstallCmd.cs

@@ -1,19 +1,27 @@
-using Quadarax.Foundation.Core.QConsole.Attributes;
+using Quadarax.Application.QLiberace.Base;
+using Quadarax.Application.QLiberace.Console.Commands.Base;
+using Quadarax.Foundation.Core.QConsole.Attributes;
 using Quadarax.Foundation.Core.QConsole;
-using Quadarax.Foundation.Core.QConsole.Command.Base;
+using Quadarax.Foundation.Core.QConsole.Argument;
+using Quadarax.Foundation.Core.QConsole.Value;
 using Quadarax.Foundation.Core.Value;
 
 namespace Quadarax.Application.QLiberace.Console.Commands
 {
     [CommandDefinition]
 
-    internal class DbInstallCmd : AbstractCommand
+    internal class DbInstallCmd : DbMigrationCommand
     {
 
         #region *** Properties ***
 
         public override string Name => Constants.Commands.DbInstall.Name;
         public override string Description => Constants.Commands.DbInstall.Description;
+        
+        #endregion
+        #region *** Fields ***
+
+        private bool _isLatestUpdateEnabled;
         #endregion
 
         #region *** Constructor ***
@@ -24,16 +32,49 @@ namespace Quadarax.Application.QLiberace.Console.Commands
         #endregion
         
         #region *** EXECUTE ***
+        protected override Result OnExecute(QlbrcDbContext context)
+        {
+            WriteInfo("Ensuring database...");
+            if (context.Database.EnsureCreated())
+                WriteInfo("Database already exists.");
+            else
+                WriteInfo("Database created.");
 
+            if (_isLatestUpdateEnabled)
+            {
+                WriteInfo("Checking pending migrations.");
+                if (CheckPendingMigrations(context))
+                {
+                    WriteInfo("New pending migrations detected.");
+                    ApplyMigration(context);
+                }
+                else
+                {
+                    WriteInfo("Nothing found.");
+                }
+            }
 
-        protected override Result OnExecute()
-        {
-            //TODO: ends here. Implements db_install
-            throw new NotImplementedException();
+            return new Result();
         }
+
+        
         #endregion
 
         #region *** Private operations ***
+        protected override void OnValidateArguments()
+        {
+            base.OnValidateArguments();
+            if (ContainsArgument(Constants.Commands.DbInstall.Arguments.Latest.Name))
+                _isLatestUpdateEnabled = GetArgumentValueOrDefault<bool>(Constants.Commands.DbInstall.Arguments.Latest.Name);
+        }
+        protected override IEnumerable<AbstractArgument> OnSetupArguments()
+        {
+            var arguments = new List<AbstractArgument>(base.OnSetupArguments());
+            arguments.Add(new FlagArgument(Constants.Commands.DbInstall.Arguments.Latest.Name, 
+                Constants.Commands.DbInstall.Arguments.Latest.Description, 
+                Constants.Commands.DbInstall.Arguments.Latest.Hint, false));
+            return arguments;
+        }
         #endregion
     }
 }

+ 10 - 0
qdr.app.qlbrc.console/Constants.cs

@@ -13,6 +13,16 @@
             {
                 public const string Name = "db_install";
                 public const string Description = "Install application database (even if not exists)";
+
+                internal class Arguments
+                {
+                    internal class Latest
+                    {
+                        public const string Name = "latest";
+                        public const string Hint = "<is_latest>";
+                        public const string Description = "Calls db_update after create database (migrate to latest version)";
+                    }
+                }
             }
         }
     }

+ 3 - 1
qdr.app.qlbrc.console/Program.cs

@@ -27,4 +27,6 @@ config.ShowStatusOnEveryCommand = false;
 config.IsConsoleDebug = false;
 
 var console = new Engine(config, new DefualtEngineContext(), args);
-console.Start();
+console.Start();
+
+Environment.Exit(console.ReturnCode);;

+ 7 - 11
qdr.app.qlbrc.console/Properties/launchSettings.json

@@ -1,12 +1,8 @@
-{
-  "profiles": {
-    "WSL": {
-      "commandName": "WSL2",
-      "distributionName": ""
-    },
-    "db_install": {
-      "commandName": "Project",
-      "commandLineArgs": "db_install"
-    }
-  }
+{
+  "profiles": {
+    "db_install": {
+      "commandName": "Project",
+      "commandLineArgs": "db_install -latest"
+    }
+  }
 }

+ 2 - 2
qdr.app.qlbrc.console/readme.txt

@@ -11,7 +11,7 @@
 | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |
  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------' 
 																					CONSOLE v.0.0.0
-																				   Modified: 16.9.2022
+																				   Modified: 17.9.2022
 
 Commands list:
 * Testing *
@@ -29,7 +29,7 @@ db_uninstall	-	Drop database
 db_install
 ----------
 	description:
-		Creates a brand new QLiberace database, depends on connection string definition (.config)
+		Creates a brand new QLiberace database with initial schemas, depends on connection string definition (.config)
 
 	arguments mandatory: