Skip to content

Commit

Permalink
NuGet Commands: Drop-Database
Browse files Browse the repository at this point in the history
Resolves #2476
  • Loading branch information
bricelam committed Mar 29, 2016
1 parent 21b8a21 commit 03f95a2
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ public DbContextOperations(
_runtimeServices = startup.ConfigureServices();
}

public virtual void DropDatabase([CanBeNull] string contextName, [NotNull] Func<string, bool> confirmCheck)
public virtual void DropDatabase([CanBeNull] string contextType, [NotNull] Func<string, string, bool> confirmCheck)
{
using (var context = CreateContext(contextName))
using (var context = CreateContext(contextType))
{
if (confirmCheck(
$"Are you sure you want to drop the database '{context.Database.GetDbConnection().Database}' on server '{context.Database.GetDbConnection().DataSource}'? (y/N)"))
var connection = context.Database.GetDbConnection();
if (confirmCheck(connection.Database, connection.DataSource))
{
context.Database.EnsureDeleted();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,27 @@ private IEnumerable<string> ReverseEngineerImpl(
}
}

public class DropDatabase : OperationBase
{
public DropDatabase(
[NotNull] OperationExecutor executor,
[NotNull] object resultHandler,
[NotNull] IDictionary args)
: base(resultHandler)
{
Check.NotNull(executor, nameof(executor));
Check.NotNull(args, nameof(args));

var contextType = (string)args["contextType"];
var confirmCheck = (Func<string, string, bool>)args["confirmCheck"];

Execute(() => executor.DropDatabaseImpl(contextType, confirmCheck));
}
}

private void DropDatabaseImpl(string contextType, Func<string, string, bool> confirmCheck)
=> _contextOperations.Value.DropDatabase(contextType, confirmCheck);

public abstract class OperationBase : MarshalByRefObject
{
private readonly IOperationResultHandler _resultHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\tools\Resources.cs">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@
'Script-Migration',
'Remove-Migration',
'Enable-Migrations',
'Scaffold-DbContext'
'Scaffold-DbContext',
'Drop-Database'
)

# Cmdlets to export from this module
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function Use-DbContext {
if ($candidates.length -gt 1 -and $exactMatch -is "String") {
$candidates = $exactMatch
}

if ($candidates.length -lt 1) {
throw "No DbContext named '$Context' was found"
} elseif ($candidates.length -gt 1 -and !($candidates -is "String")) {
Expand Down Expand Up @@ -498,7 +498,7 @@ function Scaffold-DbContext {

$artifacts | %{ $dteProject.ProjectItems.AddFromFile($_) | Out-Null }
$DTE.ItemOperations.OpenFile($artifacts[0]) | Out-Null

ShowConsole
}
}
Expand All @@ -512,6 +512,70 @@ function Enable-Migrations {
Write-Warning 'Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.'
}

#
# Drop-Database
#

Register-TabExpansion Drop-Database @{
Context = { param ($tabExpansionContext) GetContextTypes $tabExpansionContext.Project $tabExpansionContext.StartupProject $tabExpansionContext.Environment }
Project = { GetProjects }
StartupProject = { GetProjects }
}

<#
.SYNOPSIS
Drops the database.
.DESCRIPTION
Drops the database.
.PARAMETER Context
Specifies the DbContext to use. If omitted, the default DbContext is used.
.PARAMETER Project
Specifies the project to use. If omitted, the default project is used.
.PARAMETER StartupProject
Specifies the startup project to use. If omitted, the solution's startup project is used.
.PARAMETER Environment
Specifies the environment to use. If omitted, "Development" is used.
.LINK
about_EntityFramework
#>
function Drop-Database {
[CmdletBinding(ConfirmImpact = 'High', SupportsShouldProcess = $true, PositionalBinding = $false)]
param (
[string] $Context,
[string] $Project,
[string] $StartupProject,
[string] $Environment)

$values = ProcessCommonParameters $StartupProject $Project $Context
$dteStartupProject = $values.StartupProject
$dteProject = $values.Project
$contextTypeName = $values.ContextTypeName

if (IsDotNetProject $dteProject) {
# TODO: Show database information
if ($PSCmdlet.ShouldProcess('the database')) {
$options = ProcessCommonDotnetParameters $dteProject $dteStartupProject $Environment $contextTypeName
$options += "--force"
InvokeDotNetEf $dteProject database drop @options | Out-Null
}
} else {
InvokeOperation $dteStartupProject $Environment $dteProject DropDatabase @{
contextType = $contextTypeName
confirmCheck = [Func[string, string, bool]]{
param ($database, $dataSource)

return $PSCmdlet.ShouldProcess("$database on $dataSource")
}
}
}
}

#
# (Private Helpers)
#
Expand All @@ -535,7 +599,7 @@ function GetContextTypes($projectName, $startupProjectName, $environment) {
$project = $values.Project

if (IsDotNetProject $startupProject) {
$types = InvokeDotNetEf $startupProject -Json dbcontext list
$types = InvokeDotNetEf $startupProject -Json dbcontext list
return $types | %{ $_.fullName }
} else {
$contextTypes = InvokeOperation $startupProject $environment $project GetContextTypes -skipBuild
Expand Down Expand Up @@ -640,7 +704,7 @@ function InvokeDotNetEf($project, [switch] $Json) {
$arguments += "--json"
} else {
# TODO better json output parsing so we don't need to suppress verbose output
$arguments = ,"--verbose" + $arguments
$arguments = ,"--verbose" + $arguments
}
$command = "ef $($arguments -join ' ')"
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ LONG DESCRIPTION
-------------------------- ---------------------------------------------------
Add-Migration Adds a new migration.

Drop-Database Drops the database.

Remove-Migration Removes the last migration.

Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database.
Expand All @@ -34,6 +36,7 @@ LONG DESCRIPTION

SEE ALSO
Add-Migration
Drop-Database
Remove-Migration
Scaffold-DbContext
Script-Migration
Expand Down
2 changes: 1 addition & 1 deletion src/dotnet-ef/DatabaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static void Configure([NotNull] CommandLineApplication command)
command.VerboseOption();

command.Command("update", DatabaseUpdateCommand.Configure);
command.Command("delete", DatabaseDeleteCommand.Configure);
command.Command("drop", DatabaseDropCommand.Configure);

command.OnExecute(() => command.ShowHelp());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@

namespace Microsoft.EntityFrameworkCore.Commands
{
public class DatabaseDeleteCommand
public class DatabaseDropCommand
{
public static void Configure([NotNull] CommandLineApplication command)
{
command.Description = "Drop the database for specific enviroment";
command.Description = "Drop the database for specific environment";

var startupProject = command.Option(
"-s|--startup-project <project>",
Expand All @@ -39,12 +39,18 @@ private static int Execute(string context, string startupProject, string environ
new OperationExecutor(startupProject, environment)
.DropDatabase(
context,
message =>
(database, dataSource) =>
{
Reporter.Output.WriteLine(message);
if (isForced)
{
return true;
}

Reporter.Output.WriteLine(
$"Are you sure you want to drop the database '{database}' on server '{dataSource}'? (y/N)");
var readedKey = Console.ReadKey().KeyChar;

return isForced || (readedKey == 'y') || (readedKey == 'Y');
return (readedKey == 'y') || (readedKey == 'Y');
});

return 0;
Expand Down
4 changes: 1 addition & 3 deletions src/dotnet-ef/OperationExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.ProjectModel.Loader;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Design.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations.Design;
using Microsoft.EntityFrameworkCore.Scaffolding.Internal;
using Microsoft.Extensions.PlatformAbstractions;
Expand Down Expand Up @@ -121,7 +119,7 @@ public OperationExecutor([CanBeNull] string startupProject, [CanBeNull] string e
rootNamespace));
}

public virtual void DropDatabase([CanBeNull] string contextName, [NotNull] Func<string, bool> confirmCheck)
public virtual void DropDatabase([CanBeNull] string contextName, [NotNull] Func<string, string, bool> confirmCheck)
=> _contextOperations.Value.DropDatabase(contextName, confirmCheck);

public virtual MigrationFiles AddMigration(
Expand Down

0 comments on commit 03f95a2

Please sign in to comment.