Skip to content

Commit

Permalink
cmdlets Create-SqlDatabase; Execute-SqlDatabase; Upgrade-SqlDatabase
Browse files Browse the repository at this point in the history
  • Loading branch information
max-ieremenko committed Nov 1, 2018
1 parent e8355e0 commit fd248d4
Show file tree
Hide file tree
Showing 12 changed files with 168 additions and 108 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Management.Automation.Runspaces;
using Moq;
using NUnit.Framework;
Expand All @@ -9,7 +11,7 @@
namespace SqlDatabase.PowerShell
{
[TestFixture]
public class ExecuteCmdLetTest
public class SqlDatabaseCmdLetTest
{
private readonly IList<CommandLine> _commandLines = new List<CommandLine>();
private Runspace _runSpace;
Expand All @@ -20,34 +22,35 @@ public class ExecuteCmdLetTest
public void BeforeEachTest()
{
var sessionState = InitialSessionState.CreateDefault();
sessionState.Commands.Add(new SessionStateCmdletEntry("Invoke-SqlDatabase", typeof(ExecuteCmdLet), null));
sessionState.Commands.Add(new SessionStateCmdletEntry("Test-SqlDatabase", typeof(SomeSqlDatabaseCmdLet), null));

_runSpace = RunspaceFactory.CreateRunspace(sessionState);
_runSpace.Open();

_powerShell = System.Management.Automation.PowerShell.Create();
_powerShell.Runspace = _runSpace;

_invokeSqlDatabase = new Command("Invoke-SqlDatabase");
_invokeSqlDatabase = new Command("Test-SqlDatabase");
_powerShell.Commands.AddCommand(_invokeSqlDatabase);

var program = new Mock<ISqlDatabaseProgram>(MockBehavior.Strict);
program
.Setup(p => p.ExecuteCommand(It.IsNotNull<CommandLine>()))
.Callback<CommandLine>(cmd =>
{
Assert.AreEqual(Configuration.Command.Execute, cmd.Command);
_commandLines.Add(cmd);
});
.Callback<CommandLine>(cmd => _commandLines.Add(cmd));

_commandLines.Clear();
ExecuteCmdLet.Program = program.Object;
SqlDatabaseCmdLet.Program = program.Object;
}

[TearDown]
public void AfterEachTest()
{
ExecuteCmdLet.Program = null;
SqlDatabaseCmdLet.Program = null;

foreach (var row in _powerShell.Streams.Information)
{
Console.WriteLine(row);
}

_powerShell?.Dispose();
_runSpace?.Dispose();
Expand All @@ -62,22 +65,25 @@ public void InvokeValidateCommandLine()
InitialCatalog = "abc"
}.ToString();

var from = GetType().Assembly.Location;
var from1 = GetType().Assembly.Location;
var from2 = Path.GetDirectoryName(from1);

_invokeSqlDatabase.Parameters.Add(nameof(ExecuteCmdLet.Database), dataBase);
_invokeSqlDatabase.Parameters.Add(nameof(ExecuteCmdLet.From), from);
_invokeSqlDatabase.Parameters.Add(nameof(ExecuteCmdLet.Transaction), TransactionMode.PerStep.ToString());
_invokeSqlDatabase.Parameters.Add(nameof(ExecuteCmdLet.Var), new[] { "x=1", "y=2" });
_invokeSqlDatabase.Parameters.Add(nameof(SqlDatabaseCmdLet.Database), dataBase);
_invokeSqlDatabase.Parameters.Add(nameof(SqlDatabaseCmdLet.From), new[] { from1, from2 });
_invokeSqlDatabase.Parameters.Add(nameof(SqlDatabaseCmdLet.Transaction), TransactionMode.PerStep.ToString());
_invokeSqlDatabase.Parameters.Add(nameof(SqlDatabaseCmdLet.Var), new[] { "x=1", "y=2" });

_powerShell.Invoke();

Assert.AreEqual(1, _commandLines.Count);
var commandLine = _commandLines[0];

Assert.IsNotNull(commandLine);
Assert.AreEqual(Configuration.Command.Upgrade, commandLine.Command);
Assert.AreEqual(dataBase, commandLine.Connection.ToString());
Assert.AreEqual(1, commandLine.Scripts.Count);
Assert.AreEqual(from, commandLine.Scripts[0]);
Assert.AreEqual(2, commandLine.Scripts.Count);
Assert.AreEqual(from1, commandLine.Scripts[0]);
Assert.AreEqual(from2, commandLine.Scripts[1]);
Assert.AreEqual(TransactionMode.PerStep, commandLine.Transaction);

CollectionAssert.AreEquivalent(new[] { "x", "y" }, commandLine.Variables.Keys);
Expand All @@ -95,9 +101,9 @@ public void InvokeInPipeLine()
}.ToString();

var from1 = GetType().Assembly.Location;
var from2 = typeof(ExecuteCmdLet).Assembly.Location;
var from2 = typeof(SqlDatabaseCmdLet).Assembly.Location;

_invokeSqlDatabase.Parameters.Add(nameof(ExecuteCmdLet.Database), dataBase);
_invokeSqlDatabase.Parameters.Add(nameof(SqlDatabaseCmdLet.Database), dataBase);
_powerShell.Invoke(new[] { from1, from2 });

Assert.AreEqual(2, _commandLines.Count);
Expand All @@ -110,5 +116,13 @@ public void InvokeInPipeLine()
Assert.AreEqual(1, _commandLines[1].Scripts.Count);
Assert.AreEqual(from2, _commandLines[1].Scripts[0]);
}

private sealed class SomeSqlDatabaseCmdLet : SqlDatabaseCmdLet
{
public SomeSqlDatabaseCmdLet()
: base(Configuration.Command.Upgrade)
{
}
}
}
}
17 changes: 9 additions & 8 deletions Sources/SqlDatabase.PowerShell/CmdLetLogger.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
using System;
using System.Management.Automation;
using System.Management.Automation;
using SqlDatabase.Log;

namespace SqlDatabase.PowerShell
{
internal sealed class CmdLetLogger : ILogger
internal sealed class CmdLetLogger : LoggerBase
{
private readonly Cmdlet _owner;
private readonly PSCmdlet _owner;

public CmdLetLogger(Cmdlet owner)
public CmdLetLogger(PSCmdlet owner)
{
_owner = owner;
}

public void Error(string message)
protected override void WriteError(string message)
{
_owner.Host.UI.WriteErrorLine(message);
}

public void Info(string message)
protected override void WriteInfo(string message)
{
throw new NotImplementedException();
_owner.Host.UI.WriteLine(message);
}
}
}
14 changes: 14 additions & 0 deletions Sources/SqlDatabase.PowerShell/CreateCmdLet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Management.Automation;
using SqlDatabase.Configuration;

namespace SqlDatabase.PowerShell
{
[Cmdlet(nameof(Command.Create), "SqlDatabase")]
public sealed class CreateCmdLet : SqlDatabaseCmdLet
{
public CreateCmdLet()
: base(Command.Create)
{
}
}
}
49 changes: 5 additions & 44 deletions Sources/SqlDatabase.PowerShell/ExecuteCmdLet.cs
Original file line number Diff line number Diff line change
@@ -1,53 +1,14 @@
using System.IO;
using System.Management.Automation;
using System.Management.Automation;
using SqlDatabase.Configuration;

namespace SqlDatabase.PowerShell
{
[Cmdlet(VerbsLifecycle.Invoke, "SqlDatabase")]
public sealed class ExecuteCmdLet : Cmdlet
[Cmdlet(nameof(Command.Execute), "SqlDatabase")]
public sealed class ExecuteCmdLet : SqlDatabaseCmdLet
{
[Parameter(Mandatory = true, Position = 1, HelpMessage = "Connection string to target database.")]
[Alias("d")]
public string Database { get; set; }

[Parameter(Mandatory = true, Position = 2, ValueFromPipeline = true, HelpMessage = "Scripts file.")]
[Alias("f")]
public FileInfo From { get; set; }

[Parameter(Position = 3, HelpMessage = "Transaction mode. Possible values: none, perStep. Default is none.")]
[Alias("t")]
public TransactionMode Transaction { get; set; }

[Parameter(ValueFromRemainingArguments = true, HelpMessage = "set a variable in format \"[name of variable]=[value of variable]\".")]
[Alias("v")]
public string[] Var { get; set; }

// only for tests
internal static ISqlDatabaseProgram Program { get; set; }

protected override void ProcessRecord()
{
var cmd = new CommandLineBuilder()
.SetCommand(Command.Execute)
.SetConnection(Database)
.SetTransaction(Transaction)
.SetScripts(From.FullName);

if (Var != null && Var.Length > 0)
{
foreach (var value in Var)
{
cmd.SetVariable(value);
}
}

ResolveProgram().ExecuteCommand(cmd.Build());
}

private static ISqlDatabaseProgram ResolveProgram()
public ExecuteCmdLet()
: base(Command.Execute)
{
return Program ?? new SqlDatabaseProgram();
}
}
}
2 changes: 1 addition & 1 deletion Sources/SqlDatabase.PowerShell/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
## Installation

```bash
$ Import-Module .\SqlDatabase.PowerShell.dll
$ Import-Module .\SqlDatabase.PowerShell.dll -DisableNameChecking
```

## Execute script
Expand Down
6 changes: 6 additions & 0 deletions Sources/SqlDatabase.PowerShell/SqlDatabase.PowerShell.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,10 @@
<ProjectReference Include="..\SqlDatabase\SqlDatabase.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="SqlDatabase.PowerShell.psd1">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Binary file modified Sources/SqlDatabase.PowerShell/SqlDatabase.PowerShell.psd1
Binary file not shown.
62 changes: 62 additions & 0 deletions Sources/SqlDatabase.PowerShell/SqlDatabaseCmdlet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System.Management.Automation;
using SqlDatabase.Configuration;

namespace SqlDatabase.PowerShell
{
public abstract class SqlDatabaseCmdLet : PSCmdlet
{
private readonly Command _command;

protected SqlDatabaseCmdLet(Command command)
{
_command = command;
}

[Parameter(Mandatory = true, Position = 1, HelpMessage = "Connection string to target database.")]
[Alias("d")]
public string Database { get; set; }

[Parameter(Mandatory = true, Position = 2, ValueFromPipeline = true, HelpMessage = "Scripts file.")]
[Alias("f")]
public string[] From { get; set; }

[Parameter(Position = 3, HelpMessage = "Transaction mode. Possible values: none, perStep. Default is none.")]
[Alias("t")]
public TransactionMode Transaction { get; set; }

[Parameter(ValueFromRemainingArguments = true, HelpMessage = "set a variable in format \"[name of variable]=[value of variable]\".")]
[Alias("v")]
public string[] Var { get; set; }

// only for tests
internal static ISqlDatabaseProgram Program { get; set; }

protected override void ProcessRecord()
{
var cmd = new CommandLineBuilder()
.SetCommand(_command)
.SetConnection(Database)
.SetTransaction(Transaction);

foreach (var from in From)
{
cmd.SetScripts(from);
}

if (Var != null && Var.Length > 0)
{
foreach (var value in Var)
{
cmd.SetVariable(value);
}
}

ResolveProgram().ExecuteCommand(cmd.Build());
}

private ISqlDatabaseProgram ResolveProgram()
{
return Program ?? new SqlDatabaseProgram(this);
}
}
}
13 changes: 11 additions & 2 deletions Sources/SqlDatabase.PowerShell/SqlDatabaseProgram.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
using SqlDatabase.Configuration;
using System.Management.Automation;
using SqlDatabase.Configuration;

namespace SqlDatabase.PowerShell
{
internal sealed class SqlDatabaseProgram : ISqlDatabaseProgram
{
private readonly PSCmdlet _owner;

public SqlDatabaseProgram(PSCmdlet owner)
{
_owner = owner;
}

public void ExecuteCommand(CommandLine command)
{
Program.ExecuteCommand(command);
var logger = new CmdLetLogger(_owner);
Program.ExecuteCommand(command, logger);
}
}
}
14 changes: 14 additions & 0 deletions Sources/SqlDatabase.PowerShell/UpgradeCmdLet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Management.Automation;
using SqlDatabase.Configuration;

namespace SqlDatabase.PowerShell
{
[Cmdlet(nameof(Command.Upgrade), "SqlDatabase")]
public sealed class UpgradeCmdLet : SqlDatabaseCmdLet
{
public UpgradeCmdLet()
: base(Command.Upgrade)
{
}
}
}
22 changes: 0 additions & 22 deletions Sources/SqlDatabase/ConsoleLogger.cs

This file was deleted.

Loading

0 comments on commit fd248d4

Please sign in to comment.