浏览代码

add DbUpdate, DbClear

Dalibor Votruba 3 年之前
父节点
当前提交
3b1b3db7a6

+ 11 - 1
qdr.app.qlbrc.console/Commands/Base/DbContextCommand.cs

@@ -1,4 +1,5 @@
-using Quadarax.Application.QLiberace.Base;
+using Microsoft.Data.SqlClient;
+using Quadarax.Application.QLiberace.Base;
 using Quadarax.Foundation.Core.QConsole.Command.Base;
 using Quadarax.Foundation.Core.QConsole;
 using Quadarax.Foundation.Core.Value;
@@ -34,6 +35,15 @@ namespace Quadarax.Application.QLiberace.Console.Commands.Base
 
         #region *** Private operations ***
 
+        protected Result HandleConnectionException(SqlException e)
+        {
+            if (e.Message.Contains("A network-related or instance-specific error occurred while establishing a connection to SQL Server"))
+            {
+                WriteError(e);
+                return new Result(Constants.ReturnCodes.CannotConnectToServer);
+            }
+            throw e;
+        }
         #endregion
     }
 }

+ 60 - 0
qdr.app.qlbrc.console/Commands/DbClearCmd.cs

@@ -0,0 +1,60 @@
+using Microsoft.Data.SqlClient;
+using Quadarax.Application.QLiberace.Base;
+using Quadarax.Application.QLiberace.Console.Commands.Base;
+using Quadarax.Foundation.Core.QConsole;
+using Quadarax.Foundation.Core.QConsole.Attributes;
+using Quadarax.Foundation.Core.Value;
+
+namespace Quadarax.Application.QLiberace.Console.Commands
+{
+    [CommandDefinition]
+    internal class DbClearCmd : DbContextCommand
+    {
+         #region *** Properties ***
+
+        public override string Name => Constants.Commands.DbClear.Name;
+        public override string Description => Constants.Commands.DbClear.Description;
+        
+        #endregion
+        #region *** Fields ***
+
+        #endregion
+
+        #region *** Constructor ***
+
+        public DbClearCmd(Engine engine) : base(engine)
+        {
+        }
+        #endregion
+        
+        #region *** EXECUTE ***
+        protected override Result OnExecute(QlbrcDbContext context)
+        {
+            WriteInfo("Connecting database...");
+            var resultCode = 0;
+            try
+            {
+                if (context.Database.CanConnect())
+                {
+                    WriteInfo("Deleting database...");
+                    context.Database.EnsureDeleted();
+                }
+                WriteInfo("Creating database...");
+                context.Database.EnsureCreated();
+            }
+            catch (SqlException e)
+            {
+                return HandleConnectionException(e);
+            }
+
+            return new Result(resultCode);
+        }
+
+        
+        #endregion
+
+        #region *** Private operations ***
+        #endregion
+    }
+    
+}

+ 5 - 15
qdr.app.qlbrc.console/Commands/DbInstallCmd.cs

@@ -1,11 +1,9 @@
-using System.Linq.Expressions;
-using Microsoft.Data.SqlClient;
+using Microsoft.Data.SqlClient;
 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.Argument;
-using Quadarax.Foundation.Core.QConsole.Value;
 using Quadarax.Foundation.Core.Value;
 
 namespace Quadarax.Application.QLiberace.Console.Commands
@@ -37,19 +35,17 @@ namespace Quadarax.Application.QLiberace.Console.Commands
         protected override Result OnExecute(QlbrcDbContext context)
         {
             WriteInfo("Ensuring database...");
-            var resultCode = 0;
-            // TODO: handle this exception as resultCode = 1 on context.Database.EnsureCreated()
-            // Microsoft.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server
+            var resultCode = Constants.ReturnCodes.Ok;
             try
             {
                 if (!context.Database.EnsureCreated())
                 {
                     WriteInfo("Database already exists.");
-                    resultCode = 1;
+                    resultCode = Constants.Commands.DbInstall.ReturnCodes.DatabaseExists;
                 }
                 else
                 {
-                    WriteInfo("Database created.");
+                    WriteWarning("Database created.");
                 }
 
                 if (_isLatestUpdateEnabled)
@@ -68,13 +64,7 @@ namespace Quadarax.Application.QLiberace.Console.Commands
             }
             catch (SqlException e)
             {
-                if (e.Message.Contains("A network-related or instance-specific error occurred while establishing a connection to SQL Server"))
-                {
-                    WriteError(e);
-                    return new Result(10);
-                }
-
-                throw e;
+                return HandleConnectionException(e);
             }
 
             return new Result(resultCode);

+ 98 - 0
qdr.app.qlbrc.console/Commands/DbUpdateCmd.cs

@@ -0,0 +1,98 @@
+using Microsoft.Data.SqlClient;
+using Quadarax.Application.QLiberace.Base;
+using Quadarax.Application.QLiberace.Console.Commands.Base;
+using Quadarax.Foundation.Core.QConsole.Argument;
+using Quadarax.Foundation.Core.QConsole;
+using Quadarax.Foundation.Core.Value;
+using Microsoft.EntityFrameworkCore;
+using Quadarax.Foundation.Core.QConsole.Attributes;
+
+namespace Quadarax.Application.QLiberace.Console.Commands
+{
+    [CommandDefinition]
+    internal class DbUpdateCmd : DbMigrationCommand
+    {
+         #region *** Properties ***
+
+        public override string Name => Constants.Commands.DbUpdate.Name;
+        public override string Description => Constants.Commands.DbUpdate.Description;
+        
+        #endregion
+        #region *** Fields ***
+
+        private bool _isListOnly;
+        #endregion
+
+        #region *** Constructor ***
+
+        public DbUpdateCmd(Engine engine) : base(engine)
+        {
+        }
+        #endregion
+        
+        #region *** EXECUTE ***
+        protected override Result OnExecute(QlbrcDbContext context)
+        {
+            WriteInfo("Connecting database...");
+            var resultCode = 0;
+            try
+            {
+                if (context.Database.CanConnect())
+                {
+                    if (_isListOnly)
+                    {
+                        WriteInfo("Pending migrations list:");
+                        var migrations = context.Database.GetPendingMigrations().ToArray();
+                        if (migrations.Length > 0)
+                        {
+                            foreach (var mig in migrations)
+                                WriteInfo(mig);
+                        }
+                        else
+                        {
+                            WriteInfo("No pending migrations present.");
+                        }
+
+                        WriteWarning("No migration applied.");
+                    }
+                    else
+                    {
+                        ApplyMigration(context);
+                        WriteWarning("Migration applied.");
+                    }
+                }
+                else
+                {
+                    WriteWarning("Database doesn't exists. Use db_install first.");
+                    return new Result(Constants.Commands.DbUpdate.ReturnCodes.DatabaseNotExists); 
+                }
+            }
+            catch (SqlException e)
+            {
+                return HandleConnectionException(e);
+            }
+
+            return new Result(resultCode);
+        }
+
+        
+        #endregion
+
+        #region *** Private operations ***
+        protected override void OnValidateArguments()
+        {
+            base.OnValidateArguments();
+            if (ContainsArgument(Constants.Commands.DbUpdate.Arguments.List.Name))
+                  _isListOnly = GetArgumentValueOrDefault<bool>(Constants.Commands.DbUpdate.Arguments.List.Name);
+        }
+        protected override IEnumerable<AbstractArgument> OnSetupArguments()
+        {
+            var arguments = new List<AbstractArgument>(base.OnSetupArguments());
+            arguments.Add(new FlagArgument(Constants.Commands.DbUpdate.Arguments.List.Name, 
+                Constants.Commands.DbUpdate.Arguments.List.Description, 
+                Constants.Commands.DbUpdate.Arguments.List.Hint, false));
+            return arguments;
+        }
+        #endregion
+    }
+}

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

@@ -7,6 +7,20 @@
             public const string Name = "QLiberace console";
         }
 
+        internal class ReturnCodes
+        {
+            /*
+             Return codes range:
+            0           Ok
+            1 - 9       Warning
+            10 - 99     Handled errors
+            100 - *     Unhandled errors
+             */
+            public const int Ok = 0;
+            public const int CannotConnectToServer = 10;
+            public const int UndandledError = 100;
+        }
+
         internal class Commands
         {
             internal class DbInstall
@@ -23,6 +37,41 @@
                         public const string Description = "Calls db_update after create database (migrate to latest version)";
                     }
                 }
+                public class ReturnCodes : Constants.ReturnCodes
+                {
+                    public const int DatabaseExists = 1;
+                }
+            }
+            internal class DbUpdate
+            {
+                public const string Name = "db_update";
+                public const string Description = "Install application database updates (must exists)";
+
+                internal class Arguments
+                {
+                    internal class List
+                    {
+                        public const string Name = "list";
+                        public const string Hint = "<is_list_only>";
+                        public const string Description = "List all pendings updates, nothing will be applied (just list)";
+                    }
+                }
+                public class ReturnCodes : Constants.ReturnCodes
+                {
+                    public const int DatabaseNotExists = 1;
+                }
+            }
+            internal class DbClear
+            {
+                public const string Name = "db_clear";
+                public const string Description = "Clears all data in database (reset to factory defaults)";
+
+                internal class Arguments
+                {
+                }
+                public class ReturnCodes : Constants.ReturnCodes
+                {
+                }
             }
         }
     }

+ 8 - 0
qdr.app.qlbrc.console/Properties/launchSettings.json

@@ -3,6 +3,14 @@
     "db_install": {
       "commandName": "Project",
       "commandLineArgs": "db_install -latest"
+    },
+    "db_update": {
+      "commandName": "Project",
+      "commandLineArgs": "db_update -list"
+    },
+    "db_clear": {
+      "commandName": "Project",
+      "commandLineArgs": "db_clear"
     }
   }
 }

+ 34 - 1
qdr.app.qlbrc.console/readme.txt

@@ -11,7 +11,7 @@
 | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |
  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------'  '----------------' 
 																					CONSOLE v.0.0.0
-																				   Modified: 17.9.2022
+																				   Modified: 18.9.2022
 
 Commands list:
 * Testing *
@@ -40,4 +40,37 @@ db_install
 		0		Ok
 		1		Database already axists
 		10		Cannot connect to server		
+		100		Other unhandled exception
+
+
+db_update
+----------
+	description:
+		Install all pending updates to existing database (database must exists, keeps existing data)
+
+	arguments mandatory:
+		-list				- list all pendings updates, nothing will be applied (just list)
+
+	arguments optional:
+		
+
+	exit codes:
+		0		Ok		
+		1		Database doesn't exists		
+		10		Cannot connect to server				
+		100		Other unhandled exception
+
+db_clear
+----------
+	description:
+		Clears all data in database (reset to factory defaults), deletes and create database during the process.
+
+	arguments mandatory:
+
+	arguments optional:
+		
+
+	exit codes:
+		0		Ok		
+		10		Cannot connect to server				
 		100		Other unhandled exception