|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System.CommandLine; |
| 5 | +using System.CommandLine.Parsing; |
| 6 | +using Azure.Mcp.Core.Commands; |
| 7 | +using Azure.Mcp.Core.Extensions; |
| 8 | +using Azure.Mcp.Core.Models.Command; |
| 9 | +using Azure.Mcp.Tools.Sql.Commands; |
| 10 | +using Azure.Mcp.Tools.Sql.Models; |
| 11 | +using Azure.Mcp.Tools.Sql.Options; |
| 12 | +using Azure.Mcp.Tools.Sql.Options.Database; |
| 13 | +using Azure.Mcp.Tools.Sql.Services; |
| 14 | +using Azure.ResourceManager.Sql.Models; |
| 15 | +using Microsoft.Extensions.Logging; |
| 16 | + |
| 17 | +namespace Azure.Mcp.Tools.Sql.Commands.Database; |
| 18 | + |
| 19 | +public sealed class DatabaseExportCommand(ILogger<DatabaseExportCommand> logger) |
| 20 | + : BaseDatabaseCommand<DatabaseExportOptions>(logger) |
| 21 | +{ |
| 22 | + private const string CommandTitle = "Export SQL Database"; |
| 23 | + |
| 24 | + public override string Name => "export"; |
| 25 | + |
| 26 | + public override string Description => |
| 27 | + """ |
| 28 | + Export an Azure SQL Database to a BACPAC file in Azure Storage. This command creates a logical backup |
| 29 | + of the database schema and data that can be used for archiving or migration purposes. The export |
| 30 | + operation is equivalent to 'az sql db export'. Returns export operation information including status. |
| 31 | + """; |
| 32 | + |
| 33 | + public override string Title => CommandTitle; |
| 34 | + |
| 35 | + public override ToolMetadata Metadata => new() |
| 36 | + { |
| 37 | + Destructive = false, |
| 38 | + Idempotent = false, |
| 39 | + OpenWorld = false, |
| 40 | + ReadOnly = true, |
| 41 | + LocalRequired = false, |
| 42 | + Secret = true |
| 43 | + }; |
| 44 | + |
| 45 | + protected override void RegisterOptions(Command command) |
| 46 | + { |
| 47 | + base.RegisterOptions(command); |
| 48 | + command.Options.Add(SqlOptionDefinitions.StorageUriOption); |
| 49 | + command.Options.Add(SqlOptionDefinitions.StorageKeyOption); |
| 50 | + command.Options.Add(SqlOptionDefinitions.StorageKeyTypeOption); |
| 51 | + command.Options.Add(SqlOptionDefinitions.AdminUserOption); |
| 52 | + command.Options.Add(SqlOptionDefinitions.AdminPasswordOption); |
| 53 | + command.Options.Add(SqlOptionDefinitions.AuthTypeOption); |
| 54 | + } |
| 55 | + |
| 56 | + protected override DatabaseExportOptions BindOptions(ParseResult parseResult) |
| 57 | + { |
| 58 | + var options = base.BindOptions(parseResult); |
| 59 | + options.StorageUri = parseResult.GetValueOrDefault(SqlOptionDefinitions.StorageUriOption); |
| 60 | + options.StorageKey = parseResult.GetValueOrDefault(SqlOptionDefinitions.StorageKeyOption); |
| 61 | + options.StorageKeyType = parseResult.GetValueOrDefault(SqlOptionDefinitions.StorageKeyTypeOption); |
| 62 | + options.AdminUser = parseResult.GetValueOrDefault(SqlOptionDefinitions.AdminUserOption); |
| 63 | + options.AdminPassword = parseResult.GetValueOrDefault(SqlOptionDefinitions.AdminPasswordOption); |
| 64 | + options.AuthType = parseResult.GetValueOrDefault(SqlOptionDefinitions.AuthTypeOption); |
| 65 | + return options; |
| 66 | + } |
| 67 | + |
| 68 | + public override async Task<CommandResponse> ExecuteAsync(CommandContext context, ParseResult parseResult) |
| 69 | + { |
| 70 | + if (!Validate(parseResult.CommandResult, context.Response).IsValid) |
| 71 | + { |
| 72 | + return context.Response; |
| 73 | + } |
| 74 | + |
| 75 | + var options = BindOptions(parseResult); |
| 76 | + |
| 77 | + // Additional validation for export-specific parameters |
| 78 | + if (string.IsNullOrEmpty(options.StorageUri)) |
| 79 | + { |
| 80 | + context.Response.Status = 400; |
| 81 | + context.Response.Message = "Storage URI is required for database export."; |
| 82 | + return context.Response; |
| 83 | + } |
| 84 | + |
| 85 | + if (string.IsNullOrEmpty(options.StorageKey)) |
| 86 | + { |
| 87 | + context.Response.Status = 400; |
| 88 | + context.Response.Message = "Storage key is required for database export."; |
| 89 | + return context.Response; |
| 90 | + } |
| 91 | + |
| 92 | + if (string.IsNullOrEmpty(options.StorageKeyType)) |
| 93 | + { |
| 94 | + context.Response.Status = 400; |
| 95 | + context.Response.Message = "Storage key type is required for database export."; |
| 96 | + return context.Response; |
| 97 | + } |
| 98 | + |
| 99 | + if (string.IsNullOrEmpty(options.AdminUser)) |
| 100 | + { |
| 101 | + context.Response.Status = 400; |
| 102 | + context.Response.Message = "Administrator user is required for database export."; |
| 103 | + return context.Response; |
| 104 | + } |
| 105 | + |
| 106 | + if (string.IsNullOrEmpty(options.AdminPassword)) |
| 107 | + { |
| 108 | + context.Response.Status = 400; |
| 109 | + context.Response.Message = "Administrator password is required for database export."; |
| 110 | + return context.Response; |
| 111 | + } |
| 112 | + |
| 113 | + // Validate storage key type |
| 114 | + var validStorageKeyTypes = new[] { "StorageAccessKey", "SharedAccessKey", "ManagedIdentity" }; |
| 115 | + if (!validStorageKeyTypes.Contains(options.StorageKeyType, StringComparer.OrdinalIgnoreCase)) |
| 116 | + { |
| 117 | + context.Response.Status = 400; |
| 118 | + context.Response.Message = $"Invalid storage key type '{options.StorageKeyType}'. Valid values are: {string.Join(", ", validStorageKeyTypes)}"; |
| 119 | + return context.Response; |
| 120 | + } |
| 121 | + |
| 122 | + // Validate storage URI format |
| 123 | + if (!Uri.TryCreate(options.StorageUri, UriKind.Absolute, out _)) |
| 124 | + { |
| 125 | + context.Response.Status = 400; |
| 126 | + context.Response.Message = "Storage URI must be a valid absolute URI."; |
| 127 | + return context.Response; |
| 128 | + } |
| 129 | + |
| 130 | + // Validate authentication type if provided |
| 131 | + if (!string.IsNullOrEmpty(options.AuthType)) |
| 132 | + { |
| 133 | + var validAuthTypes = new[] { "SQL", "ADPassword", "ManagedIdentity" }; |
| 134 | + if (!validAuthTypes.Contains(options.AuthType, StringComparer.OrdinalIgnoreCase)) |
| 135 | + { |
| 136 | + context.Response.Status = 400; |
| 137 | + context.Response.Message = $"Invalid authentication type '{options.AuthType}'. Valid values are: {string.Join(", ", validAuthTypes)}"; |
| 138 | + return context.Response; |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + try |
| 143 | + { |
| 144 | + var sqlService = context.GetService<ISqlService>(); |
| 145 | + |
| 146 | + var exportResult = await sqlService.ExportDatabaseAsync( |
| 147 | + options.Server!, |
| 148 | + options.Database!, |
| 149 | + options.ResourceGroup!, |
| 150 | + options.Subscription!, |
| 151 | + options.StorageUri!, |
| 152 | + options.StorageKey!, |
| 153 | + options.StorageKeyType!, |
| 154 | + options.AdminUser!, |
| 155 | + options.AdminPassword!, |
| 156 | + options.AuthType, |
| 157 | + options.RetryPolicy); |
| 158 | + |
| 159 | + context.Response.Results = ResponseResult.Create( |
| 160 | + new DatabaseExportResult(exportResult), |
| 161 | + SqlJsonContext.Default.DatabaseExportResult); |
| 162 | + } |
| 163 | + catch (Exception ex) |
| 164 | + { |
| 165 | + _logger.LogError(ex, |
| 166 | + "Error exporting SQL database. Server: {Server}, Database: {Database}, ResourceGroup: {ResourceGroup}, StorageUri: {StorageUri}", |
| 167 | + options.Server, options.Database, options.ResourceGroup, options.StorageUri); |
| 168 | + HandleException(context, ex); |
| 169 | + } |
| 170 | + |
| 171 | + return context.Response; |
| 172 | + } |
| 173 | + |
| 174 | + protected override string GetErrorMessage(Exception ex) => ex switch |
| 175 | + { |
| 176 | + RequestFailedException reqEx when reqEx.Status == 404 => |
| 177 | + "SQL database or server not found. Verify the database name, server name, resource group, and that you have access.", |
| 178 | + RequestFailedException reqEx when reqEx.Status == 403 => |
| 179 | + $"Authorization failed exporting the SQL database. Verify you have appropriate permissions and the storage account is accessible. Details: {reqEx.Message}", |
| 180 | + RequestFailedException reqEx when reqEx.Status == 400 => |
| 181 | + $"Invalid export parameters. Check your storage URI, credentials, and database configuration. Details: {reqEx.Message}", |
| 182 | + ArgumentException argEx => |
| 183 | + $"Invalid argument: {argEx.Message}", |
| 184 | + RequestFailedException reqEx => reqEx.Message, |
| 185 | + _ => base.GetErrorMessage(ex) |
| 186 | + }; |
| 187 | + |
| 188 | + internal record DatabaseExportResult(SqlDatabaseExportResult ExportResult); |
| 189 | +} |
0 commit comments