From c94602c52534255a4f7b91dbfb56383592c721d8 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 2 Oct 2018 18:06:42 -0700 Subject: [PATCH 01/38] [WIP] New schema for 2017-preview API --- azurerm/config.go | 6 + azurerm/provider.go | 1 + azurerm/resource_arm_sql2017_elasticpool.go | 346 ++ .../2018-03-01-preview/management/models.go | 6 + .../sql/backupshorttermretentionpolicies.go | 368 ++ .../2017-10-01-preview/sql/capabilities.go | 111 + .../sql/mgmt/2017-10-01-preview/sql/client.go | 52 + .../sql/databaseoperations.go | 212 ++ .../mgmt/2017-10-01-preview/sql/databases.go | 844 +++++ .../databasevulnerabilityassessmentscans.go | 365 ++ .../sql/elasticpooloperations.go | 210 ++ .../2017-10-01-preview/sql/elasticpools.go | 447 +++ .../sql/instancefailovergroups.go | 518 +++ .../sql/managedinstancetdecertificates.go | 125 + .../sql/mgmt/2017-10-01-preview/sql/models.go | 3162 +++++++++++++++++ .../2017-10-01-preview/sql/tdecertificates.go | 124 + .../mgmt/2017-10-01-preview/sql/version.go | 30 + vendor/vendor.json | 18 +- 18 files changed, 6940 insertions(+), 5 deletions(-) create mode 100644 azurerm/resource_arm_sql2017_elasticpool.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/backupshorttermretentionpolicies.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/capabilities.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databaseoperations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databases.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databasevulnerabilityassessmentscans.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpooloperations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpools.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/instancefailovergroups.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancetdecertificates.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/tdecertificates.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/version.go diff --git a/azurerm/config.go b/azurerm/config.go index 20d72f8e6505..a70562e99593 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -41,6 +41,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/operationsmanagement/mgmt/2015-11-01-preview/operationsmanagement" "github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2015-05-01-preview/sql" + sql2017 "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis" "github.com/Azure/azure-sdk-for-go/services/relay/mgmt/2017-04-01/relay" @@ -156,6 +157,7 @@ type ArmClient struct { sqlDatabasesClient sql.DatabasesClient sqlDatabaseThreatDetectionPoliciesClient sql.DatabaseThreatDetectionPoliciesClient sqlElasticPoolsClient sql.ElasticPoolsClient + sql2017ElasticPoolsClient sql2017.ElasticPoolsClient sqlFirewallRulesClient sql.FirewallRulesClient sqlServersClient sql.ServersClient sqlServerAzureADAdministratorsClient sql.ServerAzureADAdministratorsClient @@ -679,6 +681,10 @@ func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth auto c.configureClient(&sqlEPClient.Client, auth) c.sqlElasticPoolsClient = sqlEPClient + sql2017EPClient := sql2017.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&sql2017EPClient.Client, auth) + c.sql2017ElasticPoolsClient = sql2017EPClient + sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&sqlSrvClient.Client, auth) c.sqlServersClient = sqlSrvClient diff --git a/azurerm/provider.go b/azurerm/provider.go index 739e563c86f0..2e6485aa33cb 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -250,6 +250,7 @@ func Provider() terraform.ResourceProvider { "azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(), "azurerm_sql_database": resourceArmSqlDatabase(), "azurerm_sql_elasticpool": resourceArmSqlElasticPool(), + "azurerm_sql2017_elasticpool": resourceArmSql2017ElasticPool(), "azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), "azurerm_sql_active_directory_administrator": resourceArmSqlAdministrator(), "azurerm_sql_server": resourceArmSqlServer(), diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go new file mode 100644 index 000000000000..503b6cdd7f55 --- /dev/null +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -0,0 +1,346 @@ +package azurerm + +import ( + "fmt" + "log" + "time" + + "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmSql2017ElasticPool() *schema.Resource { + return &schema.Resource{ + Create: resourceArmSql2017ElasticPoolCreate, + Read: resourceArmSql2017ElasticPoolRead, + Update: resourceArmSql2017ElasticPoolCreate, + Delete: resourceArmSql2017ElasticPoolDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": locationSchema(), + + "resource_group_name": resourceGroupNameSchema(), + + "id": { + Type: schema.TypeString, + Required: false, + Computed: true, + }, + + "kind": { + Type: schema.TypeString, + Required: false, + Computed: true, + }, + + "type": { + Type: schema.TypeString, + Required: false, + Computed: true, + }, + + "server_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "sku": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "B_Gen4_1", + "B_Gen4_2", + "B_Gen5_1", + "B_Gen5_2", + "GP_Gen4_2", + "GP_Gen4_4", + "GP_Gen4_8", + "GP_Gen4_16", + "GP_Gen4_32", + "GP_Gen5_2", + "GP_Gen5_4", + "GP_Gen5_8", + "GP_Gen5_16", + "GP_Gen5_32", + "MO_Gen5_2", + "MO_Gen5_4", + "MO_Gen5_8", + "MO_Gen5_16", + }, true), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + + "capacity": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validateIntInSlice([]int{ + 1, + 2, + 4, + 8, + 16, + 32, + }), + }, + + "size": { + Type: schema.TypeString, + Required: false, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + + "tier": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "Basic", + "GeneralPurpose", + "MemoryOptimized", + }, true), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + + "family": { + Type: schema.TypeString, + Required: false, + ValidateFunc: validation.StringInSlice([]string{ + "Gen4", + "Gen5", + }, true), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + }, + }, + }, + + "properties": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "state": { + Type: schema.TypeInt, + Required: false, + }, + + "creation_date": { + Type: schema.TypeString, + Computed: true, + }, + + "max_size_bytes": { + Type: schema.TypeInt, + Required: false, + }, + + "per_database_settings": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "min_capacity": { + Type: schema.TypeFloat, + Required: true, + }, + + "max_capacity": { + Type: schema.TypeFloat, + Required: true, + }, + }, + }, + }, + + "zone_redundant": { + Type: schema.TypeBool, + Required: false, + }, + + "license_type": { + Type: schema.TypeString, + Required: false, + ValidateFunc: validation.StringInSlice([]string{ + "BasicPrice", + "LicenseIncluded", + }, true), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + }, + }, + }, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).sql2017ElasticPoolsClient + ctx := meta.(*ArmClient).StopContext + + log.Printf("[INFO] preparing arguments for SQL2017 ElasticPool creation.") + + elasticPoolName := d.Get("name").(string) + serverName := d.Get("server_name").(string) + location := azureRMNormalizeLocation(d.Get("location").(string)) + resGroup := d.Get("resource_group_name").(string) + sku := expandAzureRmSql2017ElasticPoolSku(d) + properties := expandAzureRmSql2017ElasticPoolProperties(d) + + elasticPool := sql.ElasticPool{ + Name: &elasticPoolName, + Location: &location, + ElasticPoolProperties: expandAzureRmSql2017ElasticPoolProperties(d), + } + + future, err := client.CreateOrUpdate(ctx, resGroup, serverName, elasticPoolName, elasticPool) + if err != nil { + return err + } + + err = future.WaitForCompletionRef(ctx, client.Client) + if err != nil { + return err + } + + read, err := client.Get(ctx, resGroup, serverName, elasticPoolName) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read SQL2017 ElasticPool %q (resource group %q) ID", elasticPoolName, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmSql2017ElasticPoolRead(d, meta) +} + +func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).sqlElasticPoolsClient + ctx := meta.(*ArmClient).StopContext + + resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, resGroup, serverName, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return nil + } + return fmt.Errorf("Error making Read request on Sql Elastic Pool %s: %s", name, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resGroup) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + d.Set("server_name", serverName) + + if elasticPool := resp.ElasticPoolProperties; elasticPool != nil { + d.Set("edition", string(elasticPool.Edition)) + d.Set("dtu", int(*elasticPool.Dtu)) + d.Set("db_dtu_min", int(*elasticPool.DatabaseDtuMin)) + d.Set("db_dtu_max", int(*elasticPool.DatabaseDtuMax)) + d.Set("pool_size", int(*elasticPool.StorageMB)) + + if date := elasticPool.CreationDate; date != nil { + d.Set("creation_date", date.Format(time.RFC3339)) + } + } + + return nil +} + +func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).sqlElasticPoolsClient + ctx := meta.(*ArmClient).StopContext + + resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) + if err != nil { + return err + } + + _, err = client.Delete(ctx, resGroup, serverName, name) + + return err +} + +func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { + edition := sql.ElasticPoolEdition(d.Get("edition").(string)) + dtu := int32(d.Get("dtu").(int)) + + props := &sql.ElasticPoolProperties{ + Edition: edition, + Dtu: &dtu, + } + + if databaseDtuMin, ok := d.GetOk("db_dtu_min"); ok { + databaseDtuMin := int32(databaseDtuMin.(int)) + props.DatabaseDtuMin = &databaseDtuMin + } + + if databaseDtuMax, ok := d.GetOk("db_dtu_max"); ok { + databaseDtuMax := int32(databaseDtuMax.(int)) + props.DatabaseDtuMax = &databaseDtuMax + } + + if poolSize, ok := d.GetOk("pool_size"); ok { + poolSize := int32(poolSize.(int)) + props.StorageMB = &poolSize + } + + return props +} + +func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { + id, err := parseAzureResourceID(sqlElasticPoolId) + if err != nil { + return "", "", "", fmt.Errorf("[ERROR] Unable to parse SQL ElasticPool ID %q: %+v", sqlElasticPoolId, err) + } + + return id.ResourceGroup, id.Path["servers"], id.Path["elasticPools"], nil +} + +func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { + skus := d.Get("sku").([]interface{}) + sku := skus[0].(map[string]interface{}) + + name := sku["name"].(string) + size := sku["size"].(string) + tier := sku["tier"].(string) + family := sku["family"].(string) + capacity := sku["capacity"].(int) + + return &sql.Sku{ + Name: utils.String(name), + size: utils.String(size), + Tier: utils.String(tier), + Family: utils.String(family), + Capacity: utils.Int32(int32(capacity)), + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management/models.go index e422a4054093..29e4166d6620 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management/models.go @@ -591,6 +591,10 @@ type EntityInfoProperties struct { // InheritedPermissions - Possible values include: 'Noaccess', 'View', 'Edit', 'Delete' InheritedPermissions InheritedPermissions `json:"inheritedPermissions,omitempty"` NumberOfDescendants *int32 `json:"numberOfDescendants,omitempty"` + // NumberOfChildren - Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. + NumberOfChildren *int32 `json:"numberOfChildren,omitempty"` + // NumberOfChildGroups - Number of child groups is the number of Groups that are exactly one level underneath the current Group. + NumberOfChildGroups *int32 `json:"numberOfChildGroups,omitempty"` // ParentDisplayNameChain - The parent display name chain from the root group to the immediate parent ParentDisplayNameChain *[]string `json:"parentDisplayNameChain,omitempty"` // ParentNameChain - The parent name chain from the root group to the immediate parent @@ -602,6 +606,8 @@ type EntityListResult struct { autorest.Response `json:"-"` // Value - The list of entities. Value *[]EntityInfo `json:"value,omitempty"` + // Count - Total count of records that match the filter + Count *int32 `json:"count,omitempty"` // NextLink - The URL to use for getting the next set of results. NextLink *string `json:"nextLink,omitempty"` } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/backupshorttermretentionpolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/backupshorttermretentionpolicies.go new file mode 100644 index 000000000000..a9c2ff6ae899 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/backupshorttermretentionpolicies.go @@ -0,0 +1,368 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// BackupShortTermRetentionPoliciesClient is the the Azure SQL Database management API provides a RESTful set of web +// services that interact with Azure SQL Database services to manage your databases. The API enables you to create, +// retrieve, update, and delete databases. +type BackupShortTermRetentionPoliciesClient struct { + BaseClient +} + +// NewBackupShortTermRetentionPoliciesClient creates an instance of the BackupShortTermRetentionPoliciesClient client. +func NewBackupShortTermRetentionPoliciesClient(subscriptionID string) BackupShortTermRetentionPoliciesClient { + return NewBackupShortTermRetentionPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBackupShortTermRetentionPoliciesClientWithBaseURI creates an instance of the +// BackupShortTermRetentionPoliciesClient client. +func NewBackupShortTermRetentionPoliciesClientWithBaseURI(baseURI string, subscriptionID string) BackupShortTermRetentionPoliciesClient { + return BackupShortTermRetentionPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate updates a database's short term retention policy. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// parameters - the short term retention policy info. +func (client BackupShortTermRetentionPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters BackupShortTermRetentionPolicy) (result BackupShortTermRetentionPoliciesCreateOrUpdateFuture, err error) { + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serverName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client BackupShortTermRetentionPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters BackupShortTermRetentionPolicy) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "policyName": autorest.Encode("path", "default"), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/backupShortTermRetentionPolicies/{policyName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client BackupShortTermRetentionPoliciesClient) CreateOrUpdateSender(req *http.Request) (future BackupShortTermRetentionPoliciesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client BackupShortTermRetentionPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result BackupShortTermRetentionPolicy, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets a database's short term retention policy. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +func (client BackupShortTermRetentionPoliciesClient) Get(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result BackupShortTermRetentionPolicy, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client BackupShortTermRetentionPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "policyName": autorest.Encode("path", "default"), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/backupShortTermRetentionPolicies/{policyName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client BackupShortTermRetentionPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client BackupShortTermRetentionPoliciesClient) GetResponder(resp *http.Response) (result BackupShortTermRetentionPolicy, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByDatabase gets a database's short term retention policy. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +func (client BackupShortTermRetentionPoliciesClient) ListByDatabase(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result BackupShortTermRetentionPolicyListResultPage, err error) { + result.fn = client.listByDatabaseNextResults + req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "ListByDatabase", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.bstrplr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "ListByDatabase", resp, "Failure sending request") + return + } + + result.bstrplr, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "ListByDatabase", resp, "Failure responding to request") + } + + return +} + +// ListByDatabasePreparer prepares the ListByDatabase request. +func (client BackupShortTermRetentionPoliciesClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/backupShortTermRetentionPolicies", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDatabaseSender sends the ListByDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client BackupShortTermRetentionPoliciesClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always +// closes the http.Response Body. +func (client BackupShortTermRetentionPoliciesClient) ListByDatabaseResponder(resp *http.Response) (result BackupShortTermRetentionPolicyListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByDatabaseNextResults retrieves the next set of results, if any. +func (client BackupShortTermRetentionPoliciesClient) listByDatabaseNextResults(lastResults BackupShortTermRetentionPolicyListResult) (result BackupShortTermRetentionPolicyListResult, err error) { + req, err := lastResults.backupShortTermRetentionPolicyListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "listByDatabaseNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "listByDatabaseNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "listByDatabaseNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByDatabaseComplete enumerates all values, automatically crossing page boundaries as required. +func (client BackupShortTermRetentionPoliciesClient) ListByDatabaseComplete(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result BackupShortTermRetentionPolicyListResultIterator, err error) { + result.page, err = client.ListByDatabase(ctx, resourceGroupName, serverName, databaseName) + return +} + +// Update updates a database's short term retention policy. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// parameters - the short term retention policy info. +func (client BackupShortTermRetentionPoliciesClient) Update(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters BackupShortTermRetentionPolicy) (result BackupShortTermRetentionPoliciesUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, serverName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client BackupShortTermRetentionPoliciesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters BackupShortTermRetentionPolicy) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "policyName": autorest.Encode("path", "default"), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/backupShortTermRetentionPolicies/{policyName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client BackupShortTermRetentionPoliciesClient) UpdateSender(req *http.Request) (future BackupShortTermRetentionPoliciesUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client BackupShortTermRetentionPoliciesClient) UpdateResponder(resp *http.Response) (result BackupShortTermRetentionPolicy, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/capabilities.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/capabilities.go new file mode 100644 index 000000000000..24dadbca240b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/capabilities.go @@ -0,0 +1,111 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// CapabilitiesClient is the the Azure SQL Database management API provides a RESTful set of web services that interact +// with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, and +// delete databases. +type CapabilitiesClient struct { + BaseClient +} + +// NewCapabilitiesClient creates an instance of the CapabilitiesClient client. +func NewCapabilitiesClient(subscriptionID string) CapabilitiesClient { + return NewCapabilitiesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewCapabilitiesClientWithBaseURI creates an instance of the CapabilitiesClient client. +func NewCapabilitiesClientWithBaseURI(baseURI string, subscriptionID string) CapabilitiesClient { + return CapabilitiesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ListByLocation gets the subscription capabilities available for the specified location. +// Parameters: +// locationName - the location name whose capabilities are retrieved. +// include - if specified, restricts the response to only include the selected item. +func (client CapabilitiesClient) ListByLocation(ctx context.Context, locationName string, include CapabilityGroup) (result LocationCapabilities, err error) { + req, err := client.ListByLocationPreparer(ctx, locationName, include) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.CapabilitiesClient", "ListByLocation", nil, "Failure preparing request") + return + } + + resp, err := client.ListByLocationSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.CapabilitiesClient", "ListByLocation", resp, "Failure sending request") + return + } + + result, err = client.ListByLocationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.CapabilitiesClient", "ListByLocation", resp, "Failure responding to request") + } + + return +} + +// ListByLocationPreparer prepares the ListByLocation request. +func (client CapabilitiesClient) ListByLocationPreparer(ctx context.Context, locationName string, include CapabilityGroup) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "locationName": autorest.Encode("path", locationName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(string(include)) > 0 { + queryParameters["include"] = autorest.Encode("query", include) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/capabilities", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByLocationSender sends the ListByLocation request. The method will close the +// http.Response Body if it receives an error. +func (client CapabilitiesClient) ListByLocationSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByLocationResponder handles the response to the ListByLocation request. The method always +// closes the http.Response Body. +func (client CapabilitiesClient) ListByLocationResponder(resp *http.Response) (result LocationCapabilities, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/client.go new file mode 100644 index 000000000000..e912a0c72d6b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/client.go @@ -0,0 +1,52 @@ +// Package sql implements the Azure ARM Sql service API version 2017-10-01-preview. +// +// The Azure SQL Database management API provides a RESTful set of web services that interact with Azure SQL Database +// services to manage your databases. The API enables you to create, retrieve, update, and delete databases. +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Sql + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Sql. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databaseoperations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databaseoperations.go new file mode 100644 index 000000000000..4e678b2ed533 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databaseoperations.go @@ -0,0 +1,212 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/satori/go.uuid" + "net/http" +) + +// DatabaseOperationsClient is the the Azure SQL Database management API provides a RESTful set of web services that +// interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, +// and delete databases. +type DatabaseOperationsClient struct { + BaseClient +} + +// NewDatabaseOperationsClient creates an instance of the DatabaseOperationsClient client. +func NewDatabaseOperationsClient(subscriptionID string) DatabaseOperationsClient { + return NewDatabaseOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabaseOperationsClientWithBaseURI creates an instance of the DatabaseOperationsClient client. +func NewDatabaseOperationsClientWithBaseURI(baseURI string, subscriptionID string) DatabaseOperationsClient { + return DatabaseOperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Cancel cancels the asynchronous operation on the database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// operationID - the operation identifier. +func (client DatabaseOperationsClient) Cancel(ctx context.Context, resourceGroupName string, serverName string, databaseName string, operationID uuid.UUID) (result autorest.Response, err error) { + req, err := client.CancelPreparer(ctx, resourceGroupName, serverName, databaseName, operationID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "Cancel", nil, "Failure preparing request") + return + } + + resp, err := client.CancelSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "Cancel", resp, "Failure sending request") + return + } + + result, err = client.CancelResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "Cancel", resp, "Failure responding to request") + } + + return +} + +// CancelPreparer prepares the Cancel request. +func (client DatabaseOperationsClient) CancelPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, operationID uuid.UUID) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "operationId": autorest.Encode("path", operationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/operations/{operationId}/cancel", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CancelSender sends the Cancel request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseOperationsClient) CancelSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CancelResponder handles the response to the Cancel request. The method always +// closes the http.Response Body. +func (client DatabaseOperationsClient) CancelResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListByDatabase gets a list of operations performed on the database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +func (client DatabaseOperationsClient) ListByDatabase(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result DatabaseOperationListResultPage, err error) { + result.fn = client.listByDatabaseNextResults + req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "ListByDatabase", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.dolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "ListByDatabase", resp, "Failure sending request") + return + } + + result.dolr, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "ListByDatabase", resp, "Failure responding to request") + } + + return +} + +// ListByDatabasePreparer prepares the ListByDatabase request. +func (client DatabaseOperationsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/operations", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDatabaseSender sends the ListByDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseOperationsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always +// closes the http.Response Body. +func (client DatabaseOperationsClient) ListByDatabaseResponder(resp *http.Response) (result DatabaseOperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByDatabaseNextResults retrieves the next set of results, if any. +func (client DatabaseOperationsClient) listByDatabaseNextResults(lastResults DatabaseOperationListResult) (result DatabaseOperationListResult, err error) { + req, err := lastResults.databaseOperationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "listByDatabaseNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "listByDatabaseNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseOperationsClient", "listByDatabaseNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByDatabaseComplete enumerates all values, automatically crossing page boundaries as required. +func (client DatabaseOperationsClient) ListByDatabaseComplete(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result DatabaseOperationListResultIterator, err error) { + result.page, err = client.ListByDatabase(ctx, resourceGroupName, serverName, databaseName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databases.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databases.go new file mode 100644 index 000000000000..16347e571080 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databases.go @@ -0,0 +1,844 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// DatabasesClient is the the Azure SQL Database management API provides a RESTful set of web services that interact +// with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, and +// delete databases. +type DatabasesClient struct { + BaseClient +} + +// NewDatabasesClient creates an instance of the DatabasesClient client. +func NewDatabasesClient(subscriptionID string) DatabasesClient { + return NewDatabasesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabasesClientWithBaseURI creates an instance of the DatabasesClient client. +func NewDatabasesClientWithBaseURI(baseURI string, subscriptionID string) DatabasesClient { + return DatabasesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new database or updates an existing database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// parameters - the requested database resource state. +func (client DatabasesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters Database) (result DatabasesCreateOrUpdateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.Sku.Name", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "parameters.DatabaseProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.DatabaseProperties.CurrentSku", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.DatabaseProperties.CurrentSku.Name", Name: validation.Null, Rule: true, Chain: nil}}}, + }}}}}); err != nil { + return result, validation.NewError("sql.DatabasesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serverName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DatabasesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters Database) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) CreateOrUpdateSender(req *http.Request) (future DatabasesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DatabasesClient) CreateOrUpdateResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +func (client DatabasesClient) Delete(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result DatabasesDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DatabasesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) DeleteSender(req *http.Request) (future DatabasesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DatabasesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +func (client DatabasesClient) Get(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result Database, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DatabasesClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DatabasesClient) GetResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByElasticPool gets a list of databases in an elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// elasticPoolName - the name of the elastic pool. +func (client DatabasesClient) ListByElasticPool(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (result DatabaseListResultPage, err error) { + result.fn = client.listByElasticPoolNextResults + req, err := client.ListByElasticPoolPreparer(ctx, resourceGroupName, serverName, elasticPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByElasticPool", nil, "Failure preparing request") + return + } + + resp, err := client.ListByElasticPoolSender(req) + if err != nil { + result.dlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByElasticPool", resp, "Failure sending request") + return + } + + result.dlr, err = client.ListByElasticPoolResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByElasticPool", resp, "Failure responding to request") + } + + return +} + +// ListByElasticPoolPreparer prepares the ListByElasticPool request. +func (client DatabasesClient) ListByElasticPoolPreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/databases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByElasticPoolSender sends the ListByElasticPool request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListByElasticPoolSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByElasticPoolResponder handles the response to the ListByElasticPool request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListByElasticPoolResponder(resp *http.Response) (result DatabaseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByElasticPoolNextResults retrieves the next set of results, if any. +func (client DatabasesClient) listByElasticPoolNextResults(lastResults DatabaseListResult) (result DatabaseListResult, err error) { + req, err := lastResults.databaseListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "listByElasticPoolNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByElasticPoolSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "listByElasticPoolNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByElasticPoolResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "listByElasticPoolNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByElasticPoolComplete enumerates all values, automatically crossing page boundaries as required. +func (client DatabasesClient) ListByElasticPoolComplete(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (result DatabaseListResultIterator, err error) { + result.page, err = client.ListByElasticPool(ctx, resourceGroupName, serverName, elasticPoolName) + return +} + +// ListByServer gets a list of databases. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +func (client DatabasesClient) ListByServer(ctx context.Context, resourceGroupName string, serverName string) (result DatabaseListResultPage, err error) { + result.fn = client.listByServerNextResults + req, err := client.ListByServerPreparer(ctx, resourceGroupName, serverName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByServer", nil, "Failure preparing request") + return + } + + resp, err := client.ListByServerSender(req) + if err != nil { + result.dlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByServer", resp, "Failure sending request") + return + } + + result.dlr, err = client.ListByServerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "ListByServer", resp, "Failure responding to request") + } + + return +} + +// ListByServerPreparer prepares the ListByServer request. +func (client DatabasesClient) ListByServerPreparer(ctx context.Context, resourceGroupName string, serverName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByServerSender sends the ListByServer request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListByServerSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByServerResponder handles the response to the ListByServer request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListByServerResponder(resp *http.Response) (result DatabaseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByServerNextResults retrieves the next set of results, if any. +func (client DatabasesClient) listByServerNextResults(lastResults DatabaseListResult) (result DatabaseListResult, err error) { + req, err := lastResults.databaseListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "listByServerNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByServerSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabasesClient", "listByServerNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByServerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "listByServerNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByServerComplete enumerates all values, automatically crossing page boundaries as required. +func (client DatabasesClient) ListByServerComplete(ctx context.Context, resourceGroupName string, serverName string) (result DatabaseListResultIterator, err error) { + result.page, err = client.ListByServer(ctx, resourceGroupName, serverName) + return +} + +// Pause pauses a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database to be paused. +func (client DatabasesClient) Pause(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result DatabasesPauseFuture, err error) { + req, err := client.PausePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Pause", nil, "Failure preparing request") + return + } + + result, err = client.PauseSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Pause", result.Response(), "Failure sending request") + return + } + + return +} + +// PausePreparer prepares the Pause request. +func (client DatabasesClient) PausePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/pause", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// PauseSender sends the Pause request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) PauseSender(req *http.Request) (future DatabasesPauseFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// PauseResponder handles the response to the Pause request. The method always +// closes the http.Response Body. +func (client DatabasesClient) PauseResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Rename renames a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database to rename. +// parameters - the resource move definition for renaming this database. +func (client DatabasesClient) Rename(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters ResourceMoveDefinition) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.ID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("sql.DatabasesClient", "Rename", err.Error()) + } + + req, err := client.RenamePreparer(ctx, resourceGroupName, serverName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Rename", nil, "Failure preparing request") + return + } + + resp, err := client.RenameSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Rename", resp, "Failure sending request") + return + } + + result, err = client.RenameResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Rename", resp, "Failure responding to request") + } + + return +} + +// RenamePreparer prepares the Rename request. +func (client DatabasesClient) RenamePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters ResourceMoveDefinition) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/move", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RenameSender sends the Rename request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) RenameSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// RenameResponder handles the response to the Rename request. The method always +// closes the http.Response Body. +func (client DatabasesClient) RenameResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Resume resumes a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database to be resumed. +func (client DatabasesClient) Resume(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result DatabasesResumeFuture, err error) { + req, err := client.ResumePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Resume", nil, "Failure preparing request") + return + } + + result, err = client.ResumeSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Resume", result.Response(), "Failure sending request") + return + } + + return +} + +// ResumePreparer prepares the Resume request. +func (client DatabasesClient) ResumePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/resume", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ResumeSender sends the Resume request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ResumeSender(req *http.Request) (future DatabasesResumeFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ResumeResponder handles the response to the Resume request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ResumeResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates an existing database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// parameters - the requested database resource state. +func (client DatabasesClient) Update(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters DatabaseUpdate) (result DatabasesUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, serverName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client DatabasesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, parameters DatabaseUpdate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) UpdateSender(req *http.Request) (future DatabasesUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client DatabasesClient) UpdateResponder(resp *http.Response) (result Database, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// UpgradeDataWarehouse upgrades a data warehouse. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database to be upgraded. +func (client DatabasesClient) UpgradeDataWarehouse(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result DatabasesUpgradeDataWarehouseFuture, err error) { + req, err := client.UpgradeDataWarehousePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "UpgradeDataWarehouse", nil, "Failure preparing request") + return + } + + result, err = client.UpgradeDataWarehouseSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesClient", "UpgradeDataWarehouse", result.Response(), "Failure sending request") + return + } + + return +} + +// UpgradeDataWarehousePreparer prepares the UpgradeDataWarehouse request. +func (client DatabasesClient) UpgradeDataWarehousePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/upgradeDataWarehouse", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpgradeDataWarehouseSender sends the UpgradeDataWarehouse request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) UpgradeDataWarehouseSender(req *http.Request) (future DatabasesUpgradeDataWarehouseFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpgradeDataWarehouseResponder handles the response to the UpgradeDataWarehouse request. The method always +// closes the http.Response Body. +func (client DatabasesClient) UpgradeDataWarehouseResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databasevulnerabilityassessmentscans.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databasevulnerabilityassessmentscans.go new file mode 100644 index 000000000000..9fa9dc2ecab1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/databasevulnerabilityassessmentscans.go @@ -0,0 +1,365 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// DatabaseVulnerabilityAssessmentScansClient is the the Azure SQL Database management API provides a RESTful set of +// web services that interact with Azure SQL Database services to manage your databases. The API enables you to create, +// retrieve, update, and delete databases. +type DatabaseVulnerabilityAssessmentScansClient struct { + BaseClient +} + +// NewDatabaseVulnerabilityAssessmentScansClient creates an instance of the DatabaseVulnerabilityAssessmentScansClient +// client. +func NewDatabaseVulnerabilityAssessmentScansClient(subscriptionID string) DatabaseVulnerabilityAssessmentScansClient { + return NewDatabaseVulnerabilityAssessmentScansClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabaseVulnerabilityAssessmentScansClientWithBaseURI creates an instance of the +// DatabaseVulnerabilityAssessmentScansClient client. +func NewDatabaseVulnerabilityAssessmentScansClientWithBaseURI(baseURI string, subscriptionID string) DatabaseVulnerabilityAssessmentScansClient { + return DatabaseVulnerabilityAssessmentScansClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Export convert an existing scan result to a human readable format. If already exists nothing happens +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the scanned database. +// scanID - the vulnerability assessment scan Id. +func (client DatabaseVulnerabilityAssessmentScansClient) Export(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (result DatabaseVulnerabilityAssessmentScansExport, err error) { + req, err := client.ExportPreparer(ctx, resourceGroupName, serverName, databaseName, scanID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Export", nil, "Failure preparing request") + return + } + + resp, err := client.ExportSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Export", resp, "Failure sending request") + return + } + + result, err = client.ExportResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Export", resp, "Failure responding to request") + } + + return +} + +// ExportPreparer prepares the Export request. +func (client DatabaseVulnerabilityAssessmentScansClient) ExportPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scanId": autorest.Encode("path", scanID), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/export", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExportSender sends the Export request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseVulnerabilityAssessmentScansClient) ExportSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ExportResponder handles the response to the Export request. The method always +// closes the http.Response Body. +func (client DatabaseVulnerabilityAssessmentScansClient) ExportResponder(resp *http.Response) (result DatabaseVulnerabilityAssessmentScansExport, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets a vulnerability assessment scan record of a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// scanID - the vulnerability assessment scan Id of the scan to retrieve. +func (client DatabaseVulnerabilityAssessmentScansClient) Get(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (result VulnerabilityAssessmentScanRecord, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, serverName, databaseName, scanID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DatabaseVulnerabilityAssessmentScansClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scanId": autorest.Encode("path", scanID), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseVulnerabilityAssessmentScansClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DatabaseVulnerabilityAssessmentScansClient) GetResponder(resp *http.Response) (result VulnerabilityAssessmentScanRecord, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// InitiateScan executes a Vulnerability Assessment database scan. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +// scanID - the vulnerability assessment scan Id of the scan to retrieve. +func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScan(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (result DatabaseVulnerabilityAssessmentScansInitiateScanFuture, err error) { + req, err := client.InitiateScanPreparer(ctx, resourceGroupName, serverName, databaseName, scanID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "InitiateScan", nil, "Failure preparing request") + return + } + + result, err = client.InitiateScanSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "InitiateScan", result.Response(), "Failure sending request") + return + } + + return +} + +// InitiateScanPreparer prepares the InitiateScan request. +func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScanPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scanId": autorest.Encode("path", scanID), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/initiateScan", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// InitiateScanSender sends the InitiateScan request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScanSender(req *http.Request) (future DatabaseVulnerabilityAssessmentScansInitiateScanFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// InitiateScanResponder handles the response to the InitiateScan request. The method always +// closes the http.Response Body. +func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScanResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListByDatabase lists the vulnerability assessment scans of a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// databaseName - the name of the database. +func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabase(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result VulnerabilityAssessmentScanRecordListResultPage, err error) { + result.fn = client.listByDatabaseNextResults + req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, serverName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.vasrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", resp, "Failure sending request") + return + } + + result.vasrlr, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", resp, "Failure responding to request") + } + + return +} + +// ListByDatabasePreparer prepares the ListByDatabase request. +func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDatabaseSender sends the ListByDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always +// closes the http.Response Body. +func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabaseResponder(resp *http.Response) (result VulnerabilityAssessmentScanRecordListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByDatabaseNextResults retrieves the next set of results, if any. +func (client DatabaseVulnerabilityAssessmentScansClient) listByDatabaseNextResults(lastResults VulnerabilityAssessmentScanRecordListResult) (result VulnerabilityAssessmentScanRecordListResult, err error) { + req, err := lastResults.vulnerabilityAssessmentScanRecordListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByDatabaseComplete enumerates all values, automatically crossing page boundaries as required. +func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabaseComplete(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result VulnerabilityAssessmentScanRecordListResultIterator, err error) { + result.page, err = client.ListByDatabase(ctx, resourceGroupName, serverName, databaseName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpooloperations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpooloperations.go new file mode 100644 index 000000000000..d4f79c95b4e5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpooloperations.go @@ -0,0 +1,210 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/satori/go.uuid" + "net/http" +) + +// ElasticPoolOperationsClient is the the Azure SQL Database management API provides a RESTful set of web services that +// interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, +// and delete databases. +type ElasticPoolOperationsClient struct { + BaseClient +} + +// NewElasticPoolOperationsClient creates an instance of the ElasticPoolOperationsClient client. +func NewElasticPoolOperationsClient(subscriptionID string) ElasticPoolOperationsClient { + return NewElasticPoolOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewElasticPoolOperationsClientWithBaseURI creates an instance of the ElasticPoolOperationsClient client. +func NewElasticPoolOperationsClientWithBaseURI(baseURI string, subscriptionID string) ElasticPoolOperationsClient { + return ElasticPoolOperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Cancel cancels the asynchronous operation on the elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// operationID - the operation identifier. +func (client ElasticPoolOperationsClient) Cancel(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string, operationID uuid.UUID) (result autorest.Response, err error) { + req, err := client.CancelPreparer(ctx, resourceGroupName, serverName, elasticPoolName, operationID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "Cancel", nil, "Failure preparing request") + return + } + + resp, err := client.CancelSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "Cancel", resp, "Failure sending request") + return + } + + result, err = client.CancelResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "Cancel", resp, "Failure responding to request") + } + + return +} + +// CancelPreparer prepares the Cancel request. +func (client ElasticPoolOperationsClient) CancelPreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string, operationID uuid.UUID) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "operationId": autorest.Encode("path", operationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/operations/{operationId}/cancel", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CancelSender sends the Cancel request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolOperationsClient) CancelSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CancelResponder handles the response to the Cancel request. The method always +// closes the http.Response Body. +func (client ElasticPoolOperationsClient) CancelResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListByElasticPool gets a list of operations performed on the elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +func (client ElasticPoolOperationsClient) ListByElasticPool(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (result ElasticPoolOperationListResultPage, err error) { + result.fn = client.listByElasticPoolNextResults + req, err := client.ListByElasticPoolPreparer(ctx, resourceGroupName, serverName, elasticPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "ListByElasticPool", nil, "Failure preparing request") + return + } + + resp, err := client.ListByElasticPoolSender(req) + if err != nil { + result.epolr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "ListByElasticPool", resp, "Failure sending request") + return + } + + result.epolr, err = client.ListByElasticPoolResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "ListByElasticPool", resp, "Failure responding to request") + } + + return +} + +// ListByElasticPoolPreparer prepares the ListByElasticPool request. +func (client ElasticPoolOperationsClient) ListByElasticPoolPreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/operations", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByElasticPoolSender sends the ListByElasticPool request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolOperationsClient) ListByElasticPoolSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByElasticPoolResponder handles the response to the ListByElasticPool request. The method always +// closes the http.Response Body. +func (client ElasticPoolOperationsClient) ListByElasticPoolResponder(resp *http.Response) (result ElasticPoolOperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByElasticPoolNextResults retrieves the next set of results, if any. +func (client ElasticPoolOperationsClient) listByElasticPoolNextResults(lastResults ElasticPoolOperationListResult) (result ElasticPoolOperationListResult, err error) { + req, err := lastResults.elasticPoolOperationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "listByElasticPoolNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByElasticPoolSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "listByElasticPoolNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByElasticPoolResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolOperationsClient", "listByElasticPoolNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByElasticPoolComplete enumerates all values, automatically crossing page boundaries as required. +func (client ElasticPoolOperationsClient) ListByElasticPoolComplete(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (result ElasticPoolOperationListResultIterator, err error) { + result.page, err = client.ListByElasticPool(ctx, resourceGroupName, serverName, elasticPoolName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpools.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpools.go new file mode 100644 index 000000000000..aad6cb0e1b7a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/elasticpools.go @@ -0,0 +1,447 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ElasticPoolsClient is the the Azure SQL Database management API provides a RESTful set of web services that interact +// with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, and +// delete databases. +type ElasticPoolsClient struct { + BaseClient +} + +// NewElasticPoolsClient creates an instance of the ElasticPoolsClient client. +func NewElasticPoolsClient(subscriptionID string) ElasticPoolsClient { + return NewElasticPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewElasticPoolsClientWithBaseURI creates an instance of the ElasticPoolsClient client. +func NewElasticPoolsClientWithBaseURI(baseURI string, subscriptionID string) ElasticPoolsClient { + return ElasticPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates an elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// elasticPoolName - the name of the elastic pool. +// parameters - the elastic pool parameters. +func (client ElasticPoolsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string, parameters ElasticPool) (result ElasticPoolsCreateOrUpdateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.Sku.Name", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("sql.ElasticPoolsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serverName, elasticPoolName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ElasticPoolsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string, parameters ElasticPool) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) CreateOrUpdateSender(req *http.Request) (future ElasticPoolsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) CreateOrUpdateResponder(resp *http.Response) (result ElasticPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// elasticPoolName - the name of the elastic pool. +func (client ElasticPoolsClient) Delete(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (result ElasticPoolsDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, serverName, elasticPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ElasticPoolsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) DeleteSender(req *http.Request) (future ElasticPoolsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets an elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// elasticPoolName - the name of the elastic pool. +func (client ElasticPoolsClient) Get(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (result ElasticPool, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, serverName, elasticPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ElasticPoolsClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) GetResponder(resp *http.Response) (result ElasticPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByServer gets all elastic pools in a server. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// skip - the number of elements in the collection to skip. +func (client ElasticPoolsClient) ListByServer(ctx context.Context, resourceGroupName string, serverName string, skip *int32) (result ElasticPoolListResultPage, err error) { + result.fn = client.listByServerNextResults + req, err := client.ListByServerPreparer(ctx, resourceGroupName, serverName, skip) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListByServer", nil, "Failure preparing request") + return + } + + resp, err := client.ListByServerSender(req) + if err != nil { + result.eplr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListByServer", resp, "Failure sending request") + return + } + + result.eplr, err = client.ListByServerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "ListByServer", resp, "Failure responding to request") + } + + return +} + +// ListByServerPreparer prepares the ListByServer request. +func (client ElasticPoolsClient) ListByServerPreparer(ctx context.Context, resourceGroupName string, serverName string, skip *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if skip != nil { + queryParameters["$skip"] = autorest.Encode("query", *skip) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByServerSender sends the ListByServer request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) ListByServerSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByServerResponder handles the response to the ListByServer request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) ListByServerResponder(resp *http.Response) (result ElasticPoolListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByServerNextResults retrieves the next set of results, if any. +func (client ElasticPoolsClient) listByServerNextResults(lastResults ElasticPoolListResult) (result ElasticPoolListResult, err error) { + req, err := lastResults.elasticPoolListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "listByServerNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByServerSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "listByServerNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByServerResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "listByServerNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByServerComplete enumerates all values, automatically crossing page boundaries as required. +func (client ElasticPoolsClient) ListByServerComplete(ctx context.Context, resourceGroupName string, serverName string, skip *int32) (result ElasticPoolListResultIterator, err error) { + result.page, err = client.ListByServer(ctx, resourceGroupName, serverName, skip) + return +} + +// Update updates an elastic pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// elasticPoolName - the name of the elastic pool. +// parameters - the elastic pool update parameters. +func (client ElasticPoolsClient) Update(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string, parameters ElasticPoolUpdate) (result ElasticPoolsUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, serverName, elasticPoolName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ElasticPoolsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serverName string, elasticPoolName string, parameters ElasticPoolUpdate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "elasticPoolName": autorest.Encode("path", elasticPoolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client ElasticPoolsClient) UpdateSender(req *http.Request) (future ElasticPoolsUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ElasticPoolsClient) UpdateResponder(resp *http.Response) (result ElasticPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/instancefailovergroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/instancefailovergroups.go new file mode 100644 index 000000000000..668be475c2c8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/instancefailovergroups.go @@ -0,0 +1,518 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// InstanceFailoverGroupsClient is the the Azure SQL Database management API provides a RESTful set of web services +// that interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, +// update, and delete databases. +type InstanceFailoverGroupsClient struct { + BaseClient +} + +// NewInstanceFailoverGroupsClient creates an instance of the InstanceFailoverGroupsClient client. +func NewInstanceFailoverGroupsClient(subscriptionID string) InstanceFailoverGroupsClient { + return NewInstanceFailoverGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewInstanceFailoverGroupsClientWithBaseURI creates an instance of the InstanceFailoverGroupsClient client. +func NewInstanceFailoverGroupsClientWithBaseURI(baseURI string, subscriptionID string) InstanceFailoverGroupsClient { + return InstanceFailoverGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a failover group. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// locationName - the name of the region where the resource is located. +// failoverGroupName - the name of the failover group. +// parameters - the failover group parameters. +func (client InstanceFailoverGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string, parameters InstanceFailoverGroup) (result InstanceFailoverGroupsCreateOrUpdateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.InstanceFailoverGroupProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.InstanceFailoverGroupProperties.ReadWriteEndpoint", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.InstanceFailoverGroupProperties.PartnerRegions", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.InstanceFailoverGroupProperties.ManagedInstancePairs", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("sql.InstanceFailoverGroupsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, locationName, failoverGroupName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client InstanceFailoverGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string, parameters InstanceFailoverGroup) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "failoverGroupName": autorest.Encode("path", failoverGroupName), + "locationName": autorest.Encode("path", locationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/instanceFailoverGroups/{failoverGroupName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client InstanceFailoverGroupsClient) CreateOrUpdateSender(req *http.Request) (future InstanceFailoverGroupsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client InstanceFailoverGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result InstanceFailoverGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a failover group. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// locationName - the name of the region where the resource is located. +// failoverGroupName - the name of the failover group. +func (client InstanceFailoverGroupsClient) Delete(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (result InstanceFailoverGroupsDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, locationName, failoverGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client InstanceFailoverGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "failoverGroupName": autorest.Encode("path", failoverGroupName), + "locationName": autorest.Encode("path", locationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/instanceFailoverGroups/{failoverGroupName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client InstanceFailoverGroupsClient) DeleteSender(req *http.Request) (future InstanceFailoverGroupsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client InstanceFailoverGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Failover fails over from the current primary managed instance to this managed instance. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// locationName - the name of the region where the resource is located. +// failoverGroupName - the name of the failover group. +func (client InstanceFailoverGroupsClient) Failover(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (result InstanceFailoverGroupsFailoverFuture, err error) { + req, err := client.FailoverPreparer(ctx, resourceGroupName, locationName, failoverGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Failover", nil, "Failure preparing request") + return + } + + result, err = client.FailoverSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Failover", result.Response(), "Failure sending request") + return + } + + return +} + +// FailoverPreparer prepares the Failover request. +func (client InstanceFailoverGroupsClient) FailoverPreparer(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "failoverGroupName": autorest.Encode("path", failoverGroupName), + "locationName": autorest.Encode("path", locationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/instanceFailoverGroups/{failoverGroupName}/failover", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// FailoverSender sends the Failover request. The method will close the +// http.Response Body if it receives an error. +func (client InstanceFailoverGroupsClient) FailoverSender(req *http.Request) (future InstanceFailoverGroupsFailoverFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// FailoverResponder handles the response to the Failover request. The method always +// closes the http.Response Body. +func (client InstanceFailoverGroupsClient) FailoverResponder(resp *http.Response) (result InstanceFailoverGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ForceFailoverAllowDataLoss fails over from the current primary managed instance to this managed instance. This +// operation might result in data loss. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// locationName - the name of the region where the resource is located. +// failoverGroupName - the name of the failover group. +func (client InstanceFailoverGroupsClient) ForceFailoverAllowDataLoss(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (result InstanceFailoverGroupsForceFailoverAllowDataLossFuture, err error) { + req, err := client.ForceFailoverAllowDataLossPreparer(ctx, resourceGroupName, locationName, failoverGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "ForceFailoverAllowDataLoss", nil, "Failure preparing request") + return + } + + result, err = client.ForceFailoverAllowDataLossSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "ForceFailoverAllowDataLoss", result.Response(), "Failure sending request") + return + } + + return +} + +// ForceFailoverAllowDataLossPreparer prepares the ForceFailoverAllowDataLoss request. +func (client InstanceFailoverGroupsClient) ForceFailoverAllowDataLossPreparer(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "failoverGroupName": autorest.Encode("path", failoverGroupName), + "locationName": autorest.Encode("path", locationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/instanceFailoverGroups/{failoverGroupName}/forceFailoverAllowDataLoss", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ForceFailoverAllowDataLossSender sends the ForceFailoverAllowDataLoss request. The method will close the +// http.Response Body if it receives an error. +func (client InstanceFailoverGroupsClient) ForceFailoverAllowDataLossSender(req *http.Request) (future InstanceFailoverGroupsForceFailoverAllowDataLossFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ForceFailoverAllowDataLossResponder handles the response to the ForceFailoverAllowDataLoss request. The method always +// closes the http.Response Body. +func (client InstanceFailoverGroupsClient) ForceFailoverAllowDataLossResponder(resp *http.Response) (result InstanceFailoverGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets a failover group. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// locationName - the name of the region where the resource is located. +// failoverGroupName - the name of the failover group. +func (client InstanceFailoverGroupsClient) Get(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (result InstanceFailoverGroup, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, locationName, failoverGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client InstanceFailoverGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, locationName string, failoverGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "failoverGroupName": autorest.Encode("path", failoverGroupName), + "locationName": autorest.Encode("path", locationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/instanceFailoverGroups/{failoverGroupName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client InstanceFailoverGroupsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client InstanceFailoverGroupsClient) GetResponder(resp *http.Response) (result InstanceFailoverGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByLocation lists the failover groups in a location. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// locationName - the name of the region where the resource is located. +func (client InstanceFailoverGroupsClient) ListByLocation(ctx context.Context, resourceGroupName string, locationName string) (result InstanceFailoverGroupListResultPage, err error) { + result.fn = client.listByLocationNextResults + req, err := client.ListByLocationPreparer(ctx, resourceGroupName, locationName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "ListByLocation", nil, "Failure preparing request") + return + } + + resp, err := client.ListByLocationSender(req) + if err != nil { + result.ifglr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "ListByLocation", resp, "Failure sending request") + return + } + + result.ifglr, err = client.ListByLocationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "ListByLocation", resp, "Failure responding to request") + } + + return +} + +// ListByLocationPreparer prepares the ListByLocation request. +func (client InstanceFailoverGroupsClient) ListByLocationPreparer(ctx context.Context, resourceGroupName string, locationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "locationName": autorest.Encode("path", locationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/instanceFailoverGroups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByLocationSender sends the ListByLocation request. The method will close the +// http.Response Body if it receives an error. +func (client InstanceFailoverGroupsClient) ListByLocationSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByLocationResponder handles the response to the ListByLocation request. The method always +// closes the http.Response Body. +func (client InstanceFailoverGroupsClient) ListByLocationResponder(resp *http.Response) (result InstanceFailoverGroupListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByLocationNextResults retrieves the next set of results, if any. +func (client InstanceFailoverGroupsClient) listByLocationNextResults(lastResults InstanceFailoverGroupListResult) (result InstanceFailoverGroupListResult, err error) { + req, err := lastResults.instanceFailoverGroupListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "listByLocationNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByLocationSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "listByLocationNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByLocationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsClient", "listByLocationNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByLocationComplete enumerates all values, automatically crossing page boundaries as required. +func (client InstanceFailoverGroupsClient) ListByLocationComplete(ctx context.Context, resourceGroupName string, locationName string) (result InstanceFailoverGroupListResultIterator, err error) { + result.page, err = client.ListByLocation(ctx, resourceGroupName, locationName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancetdecertificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancetdecertificates.go new file mode 100644 index 000000000000..0f1f97acf5c9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancetdecertificates.go @@ -0,0 +1,125 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ManagedInstanceTdeCertificatesClient is the the Azure SQL Database management API provides a RESTful set of web +// services that interact with Azure SQL Database services to manage your databases. The API enables you to create, +// retrieve, update, and delete databases. +type ManagedInstanceTdeCertificatesClient struct { + BaseClient +} + +// NewManagedInstanceTdeCertificatesClient creates an instance of the ManagedInstanceTdeCertificatesClient client. +func NewManagedInstanceTdeCertificatesClient(subscriptionID string) ManagedInstanceTdeCertificatesClient { + return NewManagedInstanceTdeCertificatesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedInstanceTdeCertificatesClientWithBaseURI creates an instance of the ManagedInstanceTdeCertificatesClient +// client. +func NewManagedInstanceTdeCertificatesClientWithBaseURI(baseURI string, subscriptionID string) ManagedInstanceTdeCertificatesClient { + return ManagedInstanceTdeCertificatesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create creates a TDE certificate for a given server. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// parameters - the requested TDE certificate to be created or updated. +func (client ManagedInstanceTdeCertificatesClient) Create(ctx context.Context, resourceGroupName string, managedInstanceName string, parameters TdeCertificate) (result ManagedInstanceTdeCertificatesCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TdeCertificateProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.TdeCertificateProperties.PrivateBlob", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("sql.ManagedInstanceTdeCertificatesClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, managedInstanceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceTdeCertificatesClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceTdeCertificatesClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ManagedInstanceTdeCertificatesClient) CreatePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, parameters TdeCertificate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/tdeCertificates", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceTdeCertificatesClient) CreateSender(req *http.Request) (future ManagedInstanceTdeCertificatesCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ManagedInstanceTdeCertificatesClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go new file mode 100644 index 000000000000..ca9abe427501 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go @@ -0,0 +1,3162 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "github.com/satori/go.uuid" + "net/http" +) + +// CapabilityGroup enumerates the values for capability group. +type CapabilityGroup string + +const ( + // SupportedEditions ... + SupportedEditions CapabilityGroup = "supportedEditions" + // SupportedElasticPoolEditions ... + SupportedElasticPoolEditions CapabilityGroup = "supportedElasticPoolEditions" + // SupportedManagedInstanceVersions ... + SupportedManagedInstanceVersions CapabilityGroup = "supportedManagedInstanceVersions" +) + +// PossibleCapabilityGroupValues returns an array of possible values for the CapabilityGroup const type. +func PossibleCapabilityGroupValues() []CapabilityGroup { + return []CapabilityGroup{SupportedEditions, SupportedElasticPoolEditions, SupportedManagedInstanceVersions} +} + +// CapabilityStatus enumerates the values for capability status. +type CapabilityStatus string + +const ( + // Available ... + Available CapabilityStatus = "Available" + // Default ... + Default CapabilityStatus = "Default" + // Disabled ... + Disabled CapabilityStatus = "Disabled" + // Visible ... + Visible CapabilityStatus = "Visible" +) + +// PossibleCapabilityStatusValues returns an array of possible values for the CapabilityStatus const type. +func PossibleCapabilityStatusValues() []CapabilityStatus { + return []CapabilityStatus{Available, Default, Disabled, Visible} +} + +// CatalogCollationType enumerates the values for catalog collation type. +type CatalogCollationType string + +const ( + // DATABASEDEFAULT ... + DATABASEDEFAULT CatalogCollationType = "DATABASE_DEFAULT" + // SQLLatin1GeneralCP1CIAS ... + SQLLatin1GeneralCP1CIAS CatalogCollationType = "SQL_Latin1_General_CP1_CI_AS" +) + +// PossibleCatalogCollationTypeValues returns an array of possible values for the CatalogCollationType const type. +func PossibleCatalogCollationTypeValues() []CatalogCollationType { + return []CatalogCollationType{DATABASEDEFAULT, SQLLatin1GeneralCP1CIAS} +} + +// CreateMode enumerates the values for create mode. +type CreateMode string + +const ( + // CreateModeCopy ... + CreateModeCopy CreateMode = "Copy" + // CreateModeDefault ... + CreateModeDefault CreateMode = "Default" + // CreateModeOnlineSecondary ... + CreateModeOnlineSecondary CreateMode = "OnlineSecondary" + // CreateModePointInTimeRestore ... + CreateModePointInTimeRestore CreateMode = "PointInTimeRestore" + // CreateModeRecovery ... + CreateModeRecovery CreateMode = "Recovery" + // CreateModeRestore ... + CreateModeRestore CreateMode = "Restore" + // CreateModeRestoreExternalBackup ... + CreateModeRestoreExternalBackup CreateMode = "RestoreExternalBackup" + // CreateModeRestoreExternalBackupSecondary ... + CreateModeRestoreExternalBackupSecondary CreateMode = "RestoreExternalBackupSecondary" + // CreateModeRestoreLongTermRetentionBackup ... + CreateModeRestoreLongTermRetentionBackup CreateMode = "RestoreLongTermRetentionBackup" + // CreateModeSecondary ... + CreateModeSecondary CreateMode = "Secondary" +) + +// PossibleCreateModeValues returns an array of possible values for the CreateMode const type. +func PossibleCreateModeValues() []CreateMode { + return []CreateMode{CreateModeCopy, CreateModeDefault, CreateModeOnlineSecondary, CreateModePointInTimeRestore, CreateModeRecovery, CreateModeRestore, CreateModeRestoreExternalBackup, CreateModeRestoreExternalBackupSecondary, CreateModeRestoreLongTermRetentionBackup, CreateModeSecondary} +} + +// DatabaseLicenseType enumerates the values for database license type. +type DatabaseLicenseType string + +const ( + // BasePrice ... + BasePrice DatabaseLicenseType = "BasePrice" + // LicenseIncluded ... + LicenseIncluded DatabaseLicenseType = "LicenseIncluded" +) + +// PossibleDatabaseLicenseTypeValues returns an array of possible values for the DatabaseLicenseType const type. +func PossibleDatabaseLicenseTypeValues() []DatabaseLicenseType { + return []DatabaseLicenseType{BasePrice, LicenseIncluded} +} + +// DatabaseReadScale enumerates the values for database read scale. +type DatabaseReadScale string + +const ( + // DatabaseReadScaleDisabled ... + DatabaseReadScaleDisabled DatabaseReadScale = "Disabled" + // DatabaseReadScaleEnabled ... + DatabaseReadScaleEnabled DatabaseReadScale = "Enabled" +) + +// PossibleDatabaseReadScaleValues returns an array of possible values for the DatabaseReadScale const type. +func PossibleDatabaseReadScaleValues() []DatabaseReadScale { + return []DatabaseReadScale{DatabaseReadScaleDisabled, DatabaseReadScaleEnabled} +} + +// DatabaseStatus enumerates the values for database status. +type DatabaseStatus string + +const ( + // AutoClosed ... + AutoClosed DatabaseStatus = "AutoClosed" + // Copying ... + Copying DatabaseStatus = "Copying" + // Creating ... + Creating DatabaseStatus = "Creating" + // EmergencyMode ... + EmergencyMode DatabaseStatus = "EmergencyMode" + // Inaccessible ... + Inaccessible DatabaseStatus = "Inaccessible" + // Offline ... + Offline DatabaseStatus = "Offline" + // OfflineSecondary ... + OfflineSecondary DatabaseStatus = "OfflineSecondary" + // Online ... + Online DatabaseStatus = "Online" + // Paused ... + Paused DatabaseStatus = "Paused" + // Pausing ... + Pausing DatabaseStatus = "Pausing" + // Recovering ... + Recovering DatabaseStatus = "Recovering" + // RecoveryPending ... + RecoveryPending DatabaseStatus = "RecoveryPending" + // Restoring ... + Restoring DatabaseStatus = "Restoring" + // Resuming ... + Resuming DatabaseStatus = "Resuming" + // Scaling ... + Scaling DatabaseStatus = "Scaling" + // Shutdown ... + Shutdown DatabaseStatus = "Shutdown" + // Standby ... + Standby DatabaseStatus = "Standby" + // Suspect ... + Suspect DatabaseStatus = "Suspect" +) + +// PossibleDatabaseStatusValues returns an array of possible values for the DatabaseStatus const type. +func PossibleDatabaseStatusValues() []DatabaseStatus { + return []DatabaseStatus{AutoClosed, Copying, Creating, EmergencyMode, Inaccessible, Offline, OfflineSecondary, Online, Paused, Pausing, Recovering, RecoveryPending, Restoring, Resuming, Scaling, Shutdown, Standby, Suspect} +} + +// ElasticPoolLicenseType enumerates the values for elastic pool license type. +type ElasticPoolLicenseType string + +const ( + // ElasticPoolLicenseTypeBasePrice ... + ElasticPoolLicenseTypeBasePrice ElasticPoolLicenseType = "BasePrice" + // ElasticPoolLicenseTypeLicenseIncluded ... + ElasticPoolLicenseTypeLicenseIncluded ElasticPoolLicenseType = "LicenseIncluded" +) + +// PossibleElasticPoolLicenseTypeValues returns an array of possible values for the ElasticPoolLicenseType const type. +func PossibleElasticPoolLicenseTypeValues() []ElasticPoolLicenseType { + return []ElasticPoolLicenseType{ElasticPoolLicenseTypeBasePrice, ElasticPoolLicenseTypeLicenseIncluded} +} + +// ElasticPoolState enumerates the values for elastic pool state. +type ElasticPoolState string + +const ( + // ElasticPoolStateCreating ... + ElasticPoolStateCreating ElasticPoolState = "Creating" + // ElasticPoolStateDisabled ... + ElasticPoolStateDisabled ElasticPoolState = "Disabled" + // ElasticPoolStateReady ... + ElasticPoolStateReady ElasticPoolState = "Ready" +) + +// PossibleElasticPoolStateValues returns an array of possible values for the ElasticPoolState const type. +func PossibleElasticPoolStateValues() []ElasticPoolState { + return []ElasticPoolState{ElasticPoolStateCreating, ElasticPoolStateDisabled, ElasticPoolStateReady} +} + +// InstanceFailoverGroupReplicationRole enumerates the values for instance failover group replication role. +type InstanceFailoverGroupReplicationRole string + +const ( + // Primary ... + Primary InstanceFailoverGroupReplicationRole = "Primary" + // Secondary ... + Secondary InstanceFailoverGroupReplicationRole = "Secondary" +) + +// PossibleInstanceFailoverGroupReplicationRoleValues returns an array of possible values for the InstanceFailoverGroupReplicationRole const type. +func PossibleInstanceFailoverGroupReplicationRoleValues() []InstanceFailoverGroupReplicationRole { + return []InstanceFailoverGroupReplicationRole{Primary, Secondary} +} + +// LogSizeUnit enumerates the values for log size unit. +type LogSizeUnit string + +const ( + // Gigabytes ... + Gigabytes LogSizeUnit = "Gigabytes" + // Megabytes ... + Megabytes LogSizeUnit = "Megabytes" + // Percent ... + Percent LogSizeUnit = "Percent" + // Petabytes ... + Petabytes LogSizeUnit = "Petabytes" + // Terabytes ... + Terabytes LogSizeUnit = "Terabytes" +) + +// PossibleLogSizeUnitValues returns an array of possible values for the LogSizeUnit const type. +func PossibleLogSizeUnitValues() []LogSizeUnit { + return []LogSizeUnit{Gigabytes, Megabytes, Percent, Petabytes, Terabytes} +} + +// ManagementOperationState enumerates the values for management operation state. +type ManagementOperationState string + +const ( + // CancelInProgress ... + CancelInProgress ManagementOperationState = "CancelInProgress" + // Cancelled ... + Cancelled ManagementOperationState = "Cancelled" + // Failed ... + Failed ManagementOperationState = "Failed" + // InProgress ... + InProgress ManagementOperationState = "InProgress" + // Pending ... + Pending ManagementOperationState = "Pending" + // Succeeded ... + Succeeded ManagementOperationState = "Succeeded" +) + +// PossibleManagementOperationStateValues returns an array of possible values for the ManagementOperationState const type. +func PossibleManagementOperationStateValues() []ManagementOperationState { + return []ManagementOperationState{CancelInProgress, Cancelled, Failed, InProgress, Pending, Succeeded} +} + +// MaxSizeUnit enumerates the values for max size unit. +type MaxSizeUnit string + +const ( + // MaxSizeUnitGigabytes ... + MaxSizeUnitGigabytes MaxSizeUnit = "Gigabytes" + // MaxSizeUnitMegabytes ... + MaxSizeUnitMegabytes MaxSizeUnit = "Megabytes" + // MaxSizeUnitPetabytes ... + MaxSizeUnitPetabytes MaxSizeUnit = "Petabytes" + // MaxSizeUnitTerabytes ... + MaxSizeUnitTerabytes MaxSizeUnit = "Terabytes" +) + +// PossibleMaxSizeUnitValues returns an array of possible values for the MaxSizeUnit const type. +func PossibleMaxSizeUnitValues() []MaxSizeUnit { + return []MaxSizeUnit{MaxSizeUnitGigabytes, MaxSizeUnitMegabytes, MaxSizeUnitPetabytes, MaxSizeUnitTerabytes} +} + +// PerformanceLevelUnit enumerates the values for performance level unit. +type PerformanceLevelUnit string + +const ( + // DTU ... + DTU PerformanceLevelUnit = "DTU" + // VCores ... + VCores PerformanceLevelUnit = "VCores" +) + +// PossiblePerformanceLevelUnitValues returns an array of possible values for the PerformanceLevelUnit const type. +func PossiblePerformanceLevelUnitValues() []PerformanceLevelUnit { + return []PerformanceLevelUnit{DTU, VCores} +} + +// ReadOnlyEndpointFailoverPolicy enumerates the values for read only endpoint failover policy. +type ReadOnlyEndpointFailoverPolicy string + +const ( + // ReadOnlyEndpointFailoverPolicyDisabled ... + ReadOnlyEndpointFailoverPolicyDisabled ReadOnlyEndpointFailoverPolicy = "Disabled" + // ReadOnlyEndpointFailoverPolicyEnabled ... + ReadOnlyEndpointFailoverPolicyEnabled ReadOnlyEndpointFailoverPolicy = "Enabled" +) + +// PossibleReadOnlyEndpointFailoverPolicyValues returns an array of possible values for the ReadOnlyEndpointFailoverPolicy const type. +func PossibleReadOnlyEndpointFailoverPolicyValues() []ReadOnlyEndpointFailoverPolicy { + return []ReadOnlyEndpointFailoverPolicy{ReadOnlyEndpointFailoverPolicyDisabled, ReadOnlyEndpointFailoverPolicyEnabled} +} + +// ReadWriteEndpointFailoverPolicy enumerates the values for read write endpoint failover policy. +type ReadWriteEndpointFailoverPolicy string + +const ( + // Automatic ... + Automatic ReadWriteEndpointFailoverPolicy = "Automatic" + // Manual ... + Manual ReadWriteEndpointFailoverPolicy = "Manual" +) + +// PossibleReadWriteEndpointFailoverPolicyValues returns an array of possible values for the ReadWriteEndpointFailoverPolicy const type. +func PossibleReadWriteEndpointFailoverPolicyValues() []ReadWriteEndpointFailoverPolicy { + return []ReadWriteEndpointFailoverPolicy{Automatic, Manual} +} + +// SampleName enumerates the values for sample name. +type SampleName string + +const ( + // AdventureWorksLT ... + AdventureWorksLT SampleName = "AdventureWorksLT" + // WideWorldImportersFull ... + WideWorldImportersFull SampleName = "WideWorldImportersFull" + // WideWorldImportersStd ... + WideWorldImportersStd SampleName = "WideWorldImportersStd" +) + +// PossibleSampleNameValues returns an array of possible values for the SampleName const type. +func PossibleSampleNameValues() []SampleName { + return []SampleName{AdventureWorksLT, WideWorldImportersFull, WideWorldImportersStd} +} + +// VulnerabilityAssessmentScanState enumerates the values for vulnerability assessment scan state. +type VulnerabilityAssessmentScanState string + +const ( + // VulnerabilityAssessmentScanStateFailed ... + VulnerabilityAssessmentScanStateFailed VulnerabilityAssessmentScanState = "Failed" + // VulnerabilityAssessmentScanStateFailedToRun ... + VulnerabilityAssessmentScanStateFailedToRun VulnerabilityAssessmentScanState = "FailedToRun" + // VulnerabilityAssessmentScanStateInProgress ... + VulnerabilityAssessmentScanStateInProgress VulnerabilityAssessmentScanState = "InProgress" + // VulnerabilityAssessmentScanStatePassed ... + VulnerabilityAssessmentScanStatePassed VulnerabilityAssessmentScanState = "Passed" +) + +// PossibleVulnerabilityAssessmentScanStateValues returns an array of possible values for the VulnerabilityAssessmentScanState const type. +func PossibleVulnerabilityAssessmentScanStateValues() []VulnerabilityAssessmentScanState { + return []VulnerabilityAssessmentScanState{VulnerabilityAssessmentScanStateFailed, VulnerabilityAssessmentScanStateFailedToRun, VulnerabilityAssessmentScanStateInProgress, VulnerabilityAssessmentScanStatePassed} +} + +// VulnerabilityAssessmentScanTriggerType enumerates the values for vulnerability assessment scan trigger type. +type VulnerabilityAssessmentScanTriggerType string + +const ( + // OnDemand ... + OnDemand VulnerabilityAssessmentScanTriggerType = "OnDemand" + // Recurring ... + Recurring VulnerabilityAssessmentScanTriggerType = "Recurring" +) + +// PossibleVulnerabilityAssessmentScanTriggerTypeValues returns an array of possible values for the VulnerabilityAssessmentScanTriggerType const type. +func PossibleVulnerabilityAssessmentScanTriggerTypeValues() []VulnerabilityAssessmentScanTriggerType { + return []VulnerabilityAssessmentScanTriggerType{OnDemand, Recurring} +} + +// BackupShortTermRetentionPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of +// a long-running operation. +type BackupShortTermRetentionPoliciesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *BackupShortTermRetentionPoliciesCreateOrUpdateFuture) Result(client BackupShortTermRetentionPoliciesClient) (bstrp BackupShortTermRetentionPolicy, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.BackupShortTermRetentionPoliciesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if bstrp.Response.Response, err = future.GetResult(sender); err == nil && bstrp.Response.Response.StatusCode != http.StatusNoContent { + bstrp, err = client.CreateOrUpdateResponder(bstrp.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", bstrp.Response.Response, "Failure responding to request") + } + } + return +} + +// BackupShortTermRetentionPoliciesUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type BackupShortTermRetentionPoliciesUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *BackupShortTermRetentionPoliciesUpdateFuture) Result(client BackupShortTermRetentionPoliciesClient) (bstrp BackupShortTermRetentionPolicy, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.BackupShortTermRetentionPoliciesUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if bstrp.Response.Response, err = future.GetResult(sender); err == nil && bstrp.Response.Response.StatusCode != http.StatusNoContent { + bstrp, err = client.UpdateResponder(bstrp.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesUpdateFuture", "Result", bstrp.Response.Response, "Failure responding to request") + } + } + return +} + +// BackupShortTermRetentionPolicy a short term retention policy. +type BackupShortTermRetentionPolicy struct { + autorest.Response `json:"-"` + // BackupShortTermRetentionPolicyProperties - Resource properties. + *BackupShortTermRetentionPolicyProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for BackupShortTermRetentionPolicy. +func (bstrp BackupShortTermRetentionPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bstrp.BackupShortTermRetentionPolicyProperties != nil { + objectMap["properties"] = bstrp.BackupShortTermRetentionPolicyProperties + } + if bstrp.ID != nil { + objectMap["id"] = bstrp.ID + } + if bstrp.Name != nil { + objectMap["name"] = bstrp.Name + } + if bstrp.Type != nil { + objectMap["type"] = bstrp.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for BackupShortTermRetentionPolicy struct. +func (bstrp *BackupShortTermRetentionPolicy) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var backupShortTermRetentionPolicyProperties BackupShortTermRetentionPolicyProperties + err = json.Unmarshal(*v, &backupShortTermRetentionPolicyProperties) + if err != nil { + return err + } + bstrp.BackupShortTermRetentionPolicyProperties = &backupShortTermRetentionPolicyProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + bstrp.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + bstrp.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + bstrp.Type = &typeVar + } + } + } + + return nil +} + +// BackupShortTermRetentionPolicyListResult a list of short term retention policies. +type BackupShortTermRetentionPolicyListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]BackupShortTermRetentionPolicy `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// BackupShortTermRetentionPolicyListResultIterator provides access to a complete listing of +// BackupShortTermRetentionPolicy values. +type BackupShortTermRetentionPolicyListResultIterator struct { + i int + page BackupShortTermRetentionPolicyListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *BackupShortTermRetentionPolicyListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BackupShortTermRetentionPolicyListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter BackupShortTermRetentionPolicyListResultIterator) Response() BackupShortTermRetentionPolicyListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter BackupShortTermRetentionPolicyListResultIterator) Value() BackupShortTermRetentionPolicy { + if !iter.page.NotDone() { + return BackupShortTermRetentionPolicy{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (bstrplr BackupShortTermRetentionPolicyListResult) IsEmpty() bool { + return bstrplr.Value == nil || len(*bstrplr.Value) == 0 +} + +// backupShortTermRetentionPolicyListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (bstrplr BackupShortTermRetentionPolicyListResult) backupShortTermRetentionPolicyListResultPreparer() (*http.Request, error) { + if bstrplr.NextLink == nil || len(to.String(bstrplr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(bstrplr.NextLink))) +} + +// BackupShortTermRetentionPolicyListResultPage contains a page of BackupShortTermRetentionPolicy values. +type BackupShortTermRetentionPolicyListResultPage struct { + fn func(BackupShortTermRetentionPolicyListResult) (BackupShortTermRetentionPolicyListResult, error) + bstrplr BackupShortTermRetentionPolicyListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BackupShortTermRetentionPolicyListResultPage) Next() error { + next, err := page.fn(page.bstrplr) + if err != nil { + return err + } + page.bstrplr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BackupShortTermRetentionPolicyListResultPage) NotDone() bool { + return !page.bstrplr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BackupShortTermRetentionPolicyListResultPage) Response() BackupShortTermRetentionPolicyListResult { + return page.bstrplr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BackupShortTermRetentionPolicyListResultPage) Values() []BackupShortTermRetentionPolicy { + if page.bstrplr.IsEmpty() { + return nil + } + return *page.bstrplr.Value +} + +// BackupShortTermRetentionPolicyProperties properties of a short term retention policy +type BackupShortTermRetentionPolicyProperties struct { + // RetentionDays - The backup retention period in days. This is how many days Point-in-Time Restore will be supported. + RetentionDays *int32 `json:"retentionDays,omitempty"` +} + +// Database a database resource. +type Database struct { + autorest.Response `json:"-"` + // Sku - The name and tier of the SKU. + Sku *Sku `json:"sku,omitempty"` + // Kind - Kind of database. This is metadata used for the Azure portal experience. + Kind *string `json:"kind,omitempty"` + // ManagedBy - Resource that manages the database. + ManagedBy *string `json:"managedBy,omitempty"` + // DatabaseProperties - Resource properties. + *DatabaseProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Database. +func (d Database) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if d.Sku != nil { + objectMap["sku"] = d.Sku + } + if d.Kind != nil { + objectMap["kind"] = d.Kind + } + if d.ManagedBy != nil { + objectMap["managedBy"] = d.ManagedBy + } + if d.DatabaseProperties != nil { + objectMap["properties"] = d.DatabaseProperties + } + if d.Location != nil { + objectMap["location"] = d.Location + } + if d.Tags != nil { + objectMap["tags"] = d.Tags + } + if d.ID != nil { + objectMap["id"] = d.ID + } + if d.Name != nil { + objectMap["name"] = d.Name + } + if d.Type != nil { + objectMap["type"] = d.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Database struct. +func (d *Database) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "sku": + if v != nil { + var sku Sku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + d.Sku = &sku + } + case "kind": + if v != nil { + var kind string + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + d.Kind = &kind + } + case "managedBy": + if v != nil { + var managedBy string + err = json.Unmarshal(*v, &managedBy) + if err != nil { + return err + } + d.ManagedBy = &managedBy + } + case "properties": + if v != nil { + var databaseProperties DatabaseProperties + err = json.Unmarshal(*v, &databaseProperties) + if err != nil { + return err + } + d.DatabaseProperties = &databaseProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + d.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + d.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + d.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + d.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + d.Type = &typeVar + } + } + } + + return nil +} + +// DatabaseListResult a list of databases. +type DatabaseListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]Database `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// DatabaseListResultIterator provides access to a complete listing of Database values. +type DatabaseListResultIterator struct { + i int + page DatabaseListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *DatabaseListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DatabaseListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter DatabaseListResultIterator) Response() DatabaseListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter DatabaseListResultIterator) Value() Database { + if !iter.page.NotDone() { + return Database{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (dlr DatabaseListResult) IsEmpty() bool { + return dlr.Value == nil || len(*dlr.Value) == 0 +} + +// databaseListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (dlr DatabaseListResult) databaseListResultPreparer() (*http.Request, error) { + if dlr.NextLink == nil || len(to.String(dlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(dlr.NextLink))) +} + +// DatabaseListResultPage contains a page of Database values. +type DatabaseListResultPage struct { + fn func(DatabaseListResult) (DatabaseListResult, error) + dlr DatabaseListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *DatabaseListResultPage) Next() error { + next, err := page.fn(page.dlr) + if err != nil { + return err + } + page.dlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DatabaseListResultPage) NotDone() bool { + return !page.dlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DatabaseListResultPage) Response() DatabaseListResult { + return page.dlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DatabaseListResultPage) Values() []Database { + if page.dlr.IsEmpty() { + return nil + } + return *page.dlr.Value +} + +// DatabaseOperation a database operation. +type DatabaseOperation struct { + // DatabaseOperationProperties - Resource properties. + *DatabaseOperationProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabaseOperation. +func (do DatabaseOperation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if do.DatabaseOperationProperties != nil { + objectMap["properties"] = do.DatabaseOperationProperties + } + if do.ID != nil { + objectMap["id"] = do.ID + } + if do.Name != nil { + objectMap["name"] = do.Name + } + if do.Type != nil { + objectMap["type"] = do.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseOperation struct. +func (do *DatabaseOperation) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var databaseOperationProperties DatabaseOperationProperties + err = json.Unmarshal(*v, &databaseOperationProperties) + if err != nil { + return err + } + do.DatabaseOperationProperties = &databaseOperationProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + do.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + do.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + do.Type = &typeVar + } + } + } + + return nil +} + +// DatabaseOperationListResult the response to a list database operations request +type DatabaseOperationListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]DatabaseOperation `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// DatabaseOperationListResultIterator provides access to a complete listing of DatabaseOperation values. +type DatabaseOperationListResultIterator struct { + i int + page DatabaseOperationListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *DatabaseOperationListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DatabaseOperationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter DatabaseOperationListResultIterator) Response() DatabaseOperationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter DatabaseOperationListResultIterator) Value() DatabaseOperation { + if !iter.page.NotDone() { + return DatabaseOperation{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (dolr DatabaseOperationListResult) IsEmpty() bool { + return dolr.Value == nil || len(*dolr.Value) == 0 +} + +// databaseOperationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (dolr DatabaseOperationListResult) databaseOperationListResultPreparer() (*http.Request, error) { + if dolr.NextLink == nil || len(to.String(dolr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(dolr.NextLink))) +} + +// DatabaseOperationListResultPage contains a page of DatabaseOperation values. +type DatabaseOperationListResultPage struct { + fn func(DatabaseOperationListResult) (DatabaseOperationListResult, error) + dolr DatabaseOperationListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *DatabaseOperationListResultPage) Next() error { + next, err := page.fn(page.dolr) + if err != nil { + return err + } + page.dolr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DatabaseOperationListResultPage) NotDone() bool { + return !page.dolr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DatabaseOperationListResultPage) Response() DatabaseOperationListResult { + return page.dolr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DatabaseOperationListResultPage) Values() []DatabaseOperation { + if page.dolr.IsEmpty() { + return nil + } + return *page.dolr.Value +} + +// DatabaseOperationProperties the properties of a database operation. +type DatabaseOperationProperties struct { + // DatabaseName - The name of the database the operation is being performed on. + DatabaseName *string `json:"databaseName,omitempty"` + // Operation - The name of operation. + Operation *string `json:"operation,omitempty"` + // OperationFriendlyName - The friendly name of operation. + OperationFriendlyName *string `json:"operationFriendlyName,omitempty"` + // PercentComplete - The percentage of the operation completed. + PercentComplete *int32 `json:"percentComplete,omitempty"` + // ServerName - The name of the server. + ServerName *string `json:"serverName,omitempty"` + // StartTime - The operation start time. + StartTime *date.Time `json:"startTime,omitempty"` + // State - The operation state. Possible values include: 'Pending', 'InProgress', 'Succeeded', 'Failed', 'CancelInProgress', 'Cancelled' + State ManagementOperationState `json:"state,omitempty"` + // ErrorCode - The operation error code. + ErrorCode *int32 `json:"errorCode,omitempty"` + // ErrorDescription - The operation error description. + ErrorDescription *string `json:"errorDescription,omitempty"` + // ErrorSeverity - The operation error severity. + ErrorSeverity *int32 `json:"errorSeverity,omitempty"` + // IsUserError - Whether or not the error is a user error. + IsUserError *bool `json:"isUserError,omitempty"` + // EstimatedCompletionTime - The estimated completion time of the operation. + EstimatedCompletionTime *date.Time `json:"estimatedCompletionTime,omitempty"` + // Description - The operation description. + Description *string `json:"description,omitempty"` + // IsCancellable - Whether the operation can be cancelled. + IsCancellable *bool `json:"isCancellable,omitempty"` +} + +// DatabaseProperties the database's properties. +type DatabaseProperties struct { + // CreateMode - Specifies the mode of database creation. + // + // Default: regular database creation. + // + // Copy: creates a database as a copy of an existing database. sourceDatabaseId must be specified as the resource ID of the source database. + // + // Secondary: creates a database as a secondary replica of an existing database. sourceDatabaseId must be specified as the resource ID of the existing primary database. + // + // PointInTimeRestore: Creates a database by restoring a point in time backup of an existing database. sourceDatabaseId must be specified as the resource ID of the existing database, and restorePointInTime must be specified. + // + // Recovery: Creates a database by restoring a geo-replicated backup. sourceDatabaseId must be specified as the recoverable database resource ID to restore. + // + // Restore: Creates a database by restoring a backup of a deleted database. sourceDatabaseId must be specified. If sourceDatabaseId is the database's original resource ID, then sourceDatabaseDeletionDate must be specified. Otherwise sourceDatabaseId must be the restorable dropped database resource ID and sourceDatabaseDeletionDate is ignored. restorePointInTime may also be specified to restore from an earlier point in time. + // + // RestoreLongTermRetentionBackup: Creates a database by restoring from a long term retention vault. recoveryServicesRecoveryPointResourceId must be specified as the recovery point resource ID. + // + // Copy, Secondary, and RestoreLongTermRetentionBackup are not supported for DataWarehouse edition. Possible values include: 'CreateModeDefault', 'CreateModeCopy', 'CreateModeSecondary', 'CreateModePointInTimeRestore', 'CreateModeRestore', 'CreateModeRecovery', 'CreateModeRestoreExternalBackup', 'CreateModeRestoreExternalBackupSecondary', 'CreateModeRestoreLongTermRetentionBackup', 'CreateModeOnlineSecondary' + CreateMode CreateMode `json:"createMode,omitempty"` + // Collation - The collation of the database. + Collation *string `json:"collation,omitempty"` + // MaxSizeBytes - The max size of the database expressed in bytes. + MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"` + // SampleName - The name of the sample schema to apply when creating this database. Possible values include: 'AdventureWorksLT', 'WideWorldImportersStd', 'WideWorldImportersFull' + SampleName SampleName `json:"sampleName,omitempty"` + // ElasticPoolID - The resource identifier of the elastic pool containing this database. + ElasticPoolID *string `json:"elasticPoolId,omitempty"` + // SourceDatabaseID - The resource identifier of the source database associated with create operation of this database. + SourceDatabaseID *string `json:"sourceDatabaseId,omitempty"` + // Status - The status of the database. Possible values include: 'Online', 'Restoring', 'RecoveryPending', 'Recovering', 'Suspect', 'Offline', 'Standby', 'Shutdown', 'EmergencyMode', 'AutoClosed', 'Copying', 'Creating', 'Inaccessible', 'OfflineSecondary', 'Pausing', 'Paused', 'Resuming', 'Scaling' + Status DatabaseStatus `json:"status,omitempty"` + // DatabaseID - The ID of the database. + DatabaseID *uuid.UUID `json:"databaseId,omitempty"` + // CreationDate - The creation date of the database (ISO8601 format). + CreationDate *date.Time `json:"creationDate,omitempty"` + // CurrentServiceObjectiveName - The current service level objective name of the database. + CurrentServiceObjectiveName *string `json:"currentServiceObjectiveName,omitempty"` + // RequestedServiceObjectiveName - The requested service level objective name of the database. + RequestedServiceObjectiveName *string `json:"requestedServiceObjectiveName,omitempty"` + // DefaultSecondaryLocation - The default secondary region for this database. + DefaultSecondaryLocation *string `json:"defaultSecondaryLocation,omitempty"` + // FailoverGroupID - Failover Group resource identifier that this database belongs to. + FailoverGroupID *string `json:"failoverGroupId,omitempty"` + // RestorePointInTime - Specifies the point in time (ISO8601 format) of the source database that will be restored to create the new database. + RestorePointInTime *date.Time `json:"restorePointInTime,omitempty"` + // SourceDatabaseDeletionDate - Specifies the time that the database was deleted. + SourceDatabaseDeletionDate *date.Time `json:"sourceDatabaseDeletionDate,omitempty"` + // RecoveryServicesRecoveryPointID - The resource identifier of the recovery point associated with create operation of this database. + RecoveryServicesRecoveryPointID *string `json:"recoveryServicesRecoveryPointId,omitempty"` + // LongTermRetentionBackupResourceID - The resource identifier of the long term retention backup associated with create operation of this database. + LongTermRetentionBackupResourceID *string `json:"longTermRetentionBackupResourceId,omitempty"` + // RecoverableDatabaseID - The resource identifier of the recoverable database associated with create operation of this database. + RecoverableDatabaseID *string `json:"recoverableDatabaseId,omitempty"` + // RestorableDroppedDatabaseID - The resource identifier of the restorable dropped database associated with create operation of this database. + RestorableDroppedDatabaseID *string `json:"restorableDroppedDatabaseId,omitempty"` + // CatalogCollation - Collation of the metadata catalog. Possible values include: 'DATABASEDEFAULT', 'SQLLatin1GeneralCP1CIAS' + CatalogCollation CatalogCollationType `json:"catalogCollation,omitempty"` + // ZoneRedundant - Whether or not this database is zone redundant, which means the replicas of this database will be spread across multiple availability zones. + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` + // LicenseType - The license type to apply for this database. Possible values include: 'LicenseIncluded', 'BasePrice' + LicenseType DatabaseLicenseType `json:"licenseType,omitempty"` + // MaxLogSizeBytes - The max log size for this database. + MaxLogSizeBytes *int64 `json:"maxLogSizeBytes,omitempty"` + // EarliestRestoreDate - This records the earliest start date and time that restore is available for this database (ISO8601 format). + EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` + // ReadScale - The state of read-only routing. If enabled, connections that have application intent set to readonly in their connection string may be routed to a readonly secondary replica in the same region. Possible values include: 'DatabaseReadScaleEnabled', 'DatabaseReadScaleDisabled' + ReadScale DatabaseReadScale `json:"readScale,omitempty"` + // CurrentSku - The name and tier of the SKU. + CurrentSku *Sku `json:"currentSku,omitempty"` +} + +// DatabasesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DatabasesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabasesCreateOrUpdateFuture) Result(client DatabasesClient) (d Database, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabasesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.CreateOrUpdateResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesCreateOrUpdateFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DatabasesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DatabasesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabasesDeleteFuture) Result(client DatabasesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabasesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DatabasesPauseFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DatabasesPauseFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabasesPauseFuture) Result(client DatabasesClient) (d Database, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesPauseFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabasesPauseFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.PauseResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesPauseFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DatabasesResumeFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DatabasesResumeFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabasesResumeFuture) Result(client DatabasesClient) (d Database, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesResumeFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabasesResumeFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.ResumeResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesResumeFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DatabasesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DatabasesUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabasesUpdateFuture) Result(client DatabasesClient) (d Database, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabasesUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.UpdateResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesUpdateFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DatabasesUpgradeDataWarehouseFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DatabasesUpgradeDataWarehouseFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabasesUpgradeDataWarehouseFuture) Result(client DatabasesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabasesUpgradeDataWarehouseFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabasesUpgradeDataWarehouseFuture") + return + } + ar.Response = future.Response() + return +} + +// DatabaseUpdate a database resource. +type DatabaseUpdate struct { + // Sku - The name and tier of the SKU. + Sku *Sku `json:"sku,omitempty"` + // DatabaseProperties - Resource properties. + *DatabaseProperties `json:"properties,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for DatabaseUpdate. +func (du DatabaseUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if du.Sku != nil { + objectMap["sku"] = du.Sku + } + if du.DatabaseProperties != nil { + objectMap["properties"] = du.DatabaseProperties + } + if du.Tags != nil { + objectMap["tags"] = du.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseUpdate struct. +func (du *DatabaseUpdate) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "sku": + if v != nil { + var sku Sku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + du.Sku = &sku + } + case "properties": + if v != nil { + var databaseProperties DatabaseProperties + err = json.Unmarshal(*v, &databaseProperties) + if err != nil { + return err + } + du.DatabaseProperties = &databaseProperties + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + du.Tags = tags + } + } + } + + return nil +} + +// DatabaseVulnerabilityAssessmentScanExportProperties properties of the export operation's result. +type DatabaseVulnerabilityAssessmentScanExportProperties struct { + // ExportedReportLocation - Location of the exported report (e.g. https://myStorage.blob.core.windows.net/VaScans/scans/serverName/databaseName/scan_scanId.xlsx). + ExportedReportLocation *string `json:"exportedReportLocation,omitempty"` +} + +// DatabaseVulnerabilityAssessmentScansExport a database Vulnerability Assessment scan export resource. +type DatabaseVulnerabilityAssessmentScansExport struct { + autorest.Response `json:"-"` + // DatabaseVulnerabilityAssessmentScanExportProperties - Resource properties. + *DatabaseVulnerabilityAssessmentScanExportProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabaseVulnerabilityAssessmentScansExport. +func (dvase DatabaseVulnerabilityAssessmentScansExport) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dvase.DatabaseVulnerabilityAssessmentScanExportProperties != nil { + objectMap["properties"] = dvase.DatabaseVulnerabilityAssessmentScanExportProperties + } + if dvase.ID != nil { + objectMap["id"] = dvase.ID + } + if dvase.Name != nil { + objectMap["name"] = dvase.Name + } + if dvase.Type != nil { + objectMap["type"] = dvase.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseVulnerabilityAssessmentScansExport struct. +func (dvase *DatabaseVulnerabilityAssessmentScansExport) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var databaseVulnerabilityAssessmentScanExportProperties DatabaseVulnerabilityAssessmentScanExportProperties + err = json.Unmarshal(*v, &databaseVulnerabilityAssessmentScanExportProperties) + if err != nil { + return err + } + dvase.DatabaseVulnerabilityAssessmentScanExportProperties = &databaseVulnerabilityAssessmentScanExportProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + dvase.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + dvase.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + dvase.Type = &typeVar + } + } + } + + return nil +} + +// DatabaseVulnerabilityAssessmentScansInitiateScanFuture an abstraction for monitoring and retrieving the results +// of a long-running operation. +type DatabaseVulnerabilityAssessmentScansInitiateScanFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DatabaseVulnerabilityAssessmentScansInitiateScanFuture) Result(client DatabaseVulnerabilityAssessmentScansClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansInitiateScanFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.DatabaseVulnerabilityAssessmentScansInitiateScanFuture") + return + } + ar.Response = future.Response() + return +} + +// EditionCapability the edition capability. +type EditionCapability struct { + // Name - The database edition name. + Name *string `json:"name,omitempty"` + // SupportedServiceLevelObjectives - The list of supported service objectives for the edition. + SupportedServiceLevelObjectives *[]ServiceObjectiveCapability `json:"supportedServiceLevelObjectives,omitempty"` + // ZoneRedundant - Whether or not zone redundancy is supported for the edition. + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ElasticPool an elastic pool. +type ElasticPool struct { + autorest.Response `json:"-"` + Sku *Sku `json:"sku,omitempty"` + // Kind - Kind of elastic pool. This is metadata used for the Azure portal experience. + Kind *string `json:"kind,omitempty"` + // ElasticPoolProperties - Resource properties. + *ElasticPoolProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ElasticPool. +func (ep ElasticPool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ep.Sku != nil { + objectMap["sku"] = ep.Sku + } + if ep.Kind != nil { + objectMap["kind"] = ep.Kind + } + if ep.ElasticPoolProperties != nil { + objectMap["properties"] = ep.ElasticPoolProperties + } + if ep.Location != nil { + objectMap["location"] = ep.Location + } + if ep.Tags != nil { + objectMap["tags"] = ep.Tags + } + if ep.ID != nil { + objectMap["id"] = ep.ID + } + if ep.Name != nil { + objectMap["name"] = ep.Name + } + if ep.Type != nil { + objectMap["type"] = ep.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ElasticPool struct. +func (ep *ElasticPool) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "sku": + if v != nil { + var sku Sku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + ep.Sku = &sku + } + case "kind": + if v != nil { + var kind string + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + ep.Kind = &kind + } + case "properties": + if v != nil { + var elasticPoolProperties ElasticPoolProperties + err = json.Unmarshal(*v, &elasticPoolProperties) + if err != nil { + return err + } + ep.ElasticPoolProperties = &elasticPoolProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + ep.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + ep.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ep.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ep.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ep.Type = &typeVar + } + } + } + + return nil +} + +// ElasticPoolEditionCapability the elastic pool edition capability. +type ElasticPoolEditionCapability struct { + // Name - The elastic pool edition name. + Name *string `json:"name,omitempty"` + // SupportedElasticPoolPerformanceLevels - The list of supported elastic pool DTU levels for the edition. + SupportedElasticPoolPerformanceLevels *[]ElasticPoolPerformanceLevelCapability `json:"supportedElasticPoolPerformanceLevels,omitempty"` + // ZoneRedundant - Whether or not zone redundancy is supported for the edition. + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ElasticPoolListResult the result of an elastic pool list request. +type ElasticPoolListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]ElasticPool `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ElasticPoolListResultIterator provides access to a complete listing of ElasticPool values. +type ElasticPoolListResultIterator struct { + i int + page ElasticPoolListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ElasticPoolListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ElasticPoolListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ElasticPoolListResultIterator) Response() ElasticPoolListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ElasticPoolListResultIterator) Value() ElasticPool { + if !iter.page.NotDone() { + return ElasticPool{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (eplr ElasticPoolListResult) IsEmpty() bool { + return eplr.Value == nil || len(*eplr.Value) == 0 +} + +// elasticPoolListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (eplr ElasticPoolListResult) elasticPoolListResultPreparer() (*http.Request, error) { + if eplr.NextLink == nil || len(to.String(eplr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(eplr.NextLink))) +} + +// ElasticPoolListResultPage contains a page of ElasticPool values. +type ElasticPoolListResultPage struct { + fn func(ElasticPoolListResult) (ElasticPoolListResult, error) + eplr ElasticPoolListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ElasticPoolListResultPage) Next() error { + next, err := page.fn(page.eplr) + if err != nil { + return err + } + page.eplr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ElasticPoolListResultPage) NotDone() bool { + return !page.eplr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ElasticPoolListResultPage) Response() ElasticPoolListResult { + return page.eplr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ElasticPoolListResultPage) Values() []ElasticPool { + if page.eplr.IsEmpty() { + return nil + } + return *page.eplr.Value +} + +// ElasticPoolOperation a elastic pool operation. +type ElasticPoolOperation struct { + // ElasticPoolOperationProperties - Resource properties. + *ElasticPoolOperationProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ElasticPoolOperation. +func (epo ElasticPoolOperation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if epo.ElasticPoolOperationProperties != nil { + objectMap["properties"] = epo.ElasticPoolOperationProperties + } + if epo.ID != nil { + objectMap["id"] = epo.ID + } + if epo.Name != nil { + objectMap["name"] = epo.Name + } + if epo.Type != nil { + objectMap["type"] = epo.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ElasticPoolOperation struct. +func (epo *ElasticPoolOperation) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var elasticPoolOperationProperties ElasticPoolOperationProperties + err = json.Unmarshal(*v, &elasticPoolOperationProperties) + if err != nil { + return err + } + epo.ElasticPoolOperationProperties = &elasticPoolOperationProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + epo.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + epo.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + epo.Type = &typeVar + } + } + } + + return nil +} + +// ElasticPoolOperationListResult the response to a list elastic pool operations request +type ElasticPoolOperationListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]ElasticPoolOperation `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ElasticPoolOperationListResultIterator provides access to a complete listing of ElasticPoolOperation values. +type ElasticPoolOperationListResultIterator struct { + i int + page ElasticPoolOperationListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ElasticPoolOperationListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ElasticPoolOperationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ElasticPoolOperationListResultIterator) Response() ElasticPoolOperationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ElasticPoolOperationListResultIterator) Value() ElasticPoolOperation { + if !iter.page.NotDone() { + return ElasticPoolOperation{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (epolr ElasticPoolOperationListResult) IsEmpty() bool { + return epolr.Value == nil || len(*epolr.Value) == 0 +} + +// elasticPoolOperationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (epolr ElasticPoolOperationListResult) elasticPoolOperationListResultPreparer() (*http.Request, error) { + if epolr.NextLink == nil || len(to.String(epolr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(epolr.NextLink))) +} + +// ElasticPoolOperationListResultPage contains a page of ElasticPoolOperation values. +type ElasticPoolOperationListResultPage struct { + fn func(ElasticPoolOperationListResult) (ElasticPoolOperationListResult, error) + epolr ElasticPoolOperationListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ElasticPoolOperationListResultPage) Next() error { + next, err := page.fn(page.epolr) + if err != nil { + return err + } + page.epolr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ElasticPoolOperationListResultPage) NotDone() bool { + return !page.epolr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ElasticPoolOperationListResultPage) Response() ElasticPoolOperationListResult { + return page.epolr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ElasticPoolOperationListResultPage) Values() []ElasticPoolOperation { + if page.epolr.IsEmpty() { + return nil + } + return *page.epolr.Value +} + +// ElasticPoolOperationProperties the properties of a elastic pool operation. +type ElasticPoolOperationProperties struct { + // ElasticPoolName - The name of the elastic pool the operation is being performed on. + ElasticPoolName *string `json:"elasticPoolName,omitempty"` + // Operation - The name of operation. + Operation *string `json:"operation,omitempty"` + // OperationFriendlyName - The friendly name of operation. + OperationFriendlyName *string `json:"operationFriendlyName,omitempty"` + // PercentComplete - The percentage of the operation completed. + PercentComplete *int32 `json:"percentComplete,omitempty"` + // ServerName - The name of the server. + ServerName *string `json:"serverName,omitempty"` + // StartTime - The operation start time. + StartTime *date.Time `json:"startTime,omitempty"` + // State - The operation state. + State *string `json:"state,omitempty"` + // ErrorCode - The operation error code. + ErrorCode *int32 `json:"errorCode,omitempty"` + // ErrorDescription - The operation error description. + ErrorDescription *string `json:"errorDescription,omitempty"` + // ErrorSeverity - The operation error severity. + ErrorSeverity *int32 `json:"errorSeverity,omitempty"` + // IsUserError - Whether or not the error is a user error. + IsUserError *bool `json:"isUserError,omitempty"` + // EstimatedCompletionTime - The estimated completion time of the operation. + EstimatedCompletionTime *date.Time `json:"estimatedCompletionTime,omitempty"` + // Description - The operation description. + Description *string `json:"description,omitempty"` + // IsCancellable - Whether the operation can be cancelled. + IsCancellable *bool `json:"isCancellable,omitempty"` +} + +// ElasticPoolPerDatabaseMaxPerformanceLevelCapability the max per-database performance level capability. +type ElasticPoolPerDatabaseMaxPerformanceLevelCapability struct { + // Limit - The maximum performance level per database. + Limit *float64 `json:"limit,omitempty"` + // Unit - Unit type used to measure performance level. Possible values include: 'DTU', 'VCores' + Unit PerformanceLevelUnit `json:"unit,omitempty"` + // SupportedPerDatabaseMinPerformanceLevels - The list of supported min database performance levels. + SupportedPerDatabaseMinPerformanceLevels *[]ElasticPoolPerDatabaseMinPerformanceLevelCapability `json:"supportedPerDatabaseMinPerformanceLevels,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ElasticPoolPerDatabaseMinPerformanceLevelCapability the minimum per-database performance level capability. +type ElasticPoolPerDatabaseMinPerformanceLevelCapability struct { + // Limit - The minimum performance level per database. + Limit *float64 `json:"limit,omitempty"` + // Unit - Unit type used to measure performance level. Possible values include: 'DTU', 'VCores' + Unit PerformanceLevelUnit `json:"unit,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ElasticPoolPerDatabaseSettings per database settings of an elastic pool. +type ElasticPoolPerDatabaseSettings struct { + // MinCapacity - The minimum capacity all databases are guaranteed. + MinCapacity *float64 `json:"minCapacity,omitempty"` + // MaxCapacity - The maximum capacity any one database can consume. + MaxCapacity *float64 `json:"maxCapacity,omitempty"` +} + +// ElasticPoolPerformanceLevelCapability the Elastic Pool performance level capability. +type ElasticPoolPerformanceLevelCapability struct { + // PerformanceLevel - The performance level for the pool. + PerformanceLevel *PerformanceLevelCapability `json:"performanceLevel,omitempty"` + // Sku - The sku. + Sku *Sku `json:"sku,omitempty"` + // SupportedLicenseTypes - List of supported license types. + SupportedLicenseTypes *[]LicenseTypeCapability `json:"supportedLicenseTypes,omitempty"` + // MaxDatabaseCount - The maximum number of databases supported. + MaxDatabaseCount *int32 `json:"maxDatabaseCount,omitempty"` + // IncludedMaxSize - The included (free) max size for this performance level. + IncludedMaxSize *MaxSizeCapability `json:"includedMaxSize,omitempty"` + // SupportedMaxSizes - The list of supported max sizes. + SupportedMaxSizes *[]MaxSizeRangeCapability `json:"supportedMaxSizes,omitempty"` + // SupportedPerDatabaseMaxSizes - The list of supported per database max sizes. + SupportedPerDatabaseMaxSizes *[]MaxSizeRangeCapability `json:"supportedPerDatabaseMaxSizes,omitempty"` + // SupportedPerDatabaseMaxPerformanceLevels - The list of supported per database max performance levels. + SupportedPerDatabaseMaxPerformanceLevels *[]ElasticPoolPerDatabaseMaxPerformanceLevelCapability `json:"supportedPerDatabaseMaxPerformanceLevels,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ElasticPoolProperties properties of an elastic pool +type ElasticPoolProperties struct { + // State - The state of the elastic pool. Possible values include: 'ElasticPoolStateCreating', 'ElasticPoolStateReady', 'ElasticPoolStateDisabled' + State ElasticPoolState `json:"state,omitempty"` + // CreationDate - The creation date of the elastic pool (ISO8601 format). + CreationDate *date.Time `json:"creationDate,omitempty"` + // MaxSizeBytes - The storage limit for the database elastic pool in bytes. + MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"` + // PerDatabaseSettings - The per database settings for the elastic pool. + PerDatabaseSettings *ElasticPoolPerDatabaseSettings `json:"perDatabaseSettings,omitempty"` + // ZoneRedundant - Whether or not this elastic pool is zone redundant, which means the replicas of this elastic pool will be spread across multiple availability zones. + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` + // LicenseType - The license type to apply for this elastic pool. Possible values include: 'ElasticPoolLicenseTypeLicenseIncluded', 'ElasticPoolLicenseTypeBasePrice' + LicenseType ElasticPoolLicenseType `json:"licenseType,omitempty"` +} + +// ElasticPoolsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ElasticPoolsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ElasticPoolsCreateOrUpdateFuture) Result(client ElasticPoolsClient) (ep ElasticPool, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ep.Response.Response, err = future.GetResult(sender); err == nil && ep.Response.Response.StatusCode != http.StatusNoContent { + ep, err = client.CreateOrUpdateResponder(ep.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsCreateOrUpdateFuture", "Result", ep.Response.Response, "Failure responding to request") + } + } + return +} + +// ElasticPoolsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ElasticPoolsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ElasticPoolsDeleteFuture) Result(client ElasticPoolsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ElasticPoolsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ElasticPoolsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ElasticPoolsUpdateFuture) Result(client ElasticPoolsClient) (ep ElasticPool, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ep.Response.Response, err = future.GetResult(sender); err == nil && ep.Response.Response.StatusCode != http.StatusNoContent { + ep, err = client.UpdateResponder(ep.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ElasticPoolsUpdateFuture", "Result", ep.Response.Response, "Failure responding to request") + } + } + return +} + +// ElasticPoolUpdate an elastic pool update. +type ElasticPoolUpdate struct { + Sku *Sku `json:"sku,omitempty"` + // ElasticPoolUpdateProperties - Resource properties. + *ElasticPoolUpdateProperties `json:"properties,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ElasticPoolUpdate. +func (epu ElasticPoolUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if epu.Sku != nil { + objectMap["sku"] = epu.Sku + } + if epu.ElasticPoolUpdateProperties != nil { + objectMap["properties"] = epu.ElasticPoolUpdateProperties + } + if epu.Tags != nil { + objectMap["tags"] = epu.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ElasticPoolUpdate struct. +func (epu *ElasticPoolUpdate) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "sku": + if v != nil { + var sku Sku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + epu.Sku = &sku + } + case "properties": + if v != nil { + var elasticPoolUpdateProperties ElasticPoolUpdateProperties + err = json.Unmarshal(*v, &elasticPoolUpdateProperties) + if err != nil { + return err + } + epu.ElasticPoolUpdateProperties = &elasticPoolUpdateProperties + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + epu.Tags = tags + } + } + } + + return nil +} + +// ElasticPoolUpdateProperties properties of an elastic pool +type ElasticPoolUpdateProperties struct { + // MaxSizeBytes - The storage limit for the database elastic pool in bytes. + MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"` + // PerDatabaseSettings - The per database settings for the elastic pool. + PerDatabaseSettings *ElasticPoolPerDatabaseSettings `json:"perDatabaseSettings,omitempty"` + // ZoneRedundant - Whether or not this elastic pool is zone redundant, which means the replicas of this elastic pool will be spread across multiple availability zones. + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` + // LicenseType - The license type to apply for this elastic pool. Possible values include: 'ElasticPoolLicenseTypeLicenseIncluded', 'ElasticPoolLicenseTypeBasePrice' + LicenseType ElasticPoolLicenseType `json:"licenseType,omitempty"` +} + +// InstanceFailoverGroup an instance failover group. +type InstanceFailoverGroup struct { + autorest.Response `json:"-"` + // InstanceFailoverGroupProperties - Resource properties. + *InstanceFailoverGroupProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for InstanceFailoverGroup. +func (ifg InstanceFailoverGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ifg.InstanceFailoverGroupProperties != nil { + objectMap["properties"] = ifg.InstanceFailoverGroupProperties + } + if ifg.ID != nil { + objectMap["id"] = ifg.ID + } + if ifg.Name != nil { + objectMap["name"] = ifg.Name + } + if ifg.Type != nil { + objectMap["type"] = ifg.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for InstanceFailoverGroup struct. +func (ifg *InstanceFailoverGroup) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var instanceFailoverGroupProperties InstanceFailoverGroupProperties + err = json.Unmarshal(*v, &instanceFailoverGroupProperties) + if err != nil { + return err + } + ifg.InstanceFailoverGroupProperties = &instanceFailoverGroupProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ifg.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ifg.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ifg.Type = &typeVar + } + } + } + + return nil +} + +// InstanceFailoverGroupListResult a list of instance failover groups. +type InstanceFailoverGroupListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]InstanceFailoverGroup `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// InstanceFailoverGroupListResultIterator provides access to a complete listing of InstanceFailoverGroup values. +type InstanceFailoverGroupListResultIterator struct { + i int + page InstanceFailoverGroupListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *InstanceFailoverGroupListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter InstanceFailoverGroupListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter InstanceFailoverGroupListResultIterator) Response() InstanceFailoverGroupListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter InstanceFailoverGroupListResultIterator) Value() InstanceFailoverGroup { + if !iter.page.NotDone() { + return InstanceFailoverGroup{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (ifglr InstanceFailoverGroupListResult) IsEmpty() bool { + return ifglr.Value == nil || len(*ifglr.Value) == 0 +} + +// instanceFailoverGroupListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ifglr InstanceFailoverGroupListResult) instanceFailoverGroupListResultPreparer() (*http.Request, error) { + if ifglr.NextLink == nil || len(to.String(ifglr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ifglr.NextLink))) +} + +// InstanceFailoverGroupListResultPage contains a page of InstanceFailoverGroup values. +type InstanceFailoverGroupListResultPage struct { + fn func(InstanceFailoverGroupListResult) (InstanceFailoverGroupListResult, error) + ifglr InstanceFailoverGroupListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *InstanceFailoverGroupListResultPage) Next() error { + next, err := page.fn(page.ifglr) + if err != nil { + return err + } + page.ifglr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page InstanceFailoverGroupListResultPage) NotDone() bool { + return !page.ifglr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page InstanceFailoverGroupListResultPage) Response() InstanceFailoverGroupListResult { + return page.ifglr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page InstanceFailoverGroupListResultPage) Values() []InstanceFailoverGroup { + if page.ifglr.IsEmpty() { + return nil + } + return *page.ifglr.Value +} + +// InstanceFailoverGroupProperties properties of a instance failover group. +type InstanceFailoverGroupProperties struct { + // ReadWriteEndpoint - Read-write endpoint of the failover group instance. + ReadWriteEndpoint *InstanceFailoverGroupReadWriteEndpoint `json:"readWriteEndpoint,omitempty"` + // ReadOnlyEndpoint - Read-only endpoint of the failover group instance. + ReadOnlyEndpoint *InstanceFailoverGroupReadOnlyEndpoint `json:"readOnlyEndpoint,omitempty"` + // ReplicationRole - Local replication role of the failover group instance. Possible values include: 'Primary', 'Secondary' + ReplicationRole InstanceFailoverGroupReplicationRole `json:"replicationRole,omitempty"` + // ReplicationState - Replication state of the failover group instance. + ReplicationState *string `json:"replicationState,omitempty"` + // PartnerRegions - Partner region information for the failover group. + PartnerRegions *[]PartnerRegionInfo `json:"partnerRegions,omitempty"` + // ManagedInstancePairs - List of managed instance pairs in the failover group. + ManagedInstancePairs *[]ManagedInstancePairInfo `json:"managedInstancePairs,omitempty"` +} + +// InstanceFailoverGroupReadOnlyEndpoint read-only endpoint of the failover group instance. +type InstanceFailoverGroupReadOnlyEndpoint struct { + // FailoverPolicy - Failover policy of the read-only endpoint for the failover group. Possible values include: 'ReadOnlyEndpointFailoverPolicyDisabled', 'ReadOnlyEndpointFailoverPolicyEnabled' + FailoverPolicy ReadOnlyEndpointFailoverPolicy `json:"failoverPolicy,omitempty"` +} + +// InstanceFailoverGroupReadWriteEndpoint read-write endpoint of the failover group instance. +type InstanceFailoverGroupReadWriteEndpoint struct { + // FailoverPolicy - Failover policy of the read-write endpoint for the failover group. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required. Possible values include: 'Manual', 'Automatic' + FailoverPolicy ReadWriteEndpointFailoverPolicy `json:"failoverPolicy,omitempty"` + // FailoverWithDataLossGracePeriodMinutes - Grace period before failover with data loss is attempted for the read-write endpoint. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required. + FailoverWithDataLossGracePeriodMinutes *int32 `json:"failoverWithDataLossGracePeriodMinutes,omitempty"` +} + +// InstanceFailoverGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type InstanceFailoverGroupsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *InstanceFailoverGroupsCreateOrUpdateFuture) Result(client InstanceFailoverGroupsClient) (ifg InstanceFailoverGroup, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ifg.Response.Response, err = future.GetResult(sender); err == nil && ifg.Response.Response.StatusCode != http.StatusNoContent { + ifg, err = client.CreateOrUpdateResponder(ifg.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsCreateOrUpdateFuture", "Result", ifg.Response.Response, "Failure responding to request") + } + } + return +} + +// InstanceFailoverGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type InstanceFailoverGroupsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *InstanceFailoverGroupsDeleteFuture) Result(client InstanceFailoverGroupsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// InstanceFailoverGroupsFailoverFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type InstanceFailoverGroupsFailoverFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *InstanceFailoverGroupsFailoverFuture) Result(client InstanceFailoverGroupsClient) (ifg InstanceFailoverGroup, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsFailoverFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsFailoverFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ifg.Response.Response, err = future.GetResult(sender); err == nil && ifg.Response.Response.StatusCode != http.StatusNoContent { + ifg, err = client.FailoverResponder(ifg.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsFailoverFuture", "Result", ifg.Response.Response, "Failure responding to request") + } + } + return +} + +// InstanceFailoverGroupsForceFailoverAllowDataLossFuture an abstraction for monitoring and retrieving the results +// of a long-running operation. +type InstanceFailoverGroupsForceFailoverAllowDataLossFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *InstanceFailoverGroupsForceFailoverAllowDataLossFuture) Result(client InstanceFailoverGroupsClient) (ifg InstanceFailoverGroup, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsForceFailoverAllowDataLossFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsForceFailoverAllowDataLossFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ifg.Response.Response, err = future.GetResult(sender); err == nil && ifg.Response.Response.StatusCode != http.StatusNoContent { + ifg, err = client.ForceFailoverAllowDataLossResponder(ifg.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsForceFailoverAllowDataLossFuture", "Result", ifg.Response.Response, "Failure responding to request") + } + } + return +} + +// LicenseTypeCapability the license type capability +type LicenseTypeCapability struct { + // Name - License type identifier. + Name *string `json:"name,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// LocationCapabilities the location capability. +type LocationCapabilities struct { + autorest.Response `json:"-"` + // Name - The location name. + Name *string `json:"name,omitempty"` + // SupportedServerVersions - The list of supported server versions. + SupportedServerVersions *[]ServerVersionCapability `json:"supportedServerVersions,omitempty"` + // SupportedManagedInstanceVersions - The list of supported managed instance versions. + SupportedManagedInstanceVersions *[]ManagedInstanceVersionCapability `json:"supportedManagedInstanceVersions,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// LogSizeCapability the log size capability. +type LogSizeCapability struct { + // Limit - The log size limit (see 'unit' for the units). + Limit *int32 `json:"limit,omitempty"` + // Unit - The units that the limit is expressed in. Possible values include: 'Megabytes', 'Gigabytes', 'Terabytes', 'Petabytes', 'Percent' + Unit LogSizeUnit `json:"unit,omitempty"` +} + +// ManagedInstanceEditionCapability the managed server capability +type ManagedInstanceEditionCapability struct { + // Name - The managed server version name. + Name *string `json:"name,omitempty"` + // SupportedFamilies - The supported families. + SupportedFamilies *[]ManagedInstanceFamilyCapability `json:"supportedFamilies,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ManagedInstanceFamilyCapability the managed server family capability. +type ManagedInstanceFamilyCapability struct { + // Name - Family name. + Name *string `json:"name,omitempty"` + // Sku - SKU name. + Sku *string `json:"sku,omitempty"` + // SupportedLicenseTypes - List of supported license types. + SupportedLicenseTypes *[]LicenseTypeCapability `json:"supportedLicenseTypes,omitempty"` + // SupportedVcoresValues - List of supported virtual cores values. + SupportedVcoresValues *[]ManagedInstanceVcoresCapability `json:"supportedVcoresValues,omitempty"` + // IncludedMaxSize - Included size. + IncludedMaxSize *MaxSizeCapability `json:"includedMaxSize,omitempty"` + // SupportedStorageSizes - Storage size ranges. + SupportedStorageSizes *[]MaxSizeRangeCapability `json:"supportedStorageSizes,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ManagedInstancePairInfo pairs of Managed Instances in the failover group. +type ManagedInstancePairInfo struct { + // PrimaryManagedInstanceID - Id of Primary Managed Instance in pair. + PrimaryManagedInstanceID *string `json:"primaryManagedInstanceId,omitempty"` + // PartnerManagedInstanceID - Id of Partner Managed Instance in pair. + PartnerManagedInstanceID *string `json:"partnerManagedInstanceId,omitempty"` +} + +// ManagedInstanceTdeCertificatesCreateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ManagedInstanceTdeCertificatesCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ManagedInstanceTdeCertificatesCreateFuture) Result(client ManagedInstanceTdeCertificatesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceTdeCertificatesCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceTdeCertificatesCreateFuture") + return + } + ar.Response = future.Response() + return +} + +// ManagedInstanceVcoresCapability the managed instance virtual cores capability. +type ManagedInstanceVcoresCapability struct { + // Name - The virtual cores identifier. + Name *string `json:"name,omitempty"` + // Value - The virtual cores value. + Value *int32 `json:"value,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ManagedInstanceVersionCapability the managed instance capability +type ManagedInstanceVersionCapability struct { + // Name - The server version name. + Name *string `json:"name,omitempty"` + // SupportedEditions - The list of supported managed instance editions. + SupportedEditions *[]ManagedInstanceEditionCapability `json:"supportedEditions,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// MaxSizeCapability the maximum size capability. +type MaxSizeCapability struct { + // Limit - The maximum size limit (see 'unit' for the units). + Limit *int32 `json:"limit,omitempty"` + // Unit - The units that the limit is expressed in. Possible values include: 'MaxSizeUnitMegabytes', 'MaxSizeUnitGigabytes', 'MaxSizeUnitTerabytes', 'MaxSizeUnitPetabytes' + Unit MaxSizeUnit `json:"unit,omitempty"` +} + +// MaxSizeRangeCapability the maximum size range capability. +type MaxSizeRangeCapability struct { + // MinValue - Minimum value. + MinValue *MaxSizeCapability `json:"minValue,omitempty"` + // MaxValue - Maximum value. + MaxValue *MaxSizeCapability `json:"maxValue,omitempty"` + // ScaleSize - Scale/step size for discrete values between the minimum value and the maximum value. + ScaleSize *MaxSizeCapability `json:"scaleSize,omitempty"` + // LogSize - Size of transaction log. + LogSize *LogSizeCapability `json:"logSize,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// PartnerRegionInfo partner region information for the failover group. +type PartnerRegionInfo struct { + // Location - Geo location of the partner managed instances. + Location *string `json:"location,omitempty"` + // ReplicationRole - Replication role of the partner managed instances. Possible values include: 'Primary', 'Secondary' + ReplicationRole InstanceFailoverGroupReplicationRole `json:"replicationRole,omitempty"` +} + +// PerformanceLevelCapability the performance level capability. +type PerformanceLevelCapability struct { + // Value - Performance level value. + Value *float64 `json:"value,omitempty"` + // Unit - Unit type used to measure performance level. Possible values include: 'DTU', 'VCores' + Unit PerformanceLevelUnit `json:"unit,omitempty"` +} + +// ProxyResource ARM proxy resource. +type ProxyResource struct { + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// Resource ARM resource. +type Resource struct { + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// ResourceMoveDefinition contains the information necessary to perform a resource move (rename). +type ResourceMoveDefinition struct { + // ID - The target ID for the resource + ID *string `json:"id,omitempty"` +} + +// ServerVersionCapability the server capability +type ServerVersionCapability struct { + // Name - The server version name. + Name *string `json:"name,omitempty"` + // SupportedEditions - The list of supported database editions. + SupportedEditions *[]EditionCapability `json:"supportedEditions,omitempty"` + // SupportedElasticPoolEditions - The list of supported elastic pool editions. + SupportedElasticPoolEditions *[]ElasticPoolEditionCapability `json:"supportedElasticPoolEditions,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// ServiceObjectiveCapability the service objectives capability. +type ServiceObjectiveCapability struct { + // ID - The unique ID of the service objective. + ID *uuid.UUID `json:"id,omitempty"` + // Name - The service objective name. + Name *string `json:"name,omitempty"` + // SupportedMaxSizes - The list of supported maximum database sizes. + SupportedMaxSizes *[]MaxSizeRangeCapability `json:"supportedMaxSizes,omitempty"` + // PerformanceLevel - The performance level. + PerformanceLevel *PerformanceLevelCapability `json:"performanceLevel,omitempty"` + // Sku - The sku. + Sku *Sku `json:"sku,omitempty"` + // SupportedLicenseTypes - List of supported license types. + SupportedLicenseTypes *[]LicenseTypeCapability `json:"supportedLicenseTypes,omitempty"` + // IncludedMaxSize - The included (free) max size. + IncludedMaxSize *MaxSizeCapability `json:"includedMaxSize,omitempty"` + // Status - The status of the capability. Possible values include: 'Visible', 'Available', 'Default', 'Disabled' + Status CapabilityStatus `json:"status,omitempty"` + // Reason - The reason for the capability not being available. + Reason *string `json:"reason,omitempty"` +} + +// Sku the resource model definition representing SKU +type Sku struct { + // Name - The name of the SKU. Ex - P3. It is typically a letter+number code + Name *string `json:"name,omitempty"` + // Tier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. + Tier *string `json:"tier,omitempty"` + // Size - The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string `json:"size,omitempty"` + // Family - If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string `json:"family,omitempty"` + // Capacity - If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. + Capacity *int32 `json:"capacity,omitempty"` +} + +// TdeCertificate a TDE certificate that can be uploaded into a server. +type TdeCertificate struct { + // TdeCertificateProperties - Resource properties. + *TdeCertificateProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TdeCertificate. +func (tc TdeCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tc.TdeCertificateProperties != nil { + objectMap["properties"] = tc.TdeCertificateProperties + } + if tc.ID != nil { + objectMap["id"] = tc.ID + } + if tc.Name != nil { + objectMap["name"] = tc.Name + } + if tc.Type != nil { + objectMap["type"] = tc.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for TdeCertificate struct. +func (tc *TdeCertificate) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var tdeCertificateProperties TdeCertificateProperties + err = json.Unmarshal(*v, &tdeCertificateProperties) + if err != nil { + return err + } + tc.TdeCertificateProperties = &tdeCertificateProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + tc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + tc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + tc.Type = &typeVar + } + } + } + + return nil +} + +// TdeCertificateProperties properties of a TDE certificate. +type TdeCertificateProperties struct { + // PrivateBlob - The base64 encoded certificate private blob. + PrivateBlob *string `json:"privateBlob,omitempty"` + // CertPassword - The certificate password. + CertPassword *string `json:"certPassword,omitempty"` +} + +// TdeCertificatesCreateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type TdeCertificatesCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *TdeCertificatesCreateFuture) Result(client TdeCertificatesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.TdeCertificatesCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.TdeCertificatesCreateFuture") + return + } + ar.Response = future.Response() + return +} + +// TrackedResource ARM tracked top level resource. +type TrackedResource struct { + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TrackedResource. +func (tr TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tr.Location != nil { + objectMap["location"] = tr.Location + } + if tr.Tags != nil { + objectMap["tags"] = tr.Tags + } + if tr.ID != nil { + objectMap["id"] = tr.ID + } + if tr.Name != nil { + objectMap["name"] = tr.Name + } + if tr.Type != nil { + objectMap["type"] = tr.Type + } + return json.Marshal(objectMap) +} + +// VulnerabilityAssessmentRecurringScansProperties properties of a Vulnerability Assessment recurring scans. +type VulnerabilityAssessmentRecurringScansProperties struct { + // IsEnabled - Recurring scans state. + IsEnabled *bool `json:"isEnabled,omitempty"` + // EmailSubscriptionAdmins - Specifies that the schedule scan notification will be is sent to the subscription administrators. + EmailSubscriptionAdmins *bool `json:"emailSubscriptionAdmins,omitempty"` + // Emails - Specifies an array of e-mail addresses to which the scan notification is sent. + Emails *[]string `json:"emails,omitempty"` +} + +// VulnerabilityAssessmentScanError properties of a vulnerability assessment scan error. +type VulnerabilityAssessmentScanError struct { + // Code - The error code. + Code *string `json:"code,omitempty"` + // Message - The error message. + Message *string `json:"message,omitempty"` +} + +// VulnerabilityAssessmentScanRecord a vulnerability assessment scan record. +type VulnerabilityAssessmentScanRecord struct { + autorest.Response `json:"-"` + // VulnerabilityAssessmentScanRecordProperties - Resource properties. + *VulnerabilityAssessmentScanRecordProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for VulnerabilityAssessmentScanRecord. +func (vasr VulnerabilityAssessmentScanRecord) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if vasr.VulnerabilityAssessmentScanRecordProperties != nil { + objectMap["properties"] = vasr.VulnerabilityAssessmentScanRecordProperties + } + if vasr.ID != nil { + objectMap["id"] = vasr.ID + } + if vasr.Name != nil { + objectMap["name"] = vasr.Name + } + if vasr.Type != nil { + objectMap["type"] = vasr.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for VulnerabilityAssessmentScanRecord struct. +func (vasr *VulnerabilityAssessmentScanRecord) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var vulnerabilityAssessmentScanRecordProperties VulnerabilityAssessmentScanRecordProperties + err = json.Unmarshal(*v, &vulnerabilityAssessmentScanRecordProperties) + if err != nil { + return err + } + vasr.VulnerabilityAssessmentScanRecordProperties = &vulnerabilityAssessmentScanRecordProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + vasr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + vasr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + vasr.Type = &typeVar + } + } + } + + return nil +} + +// VulnerabilityAssessmentScanRecordListResult a list of vulnerability assessment scan records. +type VulnerabilityAssessmentScanRecordListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]VulnerabilityAssessmentScanRecord `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// VulnerabilityAssessmentScanRecordListResultIterator provides access to a complete listing of +// VulnerabilityAssessmentScanRecord values. +type VulnerabilityAssessmentScanRecordListResultIterator struct { + i int + page VulnerabilityAssessmentScanRecordListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *VulnerabilityAssessmentScanRecordListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter VulnerabilityAssessmentScanRecordListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter VulnerabilityAssessmentScanRecordListResultIterator) Response() VulnerabilityAssessmentScanRecordListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter VulnerabilityAssessmentScanRecordListResultIterator) Value() VulnerabilityAssessmentScanRecord { + if !iter.page.NotDone() { + return VulnerabilityAssessmentScanRecord{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (vasrlr VulnerabilityAssessmentScanRecordListResult) IsEmpty() bool { + return vasrlr.Value == nil || len(*vasrlr.Value) == 0 +} + +// vulnerabilityAssessmentScanRecordListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (vasrlr VulnerabilityAssessmentScanRecordListResult) vulnerabilityAssessmentScanRecordListResultPreparer() (*http.Request, error) { + if vasrlr.NextLink == nil || len(to.String(vasrlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(vasrlr.NextLink))) +} + +// VulnerabilityAssessmentScanRecordListResultPage contains a page of VulnerabilityAssessmentScanRecord values. +type VulnerabilityAssessmentScanRecordListResultPage struct { + fn func(VulnerabilityAssessmentScanRecordListResult) (VulnerabilityAssessmentScanRecordListResult, error) + vasrlr VulnerabilityAssessmentScanRecordListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *VulnerabilityAssessmentScanRecordListResultPage) Next() error { + next, err := page.fn(page.vasrlr) + if err != nil { + return err + } + page.vasrlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page VulnerabilityAssessmentScanRecordListResultPage) NotDone() bool { + return !page.vasrlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page VulnerabilityAssessmentScanRecordListResultPage) Response() VulnerabilityAssessmentScanRecordListResult { + return page.vasrlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page VulnerabilityAssessmentScanRecordListResultPage) Values() []VulnerabilityAssessmentScanRecord { + if page.vasrlr.IsEmpty() { + return nil + } + return *page.vasrlr.Value +} + +// VulnerabilityAssessmentScanRecordProperties properties of a vulnerability assessment scan record. +type VulnerabilityAssessmentScanRecordProperties struct { + // ScanID - The scan ID. + ScanID *string `json:"scanId,omitempty"` + // TriggerType - The scan trigger type. Possible values include: 'OnDemand', 'Recurring' + TriggerType VulnerabilityAssessmentScanTriggerType `json:"triggerType,omitempty"` + // State - The scan status. Possible values include: 'VulnerabilityAssessmentScanStatePassed', 'VulnerabilityAssessmentScanStateFailed', 'VulnerabilityAssessmentScanStateFailedToRun', 'VulnerabilityAssessmentScanStateInProgress' + State VulnerabilityAssessmentScanState `json:"state,omitempty"` + // StartTime - The scan start time (UTC). + StartTime *date.Time `json:"startTime,omitempty"` + // EndTime - The scan end time (UTC). + EndTime *date.Time `json:"endTime,omitempty"` + // Errors - The scan errors. + Errors *[]VulnerabilityAssessmentScanError `json:"errors,omitempty"` + // StorageContainerPath - The scan results storage container path. + StorageContainerPath *string `json:"storageContainerPath,omitempty"` + // NumberOfFailedSecurityChecks - The number of failed security checks. + NumberOfFailedSecurityChecks *int32 `json:"numberOfFailedSecurityChecks,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/tdecertificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/tdecertificates.go new file mode 100644 index 000000000000..41eab8cc93b7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/tdecertificates.go @@ -0,0 +1,124 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// TdeCertificatesClient is the the Azure SQL Database management API provides a RESTful set of web services that +// interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, +// and delete databases. +type TdeCertificatesClient struct { + BaseClient +} + +// NewTdeCertificatesClient creates an instance of the TdeCertificatesClient client. +func NewTdeCertificatesClient(subscriptionID string) TdeCertificatesClient { + return NewTdeCertificatesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewTdeCertificatesClientWithBaseURI creates an instance of the TdeCertificatesClient client. +func NewTdeCertificatesClientWithBaseURI(baseURI string, subscriptionID string) TdeCertificatesClient { + return TdeCertificatesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create creates a TDE certificate for a given server. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serverName - the name of the server. +// parameters - the requested TDE certificate to be created or updated. +func (client TdeCertificatesClient) Create(ctx context.Context, resourceGroupName string, serverName string, parameters TdeCertificate) (result TdeCertificatesCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TdeCertificateProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.TdeCertificateProperties.PrivateBlob", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("sql.TdeCertificatesClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, serverName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.TdeCertificatesClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.TdeCertificatesClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client TdeCertificatesClient) CreatePreparer(ctx context.Context, resourceGroupName string, serverName string, parameters TdeCertificate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serverName": autorest.Encode("path", serverName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/tdeCertificates", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client TdeCertificatesClient) CreateSender(req *http.Request) (future TdeCertificatesCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client TdeCertificatesClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/version.go new file mode 100644 index 000000000000..d6e224054971 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/version.go @@ -0,0 +1,30 @@ +package sql + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + version.Number + " sql/2017-10-01-preview" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/vendor.json b/vendor/vendor.json index c8d7b2132bbf..093fd333f903 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -235,12 +235,12 @@ "versionExact": "v20.1.0" }, { - "checksumSHA1": "MIMQxpOPfmVbgeDkI5u9qn4hIt4=", + "checksumSHA1": "dOTq3QXVgEkhOV23gEhom7VQOgk=", "path": "github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management", - "revision": "fbe7db0e3f9793ba3e5704efbab84f51436c136e", - "revisionTime": "2018-07-03T19:15:42Z", - "version": "v18.0.0", - "versionExact": "v18.0.0" + "revision": "2935c0241c74bd8549b843978dd6fc1be6f48b4a", + "revisionTime": "2018-08-31T14:25:13Z", + "version": "v20.1.0", + "versionExact": "v20.1.0" }, { "checksumSHA1": "jLzkSZFf/yBGECyJHTVOHN2oI2k=", @@ -250,6 +250,14 @@ "version": "v20.1.0", "versionExact": "v20.1.0" }, + { + "checksumSHA1": "y8HaZNznGAl6orDBEW1B6gOEWCw=", + "path": "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql", + "revision": "2935c0241c74bd8549b843978dd6fc1be6f48b4a", + "revisionTime": "2018-08-31T14:25:13Z", + "version": "v20.1.0", + "versionExact": "v20.1.0" + }, { "checksumSHA1": "UWSnIzZywuEpEevbPfbPNLk1dFk=", "path": "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices", From be32e90a59290dff2813ad9708c47c50751e0d61 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 3 Oct 2018 17:24:24 -0700 Subject: [PATCH 02/38] [wip] finished the expand functions --- azurerm/resource_arm_sql2017_elasticpool.go | 56 ++++++++++++++------- 1 file changed, 37 insertions(+), 19 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index 503b6cdd7f55..6d16a1793594 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -204,13 +204,21 @@ func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{ serverName := d.Get("server_name").(string) location := azureRMNormalizeLocation(d.Get("location").(string)) resGroup := d.Get("resource_group_name").(string) + kind := d.Get("kind").(string) sku := expandAzureRmSql2017ElasticPoolSku(d) properties := expandAzureRmSql2017ElasticPoolProperties(d) + resourceType := d.Get("type").(string) + tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ - Name: &elasticPoolName, + Sku: sku, + Kind: &kind, + ElasticPoolProperties: properties, Location: &location, - ElasticPoolProperties: expandAzureRmSql2017ElasticPoolProperties(d), + Tags: expandTags(tags), + ID: &elasticPoolName, + Name: &elasticPoolName, + Type: &resourceType, } future, err := client.CreateOrUpdate(ctx, resGroup, serverName, elasticPoolName, elasticPool) @@ -291,30 +299,40 @@ func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{ } func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { - edition := sql.ElasticPoolEdition(d.Get("edition").(string)) - dtu := int32(d.Get("dtu").(int)) + + state := sql.ElasticPoolState(d.Get("State").(string)) + maxSizeBytes := d.Get("MaxSizeBytes").(int64) + perDatabaseSettings := expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d) + zoneRedundant := d.Get("resource_group_name").(bool) + licenseType := sql.ElasticPoolLicenseType(d.Get("LicenseType").(string)) + + //edition := sql.ElasticPoolEdition(d.Get("edition").(string)) + //dtu := int32(d.Get("dtu").(int)) props := &sql.ElasticPoolProperties{ - Edition: edition, - Dtu: &dtu, + State: state, + MaxSizeBytes: utils.Int64(int64(maxSizeBytes)), + PerDatabaseSettings: perDatabaseSettings, + ZoneRedundant: utils.Bool(zoneRedundant), + LicenseType: licenseType, } - if databaseDtuMin, ok := d.GetOk("db_dtu_min"); ok { - databaseDtuMin := int32(databaseDtuMin.(int)) - props.DatabaseDtuMin = &databaseDtuMin - } + return props +} - if databaseDtuMax, ok := d.GetOk("db_dtu_max"); ok { - databaseDtuMax := int32(databaseDtuMax.(int)) - props.DatabaseDtuMax = &databaseDtuMax - } +func expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d *schema.ResourceData) *sql.ElasticPoolPerDatabaseSettings { + perDatabasSettings := d.Get("PerDatabaseSettings").([]interface{}) + perDatabaseSetting := perDatabasSettings[0].(map[string]interface{}) - if poolSize, ok := d.GetOk("pool_size"); ok { - poolSize := int32(poolSize.(int)) - props.StorageMB = &poolSize + minCapacity := perDatabaseSetting["MinCapacity"].(float64) + maxCapacity := perDatabaseSetting["MaxCapacity"].(float64) + + elasticPoolPerDatabaseSettings := &sql.ElasticPoolPerDatabaseSettings{ + MinCapacity: utils.Float(minCapacity), + MaxCapacity: utils.Float(maxCapacity), } - return props + return elasticPoolPerDatabaseSettings } func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { @@ -338,7 +356,7 @@ func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { return &sql.Sku{ Name: utils.String(name), - size: utils.String(size), + Size: utils.String(size), Tier: utils.String(tier), Family: utils.String(family), Capacity: utils.Int32(int32(capacity)), From e5043cb3edd0aebddf775412ae91b7599098453c Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 8 Oct 2018 19:23:03 -0700 Subject: [PATCH 03/38] [WIP] Updated code --- azurerm/resource_arm_sql2017_elasticpool.go | 137 ++++++++++---------- 1 file changed, 69 insertions(+), 68 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index 6d16a1793594..a34a7a89164a 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -3,9 +3,9 @@ package azurerm import ( "fmt" "log" - "time" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" + "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" @@ -32,24 +32,6 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), - "id": { - Type: schema.TypeString, - Required: false, - Computed: true, - }, - - "kind": { - Type: schema.TypeString, - Required: false, - Computed: true, - }, - - "type": { - Type: schema.TypeString, - Required: false, - Computed: true, - }, - "server_name": { Type: schema.TypeString, Required: true, @@ -103,7 +85,7 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "size": { Type: schema.TypeString, - Required: false, + Optional: true, DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, @@ -120,7 +102,7 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "family": { Type: schema.TypeString, - Required: false, + Optional: true, ValidateFunc: validation.StringInSlice([]string{ "Gen4", "Gen5", @@ -131,7 +113,7 @@ func resourceArmSql2017ElasticPool() *schema.Resource { }, }, - "properties": { + "elastic_pool_properties": { Type: schema.TypeList, Required: true, MaxItems: 1, @@ -139,7 +121,7 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Schema: map[string]*schema.Schema{ "state": { Type: schema.TypeInt, - Required: false, + Computed: true, }, "creation_date": { @@ -149,7 +131,7 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "max_size_bytes": { Type: schema.TypeInt, - Required: false, + Computed: true, }, "per_database_settings": { @@ -173,17 +155,12 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "zone_redundant": { Type: schema.TypeBool, - Required: false, + Computed: true, }, "license_type": { Type: schema.TypeString, - Required: false, - ValidateFunc: validation.StringInSlice([]string{ - "BasicPrice", - "LicenseIncluded", - }, true), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + Computed: true, }, }, }, @@ -201,22 +178,19 @@ func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{ log.Printf("[INFO] preparing arguments for SQL2017 ElasticPool creation.") elasticPoolName := d.Get("name").(string) - serverName := d.Get("server_name").(string) + serverName := azureRMNormalizeLocation(d.Get("server_name").(string)) location := azureRMNormalizeLocation(d.Get("location").(string)) resGroup := d.Get("resource_group_name").(string) - kind := d.Get("kind").(string) sku := expandAzureRmSql2017ElasticPoolSku(d) properties := expandAzureRmSql2017ElasticPoolProperties(d) resourceType := d.Get("type").(string) tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ - Sku: sku, - Kind: &kind, + Sku: sku, ElasticPoolProperties: properties, Location: &location, Tags: expandTags(tags), - ID: &elasticPoolName, Name: &elasticPoolName, Type: &resourceType, } @@ -245,10 +219,10 @@ func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{ } func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).sqlElasticPoolsClient + client := meta.(*ArmClient).sql2017ElasticPoolsClient ctx := meta.(*ArmClient).StopContext - resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) + resGroup, serverName, name, err := parseArmSql2017ElasticPoolId(d.Id()) if err != nil { return err } @@ -259,33 +233,45 @@ func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return fmt.Errorf("Error making Read request on Sql Elastic Pool %s: %s", name, err) + return fmt.Errorf("Error making Read request on Sql2017 Elastic Pool %s: %s", name, err) } d.Set("name", resp.Name) d.Set("resource_group_name", resGroup) + if location := resp.Location; location != nil { d.Set("location", azureRMNormalizeLocation(*location)) } + d.Set("server_name", serverName) - if elasticPool := resp.ElasticPoolProperties; elasticPool != nil { - d.Set("edition", string(elasticPool.Edition)) - d.Set("dtu", int(*elasticPool.Dtu)) - d.Set("db_dtu_min", int(*elasticPool.DatabaseDtuMin)) - d.Set("db_dtu_max", int(*elasticPool.DatabaseDtuMax)) - d.Set("pool_size", int(*elasticPool.StorageMB)) + if elasticPoolProperties := resp.ElasticPoolProperties; elasticPoolProperties != nil { + if err := d.Set("per_database_settings", flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(elasticPoolProperties.PerDatabaseSettings)); err != nil { + return fmt.Errorf("Error flattening `per_database_settings`: %+v", err) + } + + if maxSizeBytes := elasticPoolProperties.MaxSizeBytes; maxSizeBytes != nil { + d.Set("max_size_bytes", elasticPoolProperties.MaxSizeBytes) + } + + d.Set("state", string(elasticPoolProperties.State)) + + if date := elasticPoolProperties.CreationDate; date != nil { + d.Set("creation_date", date.String()) + } - if date := elasticPool.CreationDate; date != nil { - d.Set("creation_date", date.Format(time.RFC3339)) + if zoneRedundant := elasticPoolProperties.ZoneRedundant; zoneRedundant != nil { + d.Set("zone_redundant", bool(*elasticPoolProperties.ZoneRedundant)) } + + d.Set("license_type", string(elasticPoolProperties.LicenseType)) } return nil } func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).sqlElasticPoolsClient + client := meta.(*ArmClient).sql2017ElasticPoolsClient ctx := meta.(*ArmClient).StopContext resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) @@ -299,19 +285,20 @@ func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{ } func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { + elasticPoolProperties := d.Get("elastic_pool_properties").([]interface{}) + elasticPoolProperty := elasticPoolProperties[0].(map[string]interface{}) - state := sql.ElasticPoolState(d.Get("State").(string)) - maxSizeBytes := d.Get("MaxSizeBytes").(int64) - perDatabaseSettings := expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d) - zoneRedundant := d.Get("resource_group_name").(bool) - licenseType := sql.ElasticPoolLicenseType(d.Get("LicenseType").(string)) - - //edition := sql.ElasticPoolEdition(d.Get("edition").(string)) - //dtu := int32(d.Get("dtu").(int)) + state := sql.ElasticPoolState(elasticPoolProperty["State"].(string)) + creationDate, _ := elasticPoolProperty["CreationDate"].(date.Time) + maxSizeBytes := elasticPoolProperty["MaxSizeBytes"].(int64) + perDatabaseSettings := expandAzureRmSql2017ElasticPoolPerDatabaseSettings(elasticPoolProperty) + zoneRedundant := elasticPoolProperty["ZoneRedundant"].(bool) + licenseType := sql.ElasticPoolLicenseType(elasticPoolProperty["LicenseType"].(string)) props := &sql.ElasticPoolProperties{ State: state, - MaxSizeBytes: utils.Int64(int64(maxSizeBytes)), + CreationDate: &creationDate, + MaxSizeBytes: &maxSizeBytes, PerDatabaseSettings: perDatabaseSettings, ZoneRedundant: utils.Bool(zoneRedundant), LicenseType: licenseType, @@ -320,8 +307,17 @@ func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.Elas return props } -func expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d *schema.ResourceData) *sql.ElasticPoolPerDatabaseSettings { - perDatabasSettings := d.Get("PerDatabaseSettings").([]interface{}) +func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { + id, err := parseAzureResourceID(sqlElasticPoolId) + if err != nil { + return "", "", "", fmt.Errorf("[ERROR] Unable to parse SQL2017 ElasticPool ID %q: %+v", sqlElasticPoolId, err) + } + + return id.ResourceGroup, id.Path["servers"], id.Path["elasticPools"], nil +} + +func expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d map[string]interface{}) *sql.ElasticPoolPerDatabaseSettings { + perDatabasSettings := d["per_database_settings"].([]interface{}) perDatabaseSetting := perDatabasSettings[0].(map[string]interface{}) minCapacity := perDatabaseSetting["MinCapacity"].(float64) @@ -335,15 +331,6 @@ func expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d *schema.ResourceData) return elasticPoolPerDatabaseSettings } -func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { - id, err := parseAzureResourceID(sqlElasticPoolId) - if err != nil { - return "", "", "", fmt.Errorf("[ERROR] Unable to parse SQL ElasticPool ID %q: %+v", sqlElasticPoolId, err) - } - - return id.ResourceGroup, id.Path["servers"], id.Path["elasticPools"], nil -} - func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { skus := d.Get("sku").([]interface{}) sku := skus[0].(map[string]interface{}) @@ -362,3 +349,17 @@ func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { Capacity: utils.Int32(int32(capacity)), } } + +func flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp *sql.ElasticPoolPerDatabaseSettings) []interface{} { + perDatabaseSettings := map[string]interface{}{} + + if minCapacity := resp.MinCapacity; minCapacity != nil { + perDatabaseSettings["min_capacity"] = *minCapacity + } + + if maxCapacity := resp.MinCapacity; maxCapacity != nil { + perDatabaseSettings["max_capacity"] = *maxCapacity + } + + return []interface{}{perDatabaseSettings} +} From dcc4cfd43bd929cf3385ca25de039ae22e365093 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 9 Oct 2018 19:29:59 -0700 Subject: [PATCH 04/38] [WIP] Working now testing --- azurerm/resource_arm_sql2017_elasticpool.go | 184 +++++++++----------- 1 file changed, 86 insertions(+), 98 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index a34a7a89164a..ec2f5aebe7b4 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -5,9 +5,7 @@ import ( "log" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" - "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/terraform/helper/schema" - "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -45,42 +43,14 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - "B_Gen4_1", - "B_Gen4_2", - "B_Gen5_1", - "B_Gen5_2", - "GP_Gen4_2", - "GP_Gen4_4", - "GP_Gen4_8", - "GP_Gen4_16", - "GP_Gen4_32", - "GP_Gen5_2", - "GP_Gen5_4", - "GP_Gen5_8", - "GP_Gen5_16", - "GP_Gen5_32", - "MO_Gen5_2", - "MO_Gen5_4", - "MO_Gen5_8", - "MO_Gen5_16", - }, true), + Type: schema.TypeString, + Required: true, DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, "capacity": { Type: schema.TypeInt, Required: true, - ValidateFunc: validateIntInSlice([]int{ - 1, - 2, - 4, - 8, - 16, - 32, - }), }, "size": { @@ -90,23 +60,14 @@ func resourceArmSql2017ElasticPool() *schema.Resource { }, "tier": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice([]string{ - "Basic", - "GeneralPurpose", - "MemoryOptimized", - }, true), + Type: schema.TypeString, + Required: true, DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, "family": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - "Gen4", - "Gen5", - }, true), + Type: schema.TypeString, + Optional: true, DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, }, @@ -120,7 +81,7 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "state": { - Type: schema.TypeInt, + Type: schema.TypeString, Computed: true, }, @@ -178,12 +139,11 @@ func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{ log.Printf("[INFO] preparing arguments for SQL2017 ElasticPool creation.") elasticPoolName := d.Get("name").(string) - serverName := azureRMNormalizeLocation(d.Get("server_name").(string)) + serverName := d.Get("server_name").(string) location := azureRMNormalizeLocation(d.Get("location").(string)) resGroup := d.Get("resource_group_name").(string) sku := expandAzureRmSql2017ElasticPoolSku(d) properties := expandAzureRmSql2017ElasticPoolProperties(d) - resourceType := d.Get("type").(string) tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ @@ -192,7 +152,6 @@ func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{ Location: &location, Tags: expandTags(tags), Name: &elasticPoolName, - Type: &resourceType, } future, err := client.CreateOrUpdate(ctx, resGroup, serverName, elasticPoolName, elasticPool) @@ -245,28 +204,16 @@ func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) d.Set("server_name", serverName) - if elasticPoolProperties := resp.ElasticPoolProperties; elasticPoolProperties != nil { - if err := d.Set("per_database_settings", flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(elasticPoolProperties.PerDatabaseSettings)); err != nil { - return fmt.Errorf("Error flattening `per_database_settings`: %+v", err) - } - - if maxSizeBytes := elasticPoolProperties.MaxSizeBytes; maxSizeBytes != nil { - d.Set("max_size_bytes", elasticPoolProperties.MaxSizeBytes) - } - - d.Set("state", string(elasticPoolProperties.State)) - - if date := elasticPoolProperties.CreationDate; date != nil { - d.Set("creation_date", date.String()) - } - - if zoneRedundant := elasticPoolProperties.ZoneRedundant; zoneRedundant != nil { - d.Set("zone_redundant", bool(*elasticPoolProperties.ZoneRedundant)) - } + if err := d.Set("sku", flattenAzureRmSql2017ElasticPoolSku(resp.Sku)); err != nil { + return fmt.Errorf("Error flattening `sku`: %+v", err) + } - d.Set("license_type", string(elasticPoolProperties.LicenseType)) + if err := d.Set("elastic_pool_properties", flattenAzureRmSql2017ElasticPoolProperties(resp.ElasticPoolProperties)); err != nil { + return fmt.Errorf("Error flattening `elastic_pool_properties`: %+v", err) } + flattenAndSetTags(d, resp.Tags) + return nil } @@ -284,29 +231,6 @@ func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{ return err } -func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { - elasticPoolProperties := d.Get("elastic_pool_properties").([]interface{}) - elasticPoolProperty := elasticPoolProperties[0].(map[string]interface{}) - - state := sql.ElasticPoolState(elasticPoolProperty["State"].(string)) - creationDate, _ := elasticPoolProperty["CreationDate"].(date.Time) - maxSizeBytes := elasticPoolProperty["MaxSizeBytes"].(int64) - perDatabaseSettings := expandAzureRmSql2017ElasticPoolPerDatabaseSettings(elasticPoolProperty) - zoneRedundant := elasticPoolProperty["ZoneRedundant"].(bool) - licenseType := sql.ElasticPoolLicenseType(elasticPoolProperty["LicenseType"].(string)) - - props := &sql.ElasticPoolProperties{ - State: state, - CreationDate: &creationDate, - MaxSizeBytes: &maxSizeBytes, - PerDatabaseSettings: perDatabaseSettings, - ZoneRedundant: utils.Bool(zoneRedundant), - LicenseType: licenseType, - } - - return props -} - func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { id, err := parseAzureResourceID(sqlElasticPoolId) if err != nil { @@ -316,19 +240,35 @@ func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, stri return id.ResourceGroup, id.Path["servers"], id.Path["elasticPools"], nil } -func expandAzureRmSql2017ElasticPoolPerDatabaseSettings(d map[string]interface{}) *sql.ElasticPoolPerDatabaseSettings { - perDatabasSettings := d["per_database_settings"].([]interface{}) - perDatabaseSetting := perDatabasSettings[0].(map[string]interface{}) +func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { + elasticPoolProperties := d.Get("elastic_pool_properties").([]interface{}) + elasticPoolProperty := elasticPoolProperties[0].(map[string]interface{}) + + // state := elasticPoolProperty["state"].(string) + // maxSizeBytes := int64(elasticPoolProperty["max_size_bytes"].(int)) + // zoneRedundant := elasticPoolProperty["zone_redundant"].(bool) + // licenseType := elasticPoolProperty["license_type"].(string) + + perDatabaseSettings := elasticPoolProperty["per_database_settings"].([]interface{}) + perDatabaseSetting := perDatabaseSettings[0].(map[string]interface{}) - minCapacity := perDatabaseSetting["MinCapacity"].(float64) - maxCapacity := perDatabaseSetting["MaxCapacity"].(float64) + minCapacity := perDatabaseSetting["min_capacity"].(float64) + maxCapacity := perDatabaseSetting["max_capacity"].(float64) elasticPoolPerDatabaseSettings := &sql.ElasticPoolPerDatabaseSettings{ MinCapacity: utils.Float(minCapacity), MaxCapacity: utils.Float(maxCapacity), } - return elasticPoolPerDatabaseSettings + props := &sql.ElasticPoolProperties{ + // State: sql.ElasticPoolState(state), + // MaxSizeBytes: &maxSizeBytes, + PerDatabaseSettings: elasticPoolPerDatabaseSettings, + // ZoneRedundant: utils.Bool(zoneRedundant), + // LicenseType: sql.ElasticPoolLicenseType(licenseType), + } + + return props } func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { @@ -350,6 +290,54 @@ func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { } } +func flattenAzureRmSql2017ElasticPoolSku(resp *sql.Sku) []interface{} { + values := map[string]interface{}{} + + if name := resp.Name; name != nil { + values["name"] = *name + } + + if size := resp.Size; size != nil { + values["size"] = *size + } + + values["tier"] = *resp.Tier + + if family := resp.Family; family != nil { + values["family"] = *family + } + + if capacity := resp.Capacity; capacity != nil { + values["capacity"] = *capacity + } + + return []interface{}{values} +} + +func flattenAzureRmSql2017ElasticPoolProperties(resp *sql.ElasticPoolProperties) []interface{} { + elasticPoolProperty := map[string]interface{}{} + + if maxSizeBytes := resp.MaxSizeBytes; maxSizeBytes != nil { + elasticPoolProperty["max_size_bytes"] = *maxSizeBytes + } + + elasticPoolProperty["state"] = sql.ElasticPoolState(resp.State) + + if date := resp.CreationDate; date != nil { + elasticPoolProperty["creation_date"] = date.String() + } + + if zoneRedundant := resp.ZoneRedundant; zoneRedundant != nil { + elasticPoolProperty["zone_redundant"] = *zoneRedundant + } + + elasticPoolProperty["license_type"] = string(resp.LicenseType) + + elasticPoolProperty["per_database_settings"] = flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp.PerDatabaseSettings) + + return []interface{}{elasticPoolProperty} +} + func flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp *sql.ElasticPoolPerDatabaseSettings) []interface{} { perDatabaseSettings := map[string]interface{}{} @@ -357,7 +345,7 @@ func flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp *sql.ElasticPoolPe perDatabaseSettings["min_capacity"] = *minCapacity } - if maxCapacity := resp.MinCapacity; maxCapacity != nil { + if maxCapacity := resp.MaxCapacity; maxCapacity != nil { perDatabaseSettings["max_capacity"] = *maxCapacity } From 007a68d77bbf5b8aa6c36b3ae186ae61c8f342d5 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 12 Oct 2018 19:08:44 -0700 Subject: [PATCH 05/38] For WIP PR --- azurerm/resource_arm_sql2017_elasticpool.go | 117 +++++++++++++------- 1 file changed, 76 insertions(+), 41 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index ec2f5aebe7b4..af76c9ef26eb 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -6,6 +6,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -43,8 +44,41 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "BasicPool", + "StandardPool", + "PremiumPool", + "GP_Gen4_2", + "GP_Gen4_4", + "GP_Gen4_8", + "GP_Gen4_16", + "GP_Gen4_24", + "GP_Gen5_2", + "GP_Gen5_4", + "GP_Gen5_8", + "GP_Gen5_16", + "GP_Gen5_24", + "BC_Gen4_2", + "BC_Gen4_4", + "BC_Gen4_8", + "BC_Gen4_16", + "BC_Gen4_20", + "BC_Gen4_24", + "BC_Gen4_32", + "BC_Gen4_40", + "BC_Gen4_80", + "BC_Gen5_2", + "BC_Gen5_4", + "BC_Gen5_8", + "BC_Gen5_16", + "BC_Gen5_20", + "BC_Gen5_24", + "BC_Gen5_32", + "BC_Gen5_40", + "BC_Gen5_80", + }, true), DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, @@ -60,24 +94,54 @@ func resourceArmSql2017ElasticPool() *schema.Resource { }, "tier": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "Basic", + "Standard", + "Premium", + "GeneralPurpose", + "BusinessCritical", + }, true), DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, "family": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "Gen4", + "Gen5", + }, true), DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, }, }, }, - "elastic_pool_properties": { + "per_database_settings": { Type: schema.TypeList, Required: true, MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "min_capacity": { + Type: schema.TypeFloat, + Required: true, + }, + + "max_capacity": { + Type: schema.TypeFloat, + Required: true, + }, + }, + }, + }, + + "elastic_pool_properties": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "state": { @@ -95,25 +159,6 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Computed: true, }, - "per_database_settings": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "min_capacity": { - Type: schema.TypeFloat, - Required: true, - }, - - "max_capacity": { - Type: schema.TypeFloat, - Required: true, - }, - }, - }, - }, - "zone_redundant": { Type: schema.TypeBool, Computed: true, @@ -212,6 +257,10 @@ func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error flattening `elastic_pool_properties`: %+v", err) } + if err := d.Set("per_database_settings", flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp.ElasticPoolProperties.PerDatabaseSettings)); err != nil { + return fmt.Errorf("Error flattening `per_database_settings`: %+v", err) + } + flattenAndSetTags(d, resp.Tags) return nil @@ -241,15 +290,7 @@ func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, stri } func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { - elasticPoolProperties := d.Get("elastic_pool_properties").([]interface{}) - elasticPoolProperty := elasticPoolProperties[0].(map[string]interface{}) - - // state := elasticPoolProperty["state"].(string) - // maxSizeBytes := int64(elasticPoolProperty["max_size_bytes"].(int)) - // zoneRedundant := elasticPoolProperty["zone_redundant"].(bool) - // licenseType := elasticPoolProperty["license_type"].(string) - - perDatabaseSettings := elasticPoolProperty["per_database_settings"].([]interface{}) + perDatabaseSettings := d.Get("per_database_settings").([]interface{}) perDatabaseSetting := perDatabaseSettings[0].(map[string]interface{}) minCapacity := perDatabaseSetting["min_capacity"].(float64) @@ -261,11 +302,7 @@ func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.Elas } props := &sql.ElasticPoolProperties{ - // State: sql.ElasticPoolState(state), - // MaxSizeBytes: &maxSizeBytes, PerDatabaseSettings: elasticPoolPerDatabaseSettings, - // ZoneRedundant: utils.Bool(zoneRedundant), - // LicenseType: sql.ElasticPoolLicenseType(licenseType), } return props @@ -333,8 +370,6 @@ func flattenAzureRmSql2017ElasticPoolProperties(resp *sql.ElasticPoolProperties) elasticPoolProperty["license_type"] = string(resp.LicenseType) - elasticPoolProperty["per_database_settings"] = flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp.PerDatabaseSettings) - return []interface{}{elasticPoolProperty} } From e54cfaacd57458e00f257b1e64720fbb2fc849e3 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 15 Oct 2018 17:45:18 -0700 Subject: [PATCH 06/38] [WIP] Resolve Conflict With Master --- azurerm/provider.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/provider.go b/azurerm/provider.go index dfef9143e296..c6f12fc25eb5 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -268,6 +268,7 @@ func Provider() terraform.ResourceProvider { "azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(), "azurerm_sql_database": resourceArmSqlDatabase(), "azurerm_sql_elasticpool": resourceArmSqlElasticPool(), + "azurerm_sql2017_elasticpool": resourceArmSql2017ElasticPool(), "azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), "azurerm_sql_active_directory_administrator": resourceArmSqlAdministrator(), "azurerm_sql_server": resourceArmSqlServer(), From 14d386904368f890133013c642076b2ddc4d1875 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 16 Oct 2018 11:13:25 -0700 Subject: [PATCH 07/38] [WIP] Resolve conflict. --- azurerm/provider.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/provider.go b/azurerm/provider.go index 0c80937485c3..59e3c4e00788 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -271,6 +271,7 @@ func Provider() terraform.ResourceProvider { "azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(), "azurerm_sql_database": resourceArmSqlDatabase(), "azurerm_sql_elasticpool": resourceArmSqlElasticPool(), + "azurerm_sql2017_elasticpool": resourceArmSql2017ElasticPool(), "azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), "azurerm_sql_active_directory_administrator": resourceArmSqlAdministrator(), "azurerm_sql_server": resourceArmSqlServer(), From 9a8a8a48f3d69fdfb31ee3ba1abb93ec0c6273c0 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 18 Oct 2018 17:11:40 -0700 Subject: [PATCH 08/38] [WIP] Fix conflict --- azurerm/config.go | 1 + .../resource_arm_sql2017_elasticpool_test.go | 218 ++++++++++++++++++ vendor/vendor.json | 10 +- 3 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 azurerm/resource_arm_sql2017_elasticpool_test.go diff --git a/azurerm/config.go b/azurerm/config.go index f66a490048b3..81b84afd5417 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -46,6 +46,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management" "github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/2017-08-01-preview/security" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2015-05-01-preview/sql" + sql2017 "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/backup" "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis" diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go new file mode 100644 index 000000000000..518718910318 --- /dev/null +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -0,0 +1,218 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMSqlElasticPool_basic(t *testing.T) { + ri := acctest.RandInt() + config := testAccAzureRMSqlElasticPool_basic(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists("azurerm_sql_elasticpool.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMSqlElasticPool_disappears(t *testing.T) { + resourceName := "azurerm_sql_elasticpool.test" + ri := acctest.RandInt() + config := testAccAzureRMSqlElasticPool_basic(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists(resourceName), + testCheckAzureRMSqlElasticPoolDisappears(resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAzureRMSqlElasticPool_resizeDtu(t *testing.T) { + resourceName := "azurerm_sql_elasticpool.test" + ri := acctest.RandInt() + location := testLocation() + preConfig := testAccAzureRMSqlElasticPool_basic(ri, location) + postConfig := testAccAzureRMSqlElasticPool_resizedDtu(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "dtu", "50"), + resource.TestCheckResourceAttr(resourceName, "pool_size", "5000"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "dtu", "100"), + resource.TestCheckResourceAttr(resourceName, "pool_size", "10000"), + ), + }, + }, + }) +} + +func testCheckAzureRMSqlElasticPoolExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serverName := rs.Primary.Attributes["server_name"] + poolName := rs.Primary.Attributes["name"] + + client := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + resp, err := client.Get(ctx, resourceGroup, serverName, poolName) + if err != nil { + return fmt.Errorf("Bad: Get on sqlElasticPoolsClient: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: SQL Elastic Pool %q on server: %q (resource group: %q) does not exist", name, serverName, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMSqlElasticPoolDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_sql_elasticpool" { + continue + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serverName := rs.Primary.Attributes["server_name"] + poolName := rs.Primary.Attributes["name"] + + resp, err := client.Get(ctx, resourceGroup, serverName, poolName) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("SQL Elastic Pool still exists:\n%#v", resp.ElasticPoolProperties) + } + } + + return nil +} + +func testCheckAzureRMSqlElasticPoolDisappears(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serverName := rs.Primary.Attributes["server_name"] + poolName := rs.Primary.Attributes["name"] + + client := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + _, err := client.Delete(ctx, resourceGroup, serverName, poolName) + if err != nil { + return fmt.Errorf("Bad: Delete on sqlElasticPoolsClient: %+v", err) + } + + return nil + } +} + +func testAccAzureRMSqlElasticPool_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctest-%[1]d" + location = "%s" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql_elasticpool" "test" { + name = "acctest-pool-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + edition = "Basic" + dtu = 50 + pool_size = 5000 +} +`, rInt, location) +} + +func testAccAzureRMSqlElasticPool_resizedDtu(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctest-%[1]d" + location = "%s" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql_elasticpool" "test" { + name = "acctest-pool-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + edition = "Basic" + dtu = 100 + pool_size = 10000 +} +`, rInt, location) +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 82219dee6b39..f019ad0ec896 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -281,7 +281,15 @@ "revisionTime": "2018-09-28T00:20:07Z", "version": "v21.1.0", "versionExact": "v21.1.0" - }, + }, + { + "checksumSHA1": "9DNPP6stp1NNPv78fx/Khyv723s=", + "path": "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql", + "revision": "6d20bdbae88c06c36d72eb512295417693bfdf4e", + "revisionTime": "2018-09-27T22:44:43Z", + "version": "v21.1.0", + "versionExact": "v21.1.0" + }, { "checksumSHA1": "P0456F5O0iLtB3RwYPZ8apWby6A=", "path": "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/backup", From e605c38a20d17f8431ee5438b702e3bd3fd2e932 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 19 Oct 2018 19:09:33 -0700 Subject: [PATCH 09/38] [WIP] CustomizeDiff validation --- azurerm/resource_arm_sql2017_elasticpool.go | 140 ++++++++++++++------ 1 file changed, 100 insertions(+), 40 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index af76c9ef26eb..b8ba677e041d 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -3,6 +3,7 @@ package azurerm import ( "fmt" "log" + "strings" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" "github.com/hashicorp/terraform/helper/schema" @@ -50,34 +51,10 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "BasicPool", "StandardPool", "PremiumPool", - "GP_Gen4_2", - "GP_Gen4_4", - "GP_Gen4_8", - "GP_Gen4_16", - "GP_Gen4_24", - "GP_Gen5_2", - "GP_Gen5_4", - "GP_Gen5_8", - "GP_Gen5_16", - "GP_Gen5_24", - "BC_Gen4_2", - "BC_Gen4_4", - "BC_Gen4_8", - "BC_Gen4_16", - "BC_Gen4_20", - "BC_Gen4_24", - "BC_Gen4_32", - "BC_Gen4_40", - "BC_Gen4_80", - "BC_Gen5_2", - "BC_Gen5_4", - "BC_Gen5_8", - "BC_Gen5_16", - "BC_Gen5_20", - "BC_Gen5_24", - "BC_Gen5_32", - "BC_Gen5_40", - "BC_Gen5_80", + "GP_Gen4", + "GP_Gen5", + "BC_Gen4", + "BC_Gen5", }, true), DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, @@ -87,12 +64,6 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Required: true, }, - "size": { - Type: schema.TypeString, - Optional: true, - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, - }, - "tier": { Type: schema.TypeString, Required: true, @@ -174,6 +145,101 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "tags": tagsSchema(), }, + + CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { + + name, _ := diff.GetOk("sku.0.name") + capacity, _ := diff.GetOk("sku.0.capacity") + minCapacity, _ := diff.GetOk("per_database_settings.0.min_capacity") + maxCapacity, _ := diff.GetOk("per_database_settings.0.max_capacity") + + if strings.HasPrefix(strings.ToLower(name.(string)), "gp_") { + + if capacity.(int) > 24 { + return fmt.Errorf("GeneralPurpose pricing tier only supports upto 24 vCores") + } + + if capacity.(int) < 1 { + return fmt.Errorf("GeneralPurpose pricing tier must have a minimum of 1 vCores") + } + + switch { + case capacity.(int) == 1: + case capacity.(int) == 2: + case capacity.(int) == 4: + case capacity.(int) == 8: + case capacity.(int) == 16: + case capacity.(int) == 24: + default: + return fmt.Errorf("GeneralPurpose pricing tier must have a capacity of 1, 2, 4, 8, 16, or 24 vCores") + } + + } + + if strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { + if capacity.(int) > 80 { + return fmt.Errorf("BusinessCritical pricing tier only supports upto 80 vCores") + } + + if capacity.(int) < 2 { + return fmt.Errorf("BusinessCritical pricing tier must have a minimum of 2 vCores") + } + + switch { + case capacity.(int) == 1: + case capacity.(int) == 2: + case capacity.(int) == 4: + case capacity.(int) == 8: + case capacity.(int) == 16: + case capacity.(int) == 24: + case capacity.(int) == 32: + case capacity.(int) == 40: + case capacity.(int) == 80: + default: + return fmt.Errorf("BusinessCritical pricing tier must have a capacity of 2, 4, 8, 16, 24, 32, 40, or 80 vCores") + } + } + + // vCore based + if (strings.HasPrefix(strings.ToLower(name.(string)), "gp_") || strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { + + capacity, _ := diff.GetOk("sku.0.capacity") + minCapacity, _ := diff.GetOk("per_database_settings.0.min_capacity") + maxCapacity, _ := diff.GetOk("per_database_settings.0.max_capacity") + + if maxCapacity.(float64) > capacity { + return fmt.Errorf("BusinessCritical pricing tier must have a capacity of 2, 4, 8, 16, 24, 32, 40, or 80 vCores") + } + + if maxCapacity.(float64) > capacity { + return fmt.Errorf("BusinessCritical and GeneralPurpose pricing tiers perDatabaseSettings maxCapacity must not be higher than the SKUs capacity setting") + } + + if minCapacity.(float64) > maxCapacity.(float64) { + return fmt.Errorf("perDatabaseSettings maxCapacity must be greater than or equal to the perDatabaseSettings minCapacity value") + } + } + + //DTU based + if !strings.HasPrefix(strings.ToLower(name.(string)), "gp_") && !strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { + + if maxCapacity.(float64) != math.Trunc(maxCapacity.(float64)) { + return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as thier maxCapacity") + } + + if minCapacity.(float64) != math.Trunc(minCapacity.(float64)) { + return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as thier minCapacity") + } + + if minCapacity.(float64) < 0 { + + } + + + } + + return nil + }, } } @@ -313,14 +379,12 @@ func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { sku := skus[0].(map[string]interface{}) name := sku["name"].(string) - size := sku["size"].(string) tier := sku["tier"].(string) family := sku["family"].(string) capacity := sku["capacity"].(int) return &sql.Sku{ Name: utils.String(name), - Size: utils.String(size), Tier: utils.String(tier), Family: utils.String(family), Capacity: utils.Int32(int32(capacity)), @@ -334,10 +398,6 @@ func flattenAzureRmSql2017ElasticPoolSku(resp *sql.Sku) []interface{} { values["name"] = *name } - if size := resp.Size; size != nil { - values["size"] = *size - } - values["tier"] = *resp.Tier if family := resp.Family; family != nil { From 6b9f6314a253b5fabcf27d94bd89b66e3ed7d64d Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 29 Oct 2018 15:23:57 -0700 Subject: [PATCH 10/38] [WIP] Vallidation Tests and fixed Conflict --- azurerm/resource_arm_sql2017_elasticpool.go | 30 +-- .../resource_arm_sql2017_elasticpool_test.go | 245 ++++++++++++++---- vendor/vendor.json | 12 +- 3 files changed, 223 insertions(+), 64 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index b8ba677e041d..3670923366a6 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -3,6 +3,7 @@ package azurerm import ( "fmt" "log" + "math" "strings" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" @@ -200,29 +201,26 @@ func resourceArmSql2017ElasticPool() *schema.Resource { } } - // vCore based - if (strings.HasPrefix(strings.ToLower(name.(string)), "gp_") || strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { - + // Addutional checks based of SKU type... + if strings.HasPrefix(strings.ToLower(name.(string)), "gp_") || strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { + // vCore based capacity, _ := diff.GetOk("sku.0.capacity") minCapacity, _ := diff.GetOk("per_database_settings.0.min_capacity") maxCapacity, _ := diff.GetOk("per_database_settings.0.max_capacity") - - if maxCapacity.(float64) > capacity { + + if maxCapacity.(float64) > capacity.(float64) { return fmt.Errorf("BusinessCritical pricing tier must have a capacity of 2, 4, 8, 16, 24, 32, 40, or 80 vCores") } - if maxCapacity.(float64) > capacity { - return fmt.Errorf("BusinessCritical and GeneralPurpose pricing tiers perDatabaseSettings maxCapacity must not be higher than the SKUs capacity setting") + if maxCapacity.(float64) > capacity.(float64) { + return fmt.Errorf("BusinessCritical and GeneralPurpose pricing tiers perDatabaseSettings maxCapacity must not be higher than the SKUs capacity value") } - if minCapacity.(float64) > maxCapacity.(float64) { + if minCapacity.(float64) > maxCapacity.(float64) { return fmt.Errorf("perDatabaseSettings maxCapacity must be greater than or equal to the perDatabaseSettings minCapacity value") } - } - - //DTU based - if !strings.HasPrefix(strings.ToLower(name.(string)), "gp_") && !strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { - + } else { + // DTU based if maxCapacity.(float64) != math.Trunc(maxCapacity.(float64)) { return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as thier maxCapacity") } @@ -231,11 +229,9 @@ func resourceArmSql2017ElasticPool() *schema.Resource { return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as thier minCapacity") } - if minCapacity.(float64) < 0 { - + if minCapacity.(float64) < 0.0 { + return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs per_database_settings min_capacity must be equal to or greater than zero") } - - } return nil diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go index 518718910318..76968b2e70a2 100644 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -10,40 +10,73 @@ import ( "github.com/hashicorp/terraform/terraform" ) -func TestAccAzureRMSqlElasticPool_basic(t *testing.T) { +func TestAccAzureRMSqlElasticPool2017_basic_DTU(t *testing.T) { + resourceName := "azurerm_sql2017_elasticpool.test" ri := acctest.RandInt() - config := testAccAzureRMSqlElasticPool_basic(ri, testLocation()) + config := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, testLocation()) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, Steps: []resource.TestStep{ { Config: config, Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPoolExists("azurerm_sql_elasticpool.test"), + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "BasicPool"), ), + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, }, }, }) } -func TestAccAzureRMSqlElasticPool_disappears(t *testing.T) { - resourceName := "azurerm_sql_elasticpool.test" +func TestAccAzureRMSqlElasticPool2017_basic_vCore(t *testing.T) { + resourceName := "azurerm_sql2017_elasticpool.test" + ri := acctest.RandInt() + config := testAccAzureRMSqlElasticPool2017_basic_vCore(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "GP_Gen5"), + ), + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }, + }) +} + +func TestAccAzureRMSqlElasticPool2017_disappears(t *testing.T) { + resourceName := "azurerm_sql2017_elasticpool.test" ri := acctest.RandInt() - config := testAccAzureRMSqlElasticPool_basic(ri, testLocation()) + config := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, testLocation()) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, Steps: []resource.TestStep{ { Config: config, Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPoolExists(resourceName), - testCheckAzureRMSqlElasticPoolDisappears(resourceName), + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + testCheckAzureRMSqlElasticPool2017Disappears(resourceName), ), ExpectNonEmptyPlan: true, }, @@ -51,39 +84,71 @@ func TestAccAzureRMSqlElasticPool_disappears(t *testing.T) { }) } -func TestAccAzureRMSqlElasticPool_resizeDtu(t *testing.T) { +func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { + resourceName := "azurerm_sql_elasticpool.test" + ri := acctest.RandInt() + location := testLocation() + preConfig := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, location) + postConfig := testAccAzureRMSqlElasticPool2017_resize_DTU(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "100"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "1000"), + ), + }, + }, + }) +} + +func TestAccAzureRMSqlElasticPool2017_resize_vCore(t *testing.T) { resourceName := "azurerm_sql_elasticpool.test" ri := acctest.RandInt() location := testLocation() - preConfig := testAccAzureRMSqlElasticPool_basic(ri, location) - postConfig := testAccAzureRMSqlElasticPool_resizedDtu(ri, location) + preConfig := testAccAzureRMSqlElasticPool2017_basic_vCore(ri, location) + postConfig := testAccAzureRMSqlElasticPool2017_resize_vCore(ri, location) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPoolDestroy, + CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, Steps: []resource.TestStep{ { Config: preConfig, Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPoolExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "dtu", "50"), - resource.TestCheckResourceAttr(resourceName, "pool_size", "5000"), + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.25"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "4"), ), }, { Config: postConfig, Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPoolExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "dtu", "100"), - resource.TestCheckResourceAttr(resourceName, "pool_size", "10000"), + testCheckAzureRMSqlElasticPool2017Exists(resourceName), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "8"), ), }, }, }) } -func testCheckAzureRMSqlElasticPoolExists(name string) resource.TestCheckFunc { +func testCheckAzureRMSqlElasticPool2017Exists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -94,28 +159,28 @@ func testCheckAzureRMSqlElasticPoolExists(name string) resource.TestCheckFunc { serverName := rs.Primary.Attributes["server_name"] poolName := rs.Primary.Attributes["name"] - client := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + client := testAccProvider.Meta().(*ArmClient).sql2017ElasticPoolsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext resp, err := client.Get(ctx, resourceGroup, serverName, poolName) if err != nil { - return fmt.Errorf("Bad: Get on sqlElasticPoolsClient: %+v", err) + return fmt.Errorf("Bad: Get on sql2017ElasticPoolsClient: %+v", err) } if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: SQL Elastic Pool %q on server: %q (resource group: %q) does not exist", name, serverName, resourceGroup) + return fmt.Errorf("Bad: SQL2017 Elastic Pool %q on server: %q (resource group: %q) does not exist", name, serverName, resourceGroup) } return nil } } -func testCheckAzureRMSqlElasticPoolDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient +func testCheckAzureRMSqlElasticPool2017Destroy(s *terraform.State) error { + client := testAccProvider.Meta().(*ArmClient).sql2017ElasticPoolsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_sql_elasticpool" { + if rs.Type != "azurerm_sql2017_elasticpool" { continue } @@ -130,14 +195,14 @@ func testCheckAzureRMSqlElasticPoolDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("SQL Elastic Pool still exists:\n%#v", resp.ElasticPoolProperties) + return fmt.Errorf("SQL2017 Elastic Pool still exists:\n%#v", resp.ElasticPoolProperties) } } return nil } -func testCheckAzureRMSqlElasticPoolDisappears(name string) resource.TestCheckFunc { +func testCheckAzureRMSqlElasticPool2017Disappears(name string) resource.TestCheckFunc { return func(s *terraform.State) error { // Ensure we have enough information in state to look up in API rs, ok := s.RootModule().Resources[name] @@ -149,19 +214,19 @@ func testCheckAzureRMSqlElasticPoolDisappears(name string) resource.TestCheckFun serverName := rs.Primary.Attributes["server_name"] poolName := rs.Primary.Attributes["name"] - client := testAccProvider.Meta().(*ArmClient).sqlElasticPoolsClient + client := testAccProvider.Meta().(*ArmClient).sql2017ElasticPoolsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext _, err := client.Delete(ctx, resourceGroup, serverName, poolName) if err != nil { - return fmt.Errorf("Bad: Delete on sqlElasticPoolsClient: %+v", err) + return fmt.Errorf("Bad: Delete on sql2017ElasticPoolsClient: %+v", err) } return nil } } -func testAccAzureRMSqlElasticPool_basic(rInt int, location string) string { +func testAccAzureRMSqlElasticPool2017_basic_DTU(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctest-%[1]d" @@ -177,19 +242,64 @@ resource "azurerm_sql_server" "test" { administrator_login_password = "4-v3ry-53cr37-p455w0rd" } -resource "azurerm_sql_elasticpool" "test" { - name = "acctest-pool-%[1]d" +resource "azurerm_sql2017_elasticpool" "test" { + name = "acctest-pool-dtu-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "BasicPool" + tier = "Basic" + capacity = 1000 + } + + per_database_settings { + min_capacity = 0 + max_capacity = 100 + } +} +`, rInt, location) +} + +func testAccAzureRMSqlElasticPool2017_basic_vCore(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctest-%[1]d" + location = "%s" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" - server_name = "${azurerm_sql_server.test.name}" - edition = "Basic" - dtu = 50 - pool_size = 5000 + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql2017_elasticpool" "test" { + name = "acctest-pool-vcore-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "GP_Gen5" + tier = "GeneralPurpose" + capacity = 4 + family = "Gen5" + } + + per_database_settings { + min_capacity = 0.25 + max_capacity = 4 + } } `, rInt, location) } -func testAccAzureRMSqlElasticPool_resizedDtu(rInt int, location string) string { +func testAccAzureRMSqlElasticPool2017_resize_DTU(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctest-%[1]d" @@ -205,14 +315,59 @@ resource "azurerm_sql_server" "test" { administrator_login_password = "4-v3ry-53cr37-p455w0rd" } -resource "azurerm_sql_elasticpool" "test" { - name = "acctest-pool-%[1]d" +resource "azurerm_sql2017_elasticpool" "test" { + name = "acctest-pool-dtu-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "BasicPool" + tier = "Basic" + capacity = 1000 + } + + per_database_settings { + min_capacity = 50 + max_capacity = 1000 + } +} +`, rInt, location) +} + +func testAccAzureRMSqlElasticPool2017_resize_vCore(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctest-%[1]d" + location = "%s" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" - server_name = "${azurerm_sql_server.test.name}" - edition = "Basic" - dtu = 100 - pool_size = 10000 + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql2017_elasticpool" "test" { + name = "acctest-pool-vcore-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "GP_Gen5" + tier = "GeneralPurpose" + capacity = 8 + family = "Gen5" + } + + per_database_settings { + min_capacity = 0 + max_capacity = 8 + } } `, rInt, location) } diff --git a/vendor/vendor.json b/vendor/vendor.json index fb2911d79e9c..18c43c0f3ffc 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -281,8 +281,8 @@ "revisionTime": "2018-10-19T17:11:53Z", "version": "v21.3.0", "versionExact": "v21.3.0" - }, - { + }, + { "checksumSHA1": "/lxvjQjQNmBuS4tOwMdG3n4nWd0=", "path": "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2015-05-01-preview/sql", "revision": "da91af54816b4cf72949c225a2d0980f51fab01b", @@ -290,6 +290,14 @@ "version": "v21.3.0", "versionExact": "v21.3.0" }, + { + "checksumSHA1": "A+vy/mTrX3aAqIjnZcAhIqQc/UU=", + "path": "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql", + "revision": "da91af54816b4cf72949c225a2d0980f51fab01b", + "revisionTime": "2018-10-19T17:11:53Z", + "version": "v21.3.0", + "versionExact": "v21.3.0" + }, { "checksumSHA1": "P0456F5O0iLtB3RwYPZ8apWby6A=", "path": "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/backup", From 990dadcaf85252366ec8179cd19b8a93e69686e7 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 29 Oct 2018 15:40:38 -0700 Subject: [PATCH 11/38] [WIP] Fixing Linting Error --- azurerm/resource_arm_sql2017_elasticpool.go | 6 +++--- .../resource_arm_sql2017_elasticpool_test.go | 20 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index 3670923366a6..877f00ae216f 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -222,11 +222,11 @@ func resourceArmSql2017ElasticPool() *schema.Resource { } else { // DTU based if maxCapacity.(float64) != math.Trunc(maxCapacity.(float64)) { - return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as thier maxCapacity") + return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as their maxCapacity") } if minCapacity.(float64) != math.Trunc(minCapacity.(float64)) { - return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as thier minCapacity") + return fmt.Errorf("BasicPool, StandardPool, and PremiumPool SKUs must have whole numbers as their minCapacity") } if minCapacity.(float64) < 0.0 { @@ -414,7 +414,7 @@ func flattenAzureRmSql2017ElasticPoolProperties(resp *sql.ElasticPoolProperties) elasticPoolProperty["max_size_bytes"] = *maxSizeBytes } - elasticPoolProperty["state"] = sql.ElasticPoolState(resp.State) + elasticPoolProperty["state"] = string(resp.State) if date := resp.CreationDate; date != nil { elasticPoolProperty["creation_date"] = date.String() diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go index 76968b2e70a2..c4e69ce3f7a4 100644 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -26,11 +26,11 @@ func TestAccAzureRMSqlElasticPool2017_basic_DTU(t *testing.T) { testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "sku.0.name", "BasicPool"), ), - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) @@ -52,11 +52,11 @@ func TestAccAzureRMSqlElasticPool2017_basic_vCore(t *testing.T) { testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "sku.0.name", "GP_Gen5"), ), - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, }, }, }) From f2a0ab85a9105e480114b4cff25dd44350b275c7 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 29 Oct 2018 17:12:16 -0700 Subject: [PATCH 12/38] [WIP] Fix Vendor issue --- azurerm/resource_arm_sql2017_elasticpool_test.go | 16 ++++++++-------- vendor/vendor.json | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go index c4e69ce3f7a4..21029174a7b2 100644 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -85,7 +85,7 @@ func TestAccAzureRMSqlElasticPool2017_disappears(t *testing.T) { } func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { - resourceName := "azurerm_sql_elasticpool.test" + resourceName := "azurerm_sql2017_elasticpool.test" ri := acctest.RandInt() location := testLocation() preConfig := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, location) @@ -100,16 +100,16 @@ func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "100"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100.0"), ), }, { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "1000"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "1000.0"), ), }, }, @@ -117,7 +117,7 @@ func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { } func TestAccAzureRMSqlElasticPool2017_resize_vCore(t *testing.T) { - resourceName := "azurerm_sql_elasticpool.test" + resourceName := "azurerm_sql2017_elasticpool.test" ri := acctest.RandInt() location := testLocation() preConfig := testAccAzureRMSqlElasticPool2017_basic_vCore(ri, location) @@ -133,7 +133,7 @@ func TestAccAzureRMSqlElasticPool2017_resize_vCore(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.25"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "4"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "4.0"), ), }, { @@ -141,7 +141,7 @@ func TestAccAzureRMSqlElasticPool2017_resize_vCore(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "8"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "8.0"), ), }, }, diff --git a/vendor/vendor.json b/vendor/vendor.json index 18c43c0f3ffc..5468d62d719f 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -281,8 +281,8 @@ "revisionTime": "2018-10-19T17:11:53Z", "version": "v21.3.0", "versionExact": "v21.3.0" - }, - { + }, + { "checksumSHA1": "/lxvjQjQNmBuS4tOwMdG3n4nWd0=", "path": "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2015-05-01-preview/sql", "revision": "da91af54816b4cf72949c225a2d0980f51fab01b", @@ -290,7 +290,7 @@ "version": "v21.3.0", "versionExact": "v21.3.0" }, - { + { "checksumSHA1": "A+vy/mTrX3aAqIjnZcAhIqQc/UU=", "path": "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql", "revision": "da91af54816b4cf72949c225a2d0980f51fab01b", @@ -299,7 +299,7 @@ "versionExact": "v21.3.0" }, { - "checksumSHA1": "P0456F5O0iLtB3RwYPZ8apWby6A=", + "checksumSHA1": "P0456F5O0iLtB3RwYPZ8apWby6A=", "path": "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/backup", "revision": "da91af54816b4cf72949c225a2d0980f51fab01b", "revisionTime": "2018-10-19T17:11:53Z", From 938f231c4072928390aedebcfdc7e9ed4d62f29e Mon Sep 17 00:00:00 2001 From: Su Shi <1684739+metacpp@users.noreply.github.com> Date: Mon, 29 Oct 2018 18:13:39 -0700 Subject: [PATCH 13/38] added missed files for sql package. --- ...asevulnerabilityassessmentrulebaselines.go | 282 +++++++ ...manageddatabasevulnerabilityassessments.go | 267 +++++++ ...geddatabasevulnerabilityassessmentscans.go | 365 +++++++++ .../managedinstanceencryptionprotectors.go | 285 +++++++ .../sql/managedinstancekeys.go | 362 +++++++++ .../sql/mgmt/2017-10-01-preview/sql/models.go | 746 ++++++++++++++++++ 6 files changed, 2307 insertions(+) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentrulebaselines.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessments.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentscans.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstanceencryptionprotectors.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancekeys.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentrulebaselines.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentrulebaselines.go new file mode 100644 index 000000000000..533e16ff231c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentrulebaselines.go @@ -0,0 +1,282 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient is the the Azure SQL Database management API provides a +// RESTful set of web services that interact with Azure SQL Database services to manage your databases. The API enables +// you to create, retrieve, update, and delete databases. +type ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient struct { + BaseClient +} + +// NewManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient creates an instance of the +// ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient client. +func NewManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient(subscriptionID string) ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient { + return NewManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientWithBaseURI creates an instance of the +// ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient client. +func NewManagedDatabaseVulnerabilityAssessmentRuleBaselinesClientWithBaseURI(baseURI string, subscriptionID string) ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient { + return ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a database's vulnerability assessment rule baseline. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database for which the vulnerability assessment rule baseline is defined. +// ruleID - the vulnerability assessment rule ID. +// baselineName - the name of the vulnerability assessment rule baseline (default implies a baseline on a +// database level rule and master for server level rule). +// parameters - the requested rule baseline resource. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, ruleID string, baselineName VulnerabilityAssessmentPolicyBaselineName, parameters DatabaseVulnerabilityAssessmentRuleBaseline) (result DatabaseVulnerabilityAssessmentRuleBaseline, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.DatabaseVulnerabilityAssessmentRuleBaselineProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.DatabaseVulnerabilityAssessmentRuleBaselineProperties.BaselineResults", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, managedInstanceName, databaseName, ruleID, baselineName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, ruleID string, baselineName VulnerabilityAssessmentPolicyBaselineName, parameters DatabaseVulnerabilityAssessmentRuleBaseline) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "baselineName": autorest.Encode("path", baselineName), + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "ruleId": autorest.Encode("path", ruleID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/rules/{ruleId}/baselines/{baselineName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) CreateOrUpdateResponder(resp *http.Response) (result DatabaseVulnerabilityAssessmentRuleBaseline, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete removes the database's vulnerability assessment rule baseline. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database for which the vulnerability assessment rule baseline is defined. +// ruleID - the vulnerability assessment rule ID. +// baselineName - the name of the vulnerability assessment rule baseline (default implies a baseline on a +// database level rule and master for server level rule). +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) Delete(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, ruleID string, baselineName VulnerabilityAssessmentPolicyBaselineName) (result autorest.Response, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, managedInstanceName, databaseName, ruleID, baselineName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) DeletePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, ruleID string, baselineName VulnerabilityAssessmentPolicyBaselineName) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "baselineName": autorest.Encode("path", baselineName), + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "ruleId": autorest.Encode("path", ruleID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/rules/{ruleId}/baselines/{baselineName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a database's vulnerability assessment rule baseline. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database for which the vulnerability assessment rule baseline is defined. +// ruleID - the vulnerability assessment rule ID. +// baselineName - the name of the vulnerability assessment rule baseline (default implies a baseline on a +// database level rule and master for server level rule). +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, ruleID string, baselineName VulnerabilityAssessmentPolicyBaselineName) (result DatabaseVulnerabilityAssessmentRuleBaseline, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, managedInstanceName, databaseName, ruleID, baselineName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, ruleID string, baselineName VulnerabilityAssessmentPolicyBaselineName) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "baselineName": autorest.Encode("path", baselineName), + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "ruleId": autorest.Encode("path", ruleID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/rules/{ruleId}/baselines/{baselineName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentRuleBaselinesClient) GetResponder(resp *http.Response) (result DatabaseVulnerabilityAssessmentRuleBaseline, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessments.go new file mode 100644 index 000000000000..c5416a094b9a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessments.go @@ -0,0 +1,267 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ManagedDatabaseVulnerabilityAssessmentsClient is the the Azure SQL Database management API provides a RESTful set of +// web services that interact with Azure SQL Database services to manage your databases. The API enables you to create, +// retrieve, update, and delete databases. +type ManagedDatabaseVulnerabilityAssessmentsClient struct { + BaseClient +} + +// NewManagedDatabaseVulnerabilityAssessmentsClient creates an instance of the +// ManagedDatabaseVulnerabilityAssessmentsClient client. +func NewManagedDatabaseVulnerabilityAssessmentsClient(subscriptionID string) ManagedDatabaseVulnerabilityAssessmentsClient { + return NewManagedDatabaseVulnerabilityAssessmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedDatabaseVulnerabilityAssessmentsClientWithBaseURI creates an instance of the +// ManagedDatabaseVulnerabilityAssessmentsClient client. +func NewManagedDatabaseVulnerabilityAssessmentsClientWithBaseURI(baseURI string, subscriptionID string) ManagedDatabaseVulnerabilityAssessmentsClient { + return ManagedDatabaseVulnerabilityAssessmentsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates the database's vulnerability assessment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database for which the vulnerability assessment is defined. +// parameters - the requested resource. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, parameters DatabaseVulnerabilityAssessment) (result DatabaseVulnerabilityAssessment, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.DatabaseVulnerabilityAssessmentProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.DatabaseVulnerabilityAssessmentProperties.StorageContainerPath", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("sql.ManagedDatabaseVulnerabilityAssessmentsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, managedInstanceName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, parameters DatabaseVulnerabilityAssessment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) CreateOrUpdateResponder(resp *http.Response) (result DatabaseVulnerabilityAssessment, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete removes the database's vulnerability assessment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database for which the vulnerability assessment is defined. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) Delete(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, managedInstanceName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets the database's vulnerability assessment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database for which the vulnerability assessment is defined. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (result DatabaseVulnerabilityAssessment, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, managedInstanceName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentsClient) GetResponder(resp *http.Response) (result DatabaseVulnerabilityAssessment, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentscans.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentscans.go new file mode 100644 index 000000000000..ed1bd774f0d8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/manageddatabasevulnerabilityassessmentscans.go @@ -0,0 +1,365 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ManagedDatabaseVulnerabilityAssessmentScansClient is the the Azure SQL Database management API provides a RESTful +// set of web services that interact with Azure SQL Database services to manage your databases. The API enables you to +// create, retrieve, update, and delete databases. +type ManagedDatabaseVulnerabilityAssessmentScansClient struct { + BaseClient +} + +// NewManagedDatabaseVulnerabilityAssessmentScansClient creates an instance of the +// ManagedDatabaseVulnerabilityAssessmentScansClient client. +func NewManagedDatabaseVulnerabilityAssessmentScansClient(subscriptionID string) ManagedDatabaseVulnerabilityAssessmentScansClient { + return NewManagedDatabaseVulnerabilityAssessmentScansClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedDatabaseVulnerabilityAssessmentScansClientWithBaseURI creates an instance of the +// ManagedDatabaseVulnerabilityAssessmentScansClient client. +func NewManagedDatabaseVulnerabilityAssessmentScansClientWithBaseURI(baseURI string, subscriptionID string) ManagedDatabaseVulnerabilityAssessmentScansClient { + return ManagedDatabaseVulnerabilityAssessmentScansClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Export convert an existing scan result to a human readable format. If already exists nothing happens +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the scanned database. +// scanID - the vulnerability assessment scan Id. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) Export(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, scanID string) (result DatabaseVulnerabilityAssessmentScansExport, err error) { + req, err := client.ExportPreparer(ctx, resourceGroupName, managedInstanceName, databaseName, scanID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "Export", nil, "Failure preparing request") + return + } + + resp, err := client.ExportSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "Export", resp, "Failure sending request") + return + } + + result, err = client.ExportResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "Export", resp, "Failure responding to request") + } + + return +} + +// ExportPreparer prepares the Export request. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ExportPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, scanID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scanId": autorest.Encode("path", scanID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/export", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExportSender sends the Export request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ExportSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ExportResponder handles the response to the Export request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ExportResponder(resp *http.Response) (result DatabaseVulnerabilityAssessmentScansExport, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets a vulnerability assessment scan record of a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database. +// scanID - the vulnerability assessment scan Id of the scan to retrieve. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, scanID string) (result VulnerabilityAssessmentScanRecord, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, managedInstanceName, databaseName, scanID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, scanID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scanId": autorest.Encode("path", scanID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) GetResponder(resp *http.Response) (result VulnerabilityAssessmentScanRecord, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// InitiateScan executes a Vulnerability Assessment database scan. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database. +// scanID - the vulnerability assessment scan Id of the scan to retrieve. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) InitiateScan(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, scanID string) (result ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture, err error) { + req, err := client.InitiateScanPreparer(ctx, resourceGroupName, managedInstanceName, databaseName, scanID) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "InitiateScan", nil, "Failure preparing request") + return + } + + result, err = client.InitiateScanSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "InitiateScan", result.Response(), "Failure sending request") + return + } + + return +} + +// InitiateScanPreparer prepares the InitiateScan request. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) InitiateScanPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, scanID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scanId": autorest.Encode("path", scanID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/initiateScan", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// InitiateScanSender sends the InitiateScan request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) InitiateScanSender(req *http.Request) (future ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// InitiateScanResponder handles the response to the InitiateScan request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) InitiateScanResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListByDatabase lists the vulnerability assessment scans of a database. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// databaseName - the name of the database. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ListByDatabase(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (result VulnerabilityAssessmentScanRecordListResultPage, err error) { + result.fn = client.listByDatabaseNextResults + req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, managedInstanceName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.vasrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", resp, "Failure sending request") + return + } + + result.vasrlr, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", resp, "Failure responding to request") + } + + return +} + +// ListByDatabasePreparer prepares the ListByDatabase request. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "databaseName": autorest.Encode("path", databaseName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vulnerabilityAssessmentName": autorest.Encode("path", "default"), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDatabaseSender sends the ListByDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always +// closes the http.Response Body. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ListByDatabaseResponder(resp *http.Response) (result VulnerabilityAssessmentScanRecordListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByDatabaseNextResults retrieves the next set of results, if any. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) listByDatabaseNextResults(lastResults VulnerabilityAssessmentScanRecordListResult) (result VulnerabilityAssessmentScanRecordListResult, err error) { + req, err := lastResults.vulnerabilityAssessmentScanRecordListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByDatabaseComplete enumerates all values, automatically crossing page boundaries as required. +func (client ManagedDatabaseVulnerabilityAssessmentScansClient) ListByDatabaseComplete(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string) (result VulnerabilityAssessmentScanRecordListResultIterator, err error) { + result.page, err = client.ListByDatabase(ctx, resourceGroupName, managedInstanceName, databaseName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstanceencryptionprotectors.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstanceencryptionprotectors.go new file mode 100644 index 000000000000..1658b1a78fa4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstanceencryptionprotectors.go @@ -0,0 +1,285 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ManagedInstanceEncryptionProtectorsClient is the the Azure SQL Database management API provides a RESTful set of web +// services that interact with Azure SQL Database services to manage your databases. The API enables you to create, +// retrieve, update, and delete databases. +type ManagedInstanceEncryptionProtectorsClient struct { + BaseClient +} + +// NewManagedInstanceEncryptionProtectorsClient creates an instance of the ManagedInstanceEncryptionProtectorsClient +// client. +func NewManagedInstanceEncryptionProtectorsClient(subscriptionID string) ManagedInstanceEncryptionProtectorsClient { + return NewManagedInstanceEncryptionProtectorsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedInstanceEncryptionProtectorsClientWithBaseURI creates an instance of the +// ManagedInstanceEncryptionProtectorsClient client. +func NewManagedInstanceEncryptionProtectorsClientWithBaseURI(baseURI string, subscriptionID string) ManagedInstanceEncryptionProtectorsClient { + return ManagedInstanceEncryptionProtectorsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate updates an existing encryption protector. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// parameters - the requested encryption protector resource state. +func (client ManagedInstanceEncryptionProtectorsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, managedInstanceName string, parameters ManagedInstanceEncryptionProtector) (result ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture, err error) { + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, managedInstanceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ManagedInstanceEncryptionProtectorsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, parameters ManagedInstanceEncryptionProtector) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "encryptionProtectorName": autorest.Encode("path", "current"), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/encryptionProtector/{encryptionProtectorName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceEncryptionProtectorsClient) CreateOrUpdateSender(req *http.Request) (future ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ManagedInstanceEncryptionProtectorsClient) CreateOrUpdateResponder(resp *http.Response) (result ManagedInstanceEncryptionProtector, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets a managed instance encryption protector. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +func (client ManagedInstanceEncryptionProtectorsClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string) (result ManagedInstanceEncryptionProtector, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, managedInstanceName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ManagedInstanceEncryptionProtectorsClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "encryptionProtectorName": autorest.Encode("path", "current"), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/encryptionProtector/{encryptionProtectorName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceEncryptionProtectorsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ManagedInstanceEncryptionProtectorsClient) GetResponder(resp *http.Response) (result ManagedInstanceEncryptionProtector, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByInstance gets a list of managed instance encryption protectors +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +func (client ManagedInstanceEncryptionProtectorsClient) ListByInstance(ctx context.Context, resourceGroupName string, managedInstanceName string) (result ManagedInstanceEncryptionProtectorListResultPage, err error) { + result.fn = client.listByInstanceNextResults + req, err := client.ListByInstancePreparer(ctx, resourceGroupName, managedInstanceName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "ListByInstance", nil, "Failure preparing request") + return + } + + resp, err := client.ListByInstanceSender(req) + if err != nil { + result.mieplr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "ListByInstance", resp, "Failure sending request") + return + } + + result.mieplr, err = client.ListByInstanceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "ListByInstance", resp, "Failure responding to request") + } + + return +} + +// ListByInstancePreparer prepares the ListByInstance request. +func (client ManagedInstanceEncryptionProtectorsClient) ListByInstancePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/encryptionProtector", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByInstanceSender sends the ListByInstance request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceEncryptionProtectorsClient) ListByInstanceSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByInstanceResponder handles the response to the ListByInstance request. The method always +// closes the http.Response Body. +func (client ManagedInstanceEncryptionProtectorsClient) ListByInstanceResponder(resp *http.Response) (result ManagedInstanceEncryptionProtectorListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByInstanceNextResults retrieves the next set of results, if any. +func (client ManagedInstanceEncryptionProtectorsClient) listByInstanceNextResults(lastResults ManagedInstanceEncryptionProtectorListResult) (result ManagedInstanceEncryptionProtectorListResult, err error) { + req, err := lastResults.managedInstanceEncryptionProtectorListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "listByInstanceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByInstanceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "listByInstanceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByInstanceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsClient", "listByInstanceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByInstanceComplete enumerates all values, automatically crossing page boundaries as required. +func (client ManagedInstanceEncryptionProtectorsClient) ListByInstanceComplete(ctx context.Context, resourceGroupName string, managedInstanceName string) (result ManagedInstanceEncryptionProtectorListResultIterator, err error) { + result.page, err = client.ListByInstance(ctx, resourceGroupName, managedInstanceName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancekeys.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancekeys.go new file mode 100644 index 000000000000..536e082ceebf --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/managedinstancekeys.go @@ -0,0 +1,362 @@ +package sql + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ManagedInstanceKeysClient is the the Azure SQL Database management API provides a RESTful set of web services that +// interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve, update, +// and delete databases. +type ManagedInstanceKeysClient struct { + BaseClient +} + +// NewManagedInstanceKeysClient creates an instance of the ManagedInstanceKeysClient client. +func NewManagedInstanceKeysClient(subscriptionID string) ManagedInstanceKeysClient { + return NewManagedInstanceKeysClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedInstanceKeysClientWithBaseURI creates an instance of the ManagedInstanceKeysClient client. +func NewManagedInstanceKeysClientWithBaseURI(baseURI string, subscriptionID string) ManagedInstanceKeysClient { + return ManagedInstanceKeysClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a managed instance key. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// keyName - the name of the managed instance key to be operated on (updated or created). +// parameters - the requested managed instance key resource state. +func (client ManagedInstanceKeysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, managedInstanceName string, keyName string, parameters ManagedInstanceKey) (result ManagedInstanceKeysCreateOrUpdateFuture, err error) { + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, managedInstanceName, keyName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ManagedInstanceKeysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, keyName string, parameters ManagedInstanceKey) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "keyName": autorest.Encode("path", keyName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/keys/{keyName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceKeysClient) CreateOrUpdateSender(req *http.Request) (future ManagedInstanceKeysCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ManagedInstanceKeysClient) CreateOrUpdateResponder(resp *http.Response) (result ManagedInstanceKey, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the managed instance key with the given name. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// keyName - the name of the managed instance key to be deleted. +func (client ManagedInstanceKeysClient) Delete(ctx context.Context, resourceGroupName string, managedInstanceName string, keyName string) (result ManagedInstanceKeysDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, managedInstanceName, keyName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ManagedInstanceKeysClient) DeletePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, keyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "keyName": autorest.Encode("path", keyName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/keys/{keyName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceKeysClient) DeleteSender(req *http.Request) (future ManagedInstanceKeysDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ManagedInstanceKeysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a managed instance key. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// keyName - the name of the managed instance key to be retrieved. +func (client ManagedInstanceKeysClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string, keyName string) (result ManagedInstanceKey, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, managedInstanceName, keyName) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ManagedInstanceKeysClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, keyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "keyName": autorest.Encode("path", keyName), + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/keys/{keyName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceKeysClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ManagedInstanceKeysClient) GetResponder(resp *http.Response) (result ManagedInstanceKey, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByInstance gets a list of managed instance keys. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// managedInstanceName - the name of the managed instance. +// filter - an OData filter expression that filters elements in the collection. +func (client ManagedInstanceKeysClient) ListByInstance(ctx context.Context, resourceGroupName string, managedInstanceName string, filter string) (result ManagedInstanceKeyListResultPage, err error) { + result.fn = client.listByInstanceNextResults + req, err := client.ListByInstancePreparer(ctx, resourceGroupName, managedInstanceName, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "ListByInstance", nil, "Failure preparing request") + return + } + + resp, err := client.ListByInstanceSender(req) + if err != nil { + result.miklr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "ListByInstance", resp, "Failure sending request") + return + } + + result.miklr, err = client.ListByInstanceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "ListByInstance", resp, "Failure responding to request") + } + + return +} + +// ListByInstancePreparer prepares the ListByInstance request. +func (client ManagedInstanceKeysClient) ListByInstancePreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "managedInstanceName": autorest.Encode("path", managedInstanceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-10-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/keys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByInstanceSender sends the ListByInstance request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedInstanceKeysClient) ListByInstanceSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByInstanceResponder handles the response to the ListByInstance request. The method always +// closes the http.Response Body. +func (client ManagedInstanceKeysClient) ListByInstanceResponder(resp *http.Response) (result ManagedInstanceKeyListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByInstanceNextResults retrieves the next set of results, if any. +func (client ManagedInstanceKeysClient) listByInstanceNextResults(lastResults ManagedInstanceKeyListResult) (result ManagedInstanceKeyListResult, err error) { + req, err := lastResults.managedInstanceKeyListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "listByInstanceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByInstanceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "listByInstanceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByInstanceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysClient", "listByInstanceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByInstanceComplete enumerates all values, automatically crossing page boundaries as required. +func (client ManagedInstanceKeysClient) ListByInstanceComplete(ctx context.Context, resourceGroupName string, managedInstanceName string, filter string) (result ManagedInstanceKeyListResultIterator, err error) { + result.page, err = client.ListByInstance(ctx, resourceGroupName, managedInstanceName, filter) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go index ca9abe427501..e16fad9bac3b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql/models.go @@ -358,6 +358,37 @@ func PossibleSampleNameValues() []SampleName { return []SampleName{AdventureWorksLT, WideWorldImportersFull, WideWorldImportersStd} } +// ServerKeyType enumerates the values for server key type. +type ServerKeyType string + +const ( + // AzureKeyVault ... + AzureKeyVault ServerKeyType = "AzureKeyVault" + // ServiceManaged ... + ServiceManaged ServerKeyType = "ServiceManaged" +) + +// PossibleServerKeyTypeValues returns an array of possible values for the ServerKeyType const type. +func PossibleServerKeyTypeValues() []ServerKeyType { + return []ServerKeyType{AzureKeyVault, ServiceManaged} +} + +// VulnerabilityAssessmentPolicyBaselineName enumerates the values for vulnerability assessment policy baseline +// name. +type VulnerabilityAssessmentPolicyBaselineName string + +const ( + // VulnerabilityAssessmentPolicyBaselineNameDefault ... + VulnerabilityAssessmentPolicyBaselineNameDefault VulnerabilityAssessmentPolicyBaselineName = "default" + // VulnerabilityAssessmentPolicyBaselineNameMaster ... + VulnerabilityAssessmentPolicyBaselineNameMaster VulnerabilityAssessmentPolicyBaselineName = "master" +) + +// PossibleVulnerabilityAssessmentPolicyBaselineNameValues returns an array of possible values for the VulnerabilityAssessmentPolicyBaselineName const type. +func PossibleVulnerabilityAssessmentPolicyBaselineNameValues() []VulnerabilityAssessmentPolicyBaselineName { + return []VulnerabilityAssessmentPolicyBaselineName{VulnerabilityAssessmentPolicyBaselineNameDefault, VulnerabilityAssessmentPolicyBaselineNameMaster} +} + // VulnerabilityAssessmentScanState enumerates the values for vulnerability assessment scan state. type VulnerabilityAssessmentScanState string @@ -1407,6 +1438,196 @@ func (du *DatabaseUpdate) UnmarshalJSON(body []byte) error { return nil } +// DatabaseVulnerabilityAssessment a database vulnerability assessment. +type DatabaseVulnerabilityAssessment struct { + autorest.Response `json:"-"` + // DatabaseVulnerabilityAssessmentProperties - Resource properties. + *DatabaseVulnerabilityAssessmentProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabaseVulnerabilityAssessment. +func (dva DatabaseVulnerabilityAssessment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dva.DatabaseVulnerabilityAssessmentProperties != nil { + objectMap["properties"] = dva.DatabaseVulnerabilityAssessmentProperties + } + if dva.ID != nil { + objectMap["id"] = dva.ID + } + if dva.Name != nil { + objectMap["name"] = dva.Name + } + if dva.Type != nil { + objectMap["type"] = dva.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseVulnerabilityAssessment struct. +func (dva *DatabaseVulnerabilityAssessment) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var databaseVulnerabilityAssessmentProperties DatabaseVulnerabilityAssessmentProperties + err = json.Unmarshal(*v, &databaseVulnerabilityAssessmentProperties) + if err != nil { + return err + } + dva.DatabaseVulnerabilityAssessmentProperties = &databaseVulnerabilityAssessmentProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + dva.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + dva.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + dva.Type = &typeVar + } + } + } + + return nil +} + +// DatabaseVulnerabilityAssessmentProperties properties of a database Vulnerability Assessment. +type DatabaseVulnerabilityAssessmentProperties struct { + // StorageContainerPath - A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/). + StorageContainerPath *string `json:"storageContainerPath,omitempty"` + // StorageContainerSasKey - A shared access signature (SAS Key) that has write access to the blob container specified in 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified, StorageContainerSasKey is required. + StorageContainerSasKey *string `json:"storageContainerSasKey,omitempty"` + // StorageAccountAccessKey - Specifies the identifier key of the vulnerability assessment storage account. If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required. + StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` + // RecurringScans - The recurring scans settings + RecurringScans *VulnerabilityAssessmentRecurringScansProperties `json:"recurringScans,omitempty"` +} + +// DatabaseVulnerabilityAssessmentRuleBaseline a database vulnerability assessment rule baseline. +type DatabaseVulnerabilityAssessmentRuleBaseline struct { + autorest.Response `json:"-"` + // DatabaseVulnerabilityAssessmentRuleBaselineProperties - Resource properties. + *DatabaseVulnerabilityAssessmentRuleBaselineProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabaseVulnerabilityAssessmentRuleBaseline. +func (dvarb DatabaseVulnerabilityAssessmentRuleBaseline) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dvarb.DatabaseVulnerabilityAssessmentRuleBaselineProperties != nil { + objectMap["properties"] = dvarb.DatabaseVulnerabilityAssessmentRuleBaselineProperties + } + if dvarb.ID != nil { + objectMap["id"] = dvarb.ID + } + if dvarb.Name != nil { + objectMap["name"] = dvarb.Name + } + if dvarb.Type != nil { + objectMap["type"] = dvarb.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseVulnerabilityAssessmentRuleBaseline struct. +func (dvarb *DatabaseVulnerabilityAssessmentRuleBaseline) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var databaseVulnerabilityAssessmentRuleBaselineProperties DatabaseVulnerabilityAssessmentRuleBaselineProperties + err = json.Unmarshal(*v, &databaseVulnerabilityAssessmentRuleBaselineProperties) + if err != nil { + return err + } + dvarb.DatabaseVulnerabilityAssessmentRuleBaselineProperties = &databaseVulnerabilityAssessmentRuleBaselineProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + dvarb.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + dvarb.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + dvarb.Type = &typeVar + } + } + } + + return nil +} + +// DatabaseVulnerabilityAssessmentRuleBaselineItem properties for an Azure SQL Database Vulnerability Assessment +// rule baseline's result. +type DatabaseVulnerabilityAssessmentRuleBaselineItem struct { + // Result - The rule baseline result + Result *[]string `json:"result,omitempty"` +} + +// DatabaseVulnerabilityAssessmentRuleBaselineProperties properties of a database Vulnerability Assessment rule +// baseline. +type DatabaseVulnerabilityAssessmentRuleBaselineProperties struct { + // BaselineResults - The rule baseline result + BaselineResults *[]DatabaseVulnerabilityAssessmentRuleBaselineItem `json:"baselineResults,omitempty"` +} + // DatabaseVulnerabilityAssessmentScanExportProperties properties of the export operation's result. type DatabaseVulnerabilityAssessmentScanExportProperties struct { // ExportedReportLocation - Location of the exported report (e.g. https://myStorage.blob.core.windows.net/VaScans/scans/serverName/databaseName/scan_scanId.xlsx). @@ -2588,6 +2809,29 @@ type LogSizeCapability struct { Unit LogSizeUnit `json:"unit,omitempty"` } +// ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture an abstraction for monitoring and retrieving the +// results of a long-running operation. +type ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture) Result(client ManagedDatabaseVulnerabilityAssessmentScansClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture") + return + } + ar.Response = future.Response() + return +} + // ManagedInstanceEditionCapability the managed server capability type ManagedInstanceEditionCapability struct { // Name - The managed server version name. @@ -2600,6 +2844,246 @@ type ManagedInstanceEditionCapability struct { Reason *string `json:"reason,omitempty"` } +// ManagedInstanceEncryptionProtector the managed instance encryption protector. +type ManagedInstanceEncryptionProtector struct { + autorest.Response `json:"-"` + // Kind - Kind of encryption protector. This is metadata used for the Azure portal experience. + Kind *string `json:"kind,omitempty"` + // ManagedInstanceEncryptionProtectorProperties - Resource properties. + *ManagedInstanceEncryptionProtectorProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ManagedInstanceEncryptionProtector. +func (miep ManagedInstanceEncryptionProtector) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if miep.Kind != nil { + objectMap["kind"] = miep.Kind + } + if miep.ManagedInstanceEncryptionProtectorProperties != nil { + objectMap["properties"] = miep.ManagedInstanceEncryptionProtectorProperties + } + if miep.ID != nil { + objectMap["id"] = miep.ID + } + if miep.Name != nil { + objectMap["name"] = miep.Name + } + if miep.Type != nil { + objectMap["type"] = miep.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ManagedInstanceEncryptionProtector struct. +func (miep *ManagedInstanceEncryptionProtector) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "kind": + if v != nil { + var kind string + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + miep.Kind = &kind + } + case "properties": + if v != nil { + var managedInstanceEncryptionProtectorProperties ManagedInstanceEncryptionProtectorProperties + err = json.Unmarshal(*v, &managedInstanceEncryptionProtectorProperties) + if err != nil { + return err + } + miep.ManagedInstanceEncryptionProtectorProperties = &managedInstanceEncryptionProtectorProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + miep.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + miep.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + miep.Type = &typeVar + } + } + } + + return nil +} + +// ManagedInstanceEncryptionProtectorListResult a list of managed instance encryption protectors. +type ManagedInstanceEncryptionProtectorListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]ManagedInstanceEncryptionProtector `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ManagedInstanceEncryptionProtectorListResultIterator provides access to a complete listing of +// ManagedInstanceEncryptionProtector values. +type ManagedInstanceEncryptionProtectorListResultIterator struct { + i int + page ManagedInstanceEncryptionProtectorListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ManagedInstanceEncryptionProtectorListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ManagedInstanceEncryptionProtectorListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ManagedInstanceEncryptionProtectorListResultIterator) Response() ManagedInstanceEncryptionProtectorListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ManagedInstanceEncryptionProtectorListResultIterator) Value() ManagedInstanceEncryptionProtector { + if !iter.page.NotDone() { + return ManagedInstanceEncryptionProtector{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (mieplr ManagedInstanceEncryptionProtectorListResult) IsEmpty() bool { + return mieplr.Value == nil || len(*mieplr.Value) == 0 +} + +// managedInstanceEncryptionProtectorListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (mieplr ManagedInstanceEncryptionProtectorListResult) managedInstanceEncryptionProtectorListResultPreparer() (*http.Request, error) { + if mieplr.NextLink == nil || len(to.String(mieplr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(mieplr.NextLink))) +} + +// ManagedInstanceEncryptionProtectorListResultPage contains a page of ManagedInstanceEncryptionProtector values. +type ManagedInstanceEncryptionProtectorListResultPage struct { + fn func(ManagedInstanceEncryptionProtectorListResult) (ManagedInstanceEncryptionProtectorListResult, error) + mieplr ManagedInstanceEncryptionProtectorListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ManagedInstanceEncryptionProtectorListResultPage) Next() error { + next, err := page.fn(page.mieplr) + if err != nil { + return err + } + page.mieplr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ManagedInstanceEncryptionProtectorListResultPage) NotDone() bool { + return !page.mieplr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ManagedInstanceEncryptionProtectorListResultPage) Response() ManagedInstanceEncryptionProtectorListResult { + return page.mieplr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ManagedInstanceEncryptionProtectorListResultPage) Values() []ManagedInstanceEncryptionProtector { + if page.mieplr.IsEmpty() { + return nil + } + return *page.mieplr.Value +} + +// ManagedInstanceEncryptionProtectorProperties properties for an encryption protector execution. +type ManagedInstanceEncryptionProtectorProperties struct { + // ServerKeyName - The name of the managed instance key. + ServerKeyName *string `json:"serverKeyName,omitempty"` + // ServerKeyType - The encryption protector type like 'ServiceManaged', 'AzureKeyVault'. Possible values include: 'ServiceManaged', 'AzureKeyVault' + ServerKeyType ServerKeyType `json:"serverKeyType,omitempty"` + // URI - The URI of the server key. + URI *string `json:"uri,omitempty"` + // Thumbprint - Thumbprint of the server key. + Thumbprint *string `json:"thumbprint,omitempty"` +} + +// ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results +// of a long-running operation. +type ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture) Result(client ManagedInstanceEncryptionProtectorsClient) (miep ManagedInstanceEncryptionProtector, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if miep.Response.Response, err = future.GetResult(sender); err == nil && miep.Response.Response.StatusCode != http.StatusNoContent { + miep, err = client.CreateOrUpdateResponder(miep.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture", "Result", miep.Response.Response, "Failure responding to request") + } + } + return +} + // ManagedInstanceFamilyCapability the managed server family capability. type ManagedInstanceFamilyCapability struct { // Name - Family name. @@ -2620,6 +3104,268 @@ type ManagedInstanceFamilyCapability struct { Reason *string `json:"reason,omitempty"` } +// ManagedInstanceKey a managed instance key. +type ManagedInstanceKey struct { + autorest.Response `json:"-"` + // Kind - Kind of encryption protector. This is metadata used for the Azure portal experience. + Kind *string `json:"kind,omitempty"` + // ManagedInstanceKeyProperties - Resource properties. + *ManagedInstanceKeyProperties `json:"properties,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ManagedInstanceKey. +func (mik ManagedInstanceKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mik.Kind != nil { + objectMap["kind"] = mik.Kind + } + if mik.ManagedInstanceKeyProperties != nil { + objectMap["properties"] = mik.ManagedInstanceKeyProperties + } + if mik.ID != nil { + objectMap["id"] = mik.ID + } + if mik.Name != nil { + objectMap["name"] = mik.Name + } + if mik.Type != nil { + objectMap["type"] = mik.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ManagedInstanceKey struct. +func (mik *ManagedInstanceKey) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "kind": + if v != nil { + var kind string + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + mik.Kind = &kind + } + case "properties": + if v != nil { + var managedInstanceKeyProperties ManagedInstanceKeyProperties + err = json.Unmarshal(*v, &managedInstanceKeyProperties) + if err != nil { + return err + } + mik.ManagedInstanceKeyProperties = &managedInstanceKeyProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + mik.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + mik.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + mik.Type = &typeVar + } + } + } + + return nil +} + +// ManagedInstanceKeyListResult a list of managed instance keys. +type ManagedInstanceKeyListResult struct { + autorest.Response `json:"-"` + // Value - Array of results. + Value *[]ManagedInstanceKey `json:"value,omitempty"` + // NextLink - Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ManagedInstanceKeyListResultIterator provides access to a complete listing of ManagedInstanceKey values. +type ManagedInstanceKeyListResultIterator struct { + i int + page ManagedInstanceKeyListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ManagedInstanceKeyListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ManagedInstanceKeyListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ManagedInstanceKeyListResultIterator) Response() ManagedInstanceKeyListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ManagedInstanceKeyListResultIterator) Value() ManagedInstanceKey { + if !iter.page.NotDone() { + return ManagedInstanceKey{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (miklr ManagedInstanceKeyListResult) IsEmpty() bool { + return miklr.Value == nil || len(*miklr.Value) == 0 +} + +// managedInstanceKeyListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (miklr ManagedInstanceKeyListResult) managedInstanceKeyListResultPreparer() (*http.Request, error) { + if miklr.NextLink == nil || len(to.String(miklr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(miklr.NextLink))) +} + +// ManagedInstanceKeyListResultPage contains a page of ManagedInstanceKey values. +type ManagedInstanceKeyListResultPage struct { + fn func(ManagedInstanceKeyListResult) (ManagedInstanceKeyListResult, error) + miklr ManagedInstanceKeyListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ManagedInstanceKeyListResultPage) Next() error { + next, err := page.fn(page.miklr) + if err != nil { + return err + } + page.miklr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ManagedInstanceKeyListResultPage) NotDone() bool { + return !page.miklr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ManagedInstanceKeyListResultPage) Response() ManagedInstanceKeyListResult { + return page.miklr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ManagedInstanceKeyListResultPage) Values() []ManagedInstanceKey { + if page.miklr.IsEmpty() { + return nil + } + return *page.miklr.Value +} + +// ManagedInstanceKeyProperties properties for a key execution. +type ManagedInstanceKeyProperties struct { + // ServerKeyType - The key type like 'ServiceManaged', 'AzureKeyVault'. Possible values include: 'ServiceManaged', 'AzureKeyVault' + ServerKeyType ServerKeyType `json:"serverKeyType,omitempty"` + // URI - The URI of the key. If the ServerKeyType is AzureKeyVault, then the URI is required. + URI *string `json:"uri,omitempty"` + // Thumbprint - Thumbprint of the key. + Thumbprint *string `json:"thumbprint,omitempty"` + // CreationDate - The key creation date. + CreationDate *date.Time `json:"creationDate,omitempty"` +} + +// ManagedInstanceKeysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ManagedInstanceKeysCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ManagedInstanceKeysCreateOrUpdateFuture) Result(client ManagedInstanceKeysClient) (mik ManagedInstanceKey, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceKeysCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if mik.Response.Response, err = future.GetResult(sender); err == nil && mik.Response.Response.StatusCode != http.StatusNoContent { + mik, err = client.CreateOrUpdateResponder(mik.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysCreateOrUpdateFuture", "Result", mik.Response.Response, "Failure responding to request") + } + } + return +} + +// ManagedInstanceKeysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ManagedInstanceKeysDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ManagedInstanceKeysDeleteFuture) Result(client ManagedInstanceKeysClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceKeysDeleteFuture") + return + } + ar.Response = future.Response() + return +} + // ManagedInstancePairInfo pairs of Managed Instances in the failover group. type ManagedInstancePairInfo struct { // PrimaryManagedInstanceID - Id of Primary Managed Instance in pair. From 3be70491f0c0dea38794e38743d284652b5c37a4 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 29 Oct 2018 19:29:47 -0700 Subject: [PATCH 14/38] [New Resource] Updated Tests added Documentation --- azurerm/resource_arm_sql2017_elasticpool.go | 4 +- .../resource_arm_sql2017_elasticpool_test.go | 14 +-- website/azurerm.erb | 4 + .../docs/r/sql2017_elasticpool.html.markdown | 96 +++++++++++++++++++ 4 files changed, 109 insertions(+), 9 deletions(-) create mode 100644 website/docs/r/sql2017_elasticpool.html.markdown diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index 877f00ae216f..85a476fb9439 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -208,11 +208,11 @@ func resourceArmSql2017ElasticPool() *schema.Resource { minCapacity, _ := diff.GetOk("per_database_settings.0.min_capacity") maxCapacity, _ := diff.GetOk("per_database_settings.0.max_capacity") - if maxCapacity.(float64) > capacity.(float64) { + if maxCapacity.(float64) > float64(capacity.(int)) { return fmt.Errorf("BusinessCritical pricing tier must have a capacity of 2, 4, 8, 16, 24, 32, 40, or 80 vCores") } - if maxCapacity.(float64) > capacity.(float64) { + if maxCapacity.(float64) > float64(capacity.(int)) { return fmt.Errorf("BusinessCritical and GeneralPurpose pricing tiers perDatabaseSettings maxCapacity must not be higher than the SKUs capacity value") } diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go index 21029174a7b2..7b89f2ca3599 100644 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -100,16 +100,16 @@ func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { Config: preConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100"), ), }, { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50.0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "1000.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "1000"), ), }, }, @@ -133,15 +133,15 @@ func TestAccAzureRMSqlElasticPool2017_resize_vCore(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.25"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "4.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "4"), ), }, { Config: postConfig, Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "8.0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "8"), ), }, }, diff --git a/website/azurerm.erb b/website/azurerm.erb index a2418b22da82..910e8660df9f 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -523,6 +523,10 @@ azurerm_sql_elasticpool + > + azurerm_sql2017_elasticpool + + > azurerm_sql_firewall_rule diff --git a/website/docs/r/sql2017_elasticpool.html.markdown b/website/docs/r/sql2017_elasticpool.html.markdown new file mode 100644 index 000000000000..cf08102ead24 --- /dev/null +++ b/website/docs/r/sql2017_elasticpool.html.markdown @@ -0,0 +1,96 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_sql2017_elasticpool" +sidebar_current: "docs-azurerm-resource-database-sql2017-elasticpool" +description: |- + Manages a SQL2017 Elastic Pool. +--- + +# azurerm_sql2017_elasticpool + +Allows you to manage an Azure SQL2017 Elastic Pool. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "test" { + name = "my-resource-group" + location = "westeurope" +} + +resource "azurerm_sql_server" "test" { + name = "my-sql-server" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_sql2017_elasticpool" "test" { + name = "test-epool" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "GP_Gen5" + capacity = 4 + tier = "GeneralPurpose" + family = "Gen5" + } + + per_database_settings { + min_capacity = 0.25 + max_capacity = 4 + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the elastic pool. This needs to be globally unique. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group in which to create the elastic pool. This must be the same as the resource group of the underlying SQL server. + +* `location` - (Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. + +* `server_name` - (Required) The name of the SQL Server on which to create the elastic pool. Changing this forces a new resource to be created. + +* `sku` - (Required) A `sku` block as defined below. + +* `per_database_settings` - (Required) A `per_database_settings` block as defined below. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +--- + +`sku` supports the following: + +* `name` - (Required) Specifies the SKU Name for this Elasticpool. The name of the SKU, will be either `vCore` based `tier` + `family` pattern (e.g. GP_Gen4, BC_Gen5) or the `DTU` based `BasicPool`, `StandardPool`, or `PremiumPool` pattern. + +* `capacity` - (Required) The scale up/out capacity, representing server's compute units. For more information see the documentation for your Elasticpool configuration: [vCore-based](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-vcore-resource-limits-elastic-pools) or [DTU-based](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-dtu-resource-limits-elastic-pools). + +* `tier` - (Required) The tier of the particular SKU. Possible values are `GeneralPurpose`, `BusinessCritical`, `Basic`, `Standard`, or `Premium`. For more information see the documentation for your Elasticpool configuration: [vCore-based](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-vcore-resource-limits-elastic-pools) or [DTU-based](https://docs.microsoft.com/en-us/azure/sql-database/sql-database-dtu-resource-limits-elastic-pools). + +* `family` - (Required) The `family` of hardware `Gen4` or `Gen5`. + +--- + +`per_database_settings` supports the following: + +* `min_capacity` - (Required) The minimum capacity all databases are guaranteed. + +* `max_capacity` - (Required) The maximum capacity any one database can consume. + +--- + +## Attributes Reference + +The following attributes are exported: + +* `id` - The SQL2017 Elastic Pool ID. + +* `creation_date` - The creation date of the SQL2017 Elastic Pool. From e50d331c53e33c7e516ce3502790775d70c8b9a7 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 30 Oct 2018 16:36:24 -0700 Subject: [PATCH 15/38] Fixed test issue --- .../resource_arm_sql2017_elasticpool_test.go | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go index 7b89f2ca3599..298a5a07fe1f 100644 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -101,7 +101,7 @@ func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "50"), ), }, { @@ -109,7 +109,7 @@ func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "1000"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100"), ), }, }, @@ -249,14 +249,14 @@ resource "azurerm_sql2017_elasticpool" "test" { server_name = "${azurerm_sql_server.test.name}" sku { - name = "BasicPool" - tier = "Basic" - capacity = 1000 + name = "StandardPool" + tier = "Standard" + capacity = 50 } per_database_settings { min_capacity = 0 - max_capacity = 100 + max_capacity = 50 } } `, rInt, location) @@ -322,14 +322,14 @@ resource "azurerm_sql2017_elasticpool" "test" { server_name = "${azurerm_sql_server.test.name}" sku { - name = "BasicPool" - tier = "Basic" - capacity = 1000 + name = "StandardPool" + tier = "Standard" + capacity = 100 } per_database_settings { min_capacity = 50 - max_capacity = 1000 + max_capacity = 100 } } `, rInt, location) From ea99f409506996d913b25be0f7e6faeab01fb57f Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 30 Oct 2018 18:43:06 -0700 Subject: [PATCH 16/38] Added validation to name and server_name --- azurerm/resource_arm_sql2017_elasticpool.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index 85a476fb9439..bf5dc5409fdb 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "math" + "regexp" "strings" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" @@ -27,6 +28,10 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile("^[-a-z0-9]{2,60}$"), + "SQL2017 ElasticPool name must be 2 - 60 characters long, contain only letters, numbers and hyphens.", + ), }, "location": locationSchema(), @@ -37,6 +42,10 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile("^[-a-z0-9]{3,50}$"), + "SQL server name must be 3 - 50 characters long, contain only letters, numbers and hyphens.", + ), }, "sku": { From bc5230c005f0ddb7f7bf75e8c978f005186f69dc Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 1 Nov 2018 15:58:11 -0700 Subject: [PATCH 17/38] Added azure.ValidateServiceName func and tests --- azurerm/helpers/azure/validate.go | 26 +++++++++ azurerm/helpers/azure/validate_test.go | 58 +++++++++++++++++++++ azurerm/resource_arm_sql2017_elasticpool.go | 24 ++++----- 3 files changed, 93 insertions(+), 15 deletions(-) diff --git a/azurerm/helpers/azure/validate.go b/azurerm/helpers/azure/validate.go index ff56279807d5..472fbdc75a55 100644 --- a/azurerm/helpers/azure/validate.go +++ b/azurerm/helpers/azure/validate.go @@ -2,6 +2,7 @@ package azure import ( "fmt" + "regexp" ) func ValidateResourceID(i interface{}, k string) (_ []string, errors []error) { @@ -32,3 +33,28 @@ func ValidateResourceIDOrEmpty(i interface{}, k string) (_ []string, errors []er return ValidateResourceID(i, k) } + +//true for a resource ID or an empty string +func ValidateServiceName(i interface{}, k string) (_ []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return + } + + //First, second, and last characters must be a letter or number with a total length between 3 to 50 lowercase characters. + r := regexp.MustCompile("^[a-z0-9]{2}[-a-z0-9]{0,47}[a-z0-9]{1}$") + if !r.MatchString(v) { + errors = append(errors, fmt.Errorf("%q must be 3 - 50 characters in length", k)) + errors = append(errors, fmt.Errorf("%q first, second, and last characters must be a lowercase letter or number", k)) + errors = append(errors, fmt.Errorf("%q can only contain lowercase letters, numbers and hyphens", k)) + } + + //No consecutive dashes. + r = regexp.MustCompile("(--)") + if r.MatchString(v) { + errors = append(errors, fmt.Errorf("%q must not contain any consecutive hyphens", k)) + } + + return +} diff --git a/azurerm/helpers/azure/validate_test.go b/azurerm/helpers/azure/validate_test.go index b8b17ab474f0..9c35fbd2d41c 100644 --- a/azurerm/helpers/azure/validate_test.go +++ b/azurerm/helpers/azure/validate_test.go @@ -90,3 +90,61 @@ func TestAzureResourceIDOrEmpty(t *testing.T) { }) } } + +func TestAzureValidateServiceName(t *testing.T) { + cases := []struct { + ServiceName string + Errors int + }{ + { + ServiceName: "as", + Errors: 3, + }, + { + ServiceName: "Asd", + Errors: 3, + }, + { + ServiceName: "asd", + Errors: 0, + }, + { + ServiceName: "-asd", + Errors: 3, + }, + { + ServiceName: "asd-", + Errors: 3, + }, + { + ServiceName: "asd-1", + Errors: 0, + }, + { + ServiceName: "asd--1", + Errors: 1, + }, + { + ServiceName: "asd--1-", + Errors: 4, + }, + { + ServiceName: "asdfghjklzasdfghjklzasdfghjklzasdfghjklzasdfghjklz", + Errors: 0, + }, + { + ServiceName: "asdfghjklzasdfghjklzasdfghjklzasdfghjklzasdfghjklz1", + Errors: 3, + }, + } + + for _, tc := range cases { + t.Run(tc.ID, func(t *testing.T) { + _, errors := ValidateServiceName(tc.ServiceName, "name") + + if len(errors) < tc.Errors { + t.Fatalf("Expected TestAzureValidateServiceName to have %d not %d errors for %q", tc.Errors, len(errors), tc.ServiceName) + } + }) + } +} diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_sql2017_elasticpool.go index bf5dc5409fdb..1b91e14225ff 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_sql2017_elasticpool.go @@ -4,12 +4,12 @@ import ( "fmt" "log" "math" - "regexp" "strings" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -25,13 +25,10 @@ func resourceArmSql2017ElasticPool() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^[-a-z0-9]{2,60}$"), - "SQL2017 ElasticPool name must be 2 - 60 characters long, contain only letters, numbers and hyphens.", - ), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateServiceName, }, "location": locationSchema(), @@ -39,13 +36,10 @@ func resourceArmSql2017ElasticPool() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), "server_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^[-a-z0-9]{3,50}$"), - "SQL server name must be 3 - 50 characters long, contain only letters, numbers and hyphens.", - ), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateServiceName, }, "sku": { From 59dbd93cf0cf7ebf5609f8e0a979b36584ae0c74 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 1 Nov 2018 16:06:02 -0700 Subject: [PATCH 18/38] Fixed validation test issue --- azurerm/helpers/azure/validate_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/helpers/azure/validate_test.go b/azurerm/helpers/azure/validate_test.go index 9c35fbd2d41c..ed14ed873078 100644 --- a/azurerm/helpers/azure/validate_test.go +++ b/azurerm/helpers/azure/validate_test.go @@ -139,7 +139,7 @@ func TestAzureValidateServiceName(t *testing.T) { } for _, tc := range cases { - t.Run(tc.ID, func(t *testing.T) { + t.Run(tc.ServiceName, func(t *testing.T) { _, errors := ValidateServiceName(tc.ServiceName, "name") if len(errors) < tc.Errors { From 13e8fd91903104f4495e3a9192637c8d064e2853 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 1 Nov 2018 16:43:21 -0700 Subject: [PATCH 19/38] Updated BasicPool to StandardPool --- azurerm/resource_arm_sql2017_elasticpool_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go index 298a5a07fe1f..74f94488d138 100644 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ b/azurerm/resource_arm_sql2017_elasticpool_test.go @@ -24,7 +24,7 @@ func TestAccAzureRMSqlElasticPool2017_basic_DTU(t *testing.T) { Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "sku.0.name", "BasicPool"), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "StandardPool"), ), }, { From 242830bf6dc3e9a1224b127077c4f17395224ba5 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Nov 2018 15:24:10 -0800 Subject: [PATCH 20/38] Updates per PR comments --- azurerm/config.go | 11 +- azurerm/provider.go | 2 +- ...l.go => resource_arm_mssql_elasticpool.go} | 56 +-- .../resource_arm_mssql_elasticpool_test.go | 342 ++++++++++++++++ .../resource_arm_sql2017_elasticpool_test.go | 373 ------------------ website/azurerm.erb | 4 +- ...rkdown => mssql_elasticpool.html.markdown} | 16 +- 7 files changed, 387 insertions(+), 417 deletions(-) rename azurerm/{resource_arm_sql2017_elasticpool.go => resource_arm_mssql_elasticpool.go} (82%) create mode 100644 azurerm/resource_arm_mssql_elasticpool_test.go delete mode 100644 azurerm/resource_arm_sql2017_elasticpool_test.go rename website/docs/r/{sql2017_elasticpool.html.markdown => mssql_elasticpool.html.markdown} (87%) diff --git a/azurerm/config.go b/azurerm/config.go index 3703fb00b6b6..9a1cb0e270d6 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -47,7 +47,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management" "github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/2017-08-01-preview/security" "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2015-05-01-preview/sql" - sql2017 "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" + MsSql "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-10-01-preview/sql" "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/backup" "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis" @@ -182,7 +182,8 @@ type ArmClient struct { sqlDatabasesClient sql.DatabasesClient sqlDatabaseThreatDetectionPoliciesClient sql.DatabaseThreatDetectionPoliciesClient sqlElasticPoolsClient sql.ElasticPoolsClient - sql2017ElasticPoolsClient sql2017.ElasticPoolsClient + // Client for the new 2017-10-01-preview SQL API which implements vCore, DTU, and Azure data standards + MsSqlElasticPoolsClient MsSql.ElasticPoolsClient sqlFirewallRulesClient sql.FirewallRulesClient sqlServersClient sql.ServersClient sqlServerAzureADAdministratorsClient sql.ServerAzureADAdministratorsClient @@ -792,9 +793,9 @@ func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth auto c.configureClient(&sqlEPClient.Client, auth) c.sqlElasticPoolsClient = sqlEPClient - sql2017EPClient := sql2017.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - c.configureClient(&sql2017EPClient.Client, auth) - c.sql2017ElasticPoolsClient = sql2017EPClient + MsSqlEPClient := MsSql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&MsSqlEPClient.Client, auth) + c.MsSqlElasticPoolsClient = MsSqlEPClient sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&sqlSrvClient.Client, auth) diff --git a/azurerm/provider.go b/azurerm/provider.go index df864c8da11b..407d135b1384 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -280,7 +280,7 @@ func Provider() terraform.ResourceProvider { "azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(), "azurerm_sql_database": resourceArmSqlDatabase(), "azurerm_sql_elasticpool": resourceArmSqlElasticPool(), - "azurerm_sql2017_elasticpool": resourceArmSql2017ElasticPool(), + "azurerm_mssql_elasticpool": resourceArmMsSqlElasticPool(), "azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), "azurerm_sql_active_directory_administrator": resourceArmSqlAdministrator(), "azurerm_sql_server": resourceArmSqlServer(), diff --git a/azurerm/resource_arm_sql2017_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go similarity index 82% rename from azurerm/resource_arm_sql2017_elasticpool.go rename to azurerm/resource_arm_mssql_elasticpool.go index 1b91e14225ff..022e41bcae9b 100644 --- a/azurerm/resource_arm_sql2017_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -13,12 +13,12 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func resourceArmSql2017ElasticPool() *schema.Resource { +func resourceArmMsSqlElasticPool() *schema.Resource { return &schema.Resource{ - Create: resourceArmSql2017ElasticPoolCreate, - Read: resourceArmSql2017ElasticPoolRead, - Update: resourceArmSql2017ElasticPoolCreate, - Delete: resourceArmSql2017ElasticPoolDelete, + Create: resourceArmMsSqlElasticPoolCreate, + Read: resourceArmMsSqlElasticPoolRead, + Update: resourceArmMsSqlElasticPoolCreate, + Delete: resourceArmMsSqlElasticPoolDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -242,18 +242,18 @@ func resourceArmSql2017ElasticPool() *schema.Resource { } } -func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).sql2017ElasticPoolsClient +func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).MsSqlElasticPoolsClient ctx := meta.(*ArmClient).StopContext - log.Printf("[INFO] preparing arguments for SQL2017 ElasticPool creation.") + log.Printf("[INFO] preparing arguments for MsSQL ElasticPool creation.") elasticPoolName := d.Get("name").(string) serverName := d.Get("server_name").(string) location := azureRMNormalizeLocation(d.Get("location").(string)) resGroup := d.Get("resource_group_name").(string) - sku := expandAzureRmSql2017ElasticPoolSku(d) - properties := expandAzureRmSql2017ElasticPoolProperties(d) + sku := expandAzureRmMsSqlElasticPoolSku(d) + properties := expandAzureRmMsSqlElasticPoolProperties(d) tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ @@ -279,19 +279,19 @@ func resourceArmSql2017ElasticPoolCreate(d *schema.ResourceData, meta interface{ return err } if read.ID == nil { - return fmt.Errorf("Cannot read SQL2017 ElasticPool %q (resource group %q) ID", elasticPoolName, resGroup) + return fmt.Errorf("Cannot read MsSQL ElasticPool %q (resource group %q) ID", elasticPoolName, resGroup) } d.SetId(*read.ID) - return resourceArmSql2017ElasticPoolRead(d, meta) + return resourceArmMsSqlElasticPoolRead(d, meta) } -func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).sql2017ElasticPoolsClient +func resourceArmMsSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).MsSqlElasticPoolsClient ctx := meta.(*ArmClient).StopContext - resGroup, serverName, name, err := parseArmSql2017ElasticPoolId(d.Id()) + resGroup, serverName, name, err := parseArmMsSqlElasticPoolId(d.Id()) if err != nil { return err } @@ -302,7 +302,7 @@ func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return fmt.Errorf("Error making Read request on Sql2017 Elastic Pool %s: %s", name, err) + return fmt.Errorf("Error making Read request on MsSql Elastic Pool %s: %s", name, err) } d.Set("name", resp.Name) @@ -314,15 +314,15 @@ func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) d.Set("server_name", serverName) - if err := d.Set("sku", flattenAzureRmSql2017ElasticPoolSku(resp.Sku)); err != nil { + if err := d.Set("sku", flattenAzureRmMsSqlElasticPoolSku(resp.Sku)); err != nil { return fmt.Errorf("Error flattening `sku`: %+v", err) } - if err := d.Set("elastic_pool_properties", flattenAzureRmSql2017ElasticPoolProperties(resp.ElasticPoolProperties)); err != nil { + if err := d.Set("elastic_pool_properties", flattenAzureRmMsSqlElasticPoolProperties(resp.ElasticPoolProperties)); err != nil { return fmt.Errorf("Error flattening `elastic_pool_properties`: %+v", err) } - if err := d.Set("per_database_settings", flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp.ElasticPoolProperties.PerDatabaseSettings)); err != nil { + if err := d.Set("per_database_settings", flattenAzureRmMsSqlElasticPoolPerDatabaseSettings(resp.ElasticPoolProperties.PerDatabaseSettings)); err != nil { return fmt.Errorf("Error flattening `per_database_settings`: %+v", err) } @@ -331,8 +331,8 @@ func resourceArmSql2017ElasticPoolRead(d *schema.ResourceData, meta interface{}) return nil } -func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).sql2017ElasticPoolsClient +func resourceArmMsSqlElasticPoolDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).MsSqlElasticPoolsClient ctx := meta.(*ArmClient).StopContext resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) @@ -345,16 +345,16 @@ func resourceArmSql2017ElasticPoolDelete(d *schema.ResourceData, meta interface{ return err } -func parseArmSql2017ElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { +func parseArmMsSqlElasticPoolId(sqlElasticPoolId string) (string, string, string, error) { id, err := parseAzureResourceID(sqlElasticPoolId) if err != nil { - return "", "", "", fmt.Errorf("[ERROR] Unable to parse SQL2017 ElasticPool ID %q: %+v", sqlElasticPoolId, err) + return "", "", "", fmt.Errorf("[ERROR] Unable to parse MsSQL ElasticPool ID %q: %+v", sqlElasticPoolId, err) } return id.ResourceGroup, id.Path["servers"], id.Path["elasticPools"], nil } -func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { +func expandAzureRmMsSqlElasticPoolProperties(d *schema.ResourceData) *sql.ElasticPoolProperties { perDatabaseSettings := d.Get("per_database_settings").([]interface{}) perDatabaseSetting := perDatabaseSettings[0].(map[string]interface{}) @@ -373,7 +373,7 @@ func expandAzureRmSql2017ElasticPoolProperties(d *schema.ResourceData) *sql.Elas return props } -func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { +func expandAzureRmMsSqlElasticPoolSku(d *schema.ResourceData) *sql.Sku { skus := d.Get("sku").([]interface{}) sku := skus[0].(map[string]interface{}) @@ -390,7 +390,7 @@ func expandAzureRmSql2017ElasticPoolSku(d *schema.ResourceData) *sql.Sku { } } -func flattenAzureRmSql2017ElasticPoolSku(resp *sql.Sku) []interface{} { +func flattenAzureRmMsSqlElasticPoolSku(resp *sql.Sku) []interface{} { values := map[string]interface{}{} if name := resp.Name; name != nil { @@ -410,7 +410,7 @@ func flattenAzureRmSql2017ElasticPoolSku(resp *sql.Sku) []interface{} { return []interface{}{values} } -func flattenAzureRmSql2017ElasticPoolProperties(resp *sql.ElasticPoolProperties) []interface{} { +func flattenAzureRmMsSqlElasticPoolProperties(resp *sql.ElasticPoolProperties) []interface{} { elasticPoolProperty := map[string]interface{}{} if maxSizeBytes := resp.MaxSizeBytes; maxSizeBytes != nil { @@ -432,7 +432,7 @@ func flattenAzureRmSql2017ElasticPoolProperties(resp *sql.ElasticPoolProperties) return []interface{}{elasticPoolProperty} } -func flattenAzureRmSql2017ElasticPoolPerDatabaseSettings(resp *sql.ElasticPoolPerDatabaseSettings) []interface{} { +func flattenAzureRmMsSqlElasticPoolPerDatabaseSettings(resp *sql.ElasticPoolPerDatabaseSettings) []interface{} { perDatabaseSettings := map[string]interface{}{} if minCapacity := resp.MinCapacity; minCapacity != nil { diff --git a/azurerm/resource_arm_mssql_elasticpool_test.go b/azurerm/resource_arm_mssql_elasticpool_test.go new file mode 100644 index 000000000000..8cec020fd57a --- /dev/null +++ b/azurerm/resource_arm_mssql_elasticpool_test.go @@ -0,0 +1,342 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMMsSqlElasticPool_basic_DTU(t *testing.T) { + resourceName := "azurerm_mssql_elasticpool.test" + ri := acctest.RandInt() + config := testAccAzureRMMsSqlElasticPool_basic_DTU(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMsSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "StandardPool"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "Standard"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "50"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMsSqlElasticPool_basic_vCore(t *testing.T) { + resourceName := "azurerm_mssql_elasticpool.test" + ri := acctest.RandInt() + config := testAccAzureRMMsSqlElasticPool_basic_vCore(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMsSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "GP_Gen5"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "GeneralPurpose"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "4"), + resource.TestCheckResourceAttr(resourceName, "sku.0.family", "Gen5"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.25"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "4"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMsSqlElasticPool_disappears(t *testing.T) { + resourceName := "azurerm_mssql_elasticpool.test" + ri := acctest.RandInt() + config := testAccAzureRMMsSqlElasticPool_basic_DTU(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMsSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "StandardPool"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "Standard"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "50"), + testCheckAzureRMMsSqlElasticPoolDisappears(resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAzureRMMsSqlElasticPool_resize_DTU(t *testing.T) { + resourceName := "azurerm_mssql_elasticpool.test" + ri := acctest.RandInt() + location := testLocation() + preConfig := testAccAzureRMMsSqlElasticPool_basic_DTU(ri, location) + postConfig := testAccAzureRMMsSqlElasticPool_resize_DTU(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMsSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "StandardPool"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "Standard"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "50"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "StandardPool"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "Standard"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "100"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100"), + ), + }, + }, + }) +} + +func TestAccAzureRMMsSqlElasticPool_resize_vCore(t *testing.T) { + resourceName := "azurerm_mssql_elasticpool.test" + ri := acctest.RandInt() + location := testLocation() + preConfig := testAccAzureRMMsSqlElasticPool_basic_vCore(ri, location) + postConfig := testAccAzureRMMsSqlElasticPool_resize_vCore(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMsSqlElasticPoolDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "GP_Gen5"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "GeneralPurpose"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "4"), + resource.TestCheckResourceAttr(resourceName, "sku.0.family", "Gen5"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.25"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "4"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlElasticPoolExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "sku.0.name", "GP_Gen5"), + resource.TestCheckResourceAttr(resourceName, "sku.0.tier", "GeneralPurpose"), + resource.TestCheckResourceAttr(resourceName, "sku.0.capacity", "8"), + resource.TestCheckResourceAttr(resourceName, "sku.0.family", "Gen5"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), + resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "8"), + ), + }, + }, + }) +} + +func testCheckAzureRMMsSqlElasticPoolExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serverName := rs.Primary.Attributes["server_name"] + poolName := rs.Primary.Attributes["name"] + + client := testAccProvider.Meta().(*ArmClient).MsSqlElasticPoolsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + resp, err := client.Get(ctx, resourceGroup, serverName, poolName) + if err != nil { + return fmt.Errorf("Bad: Get on MsSqlElasticPoolsClient: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: MsSql Elastic Pool %q on server: %q (resource group: %q) does not exist", name, serverName, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMMsSqlElasticPoolDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*ArmClient).MsSqlElasticPoolsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_mssql_elasticpool" { + continue + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serverName := rs.Primary.Attributes["server_name"] + poolName := rs.Primary.Attributes["name"] + + resp, err := client.Get(ctx, resourceGroup, serverName, poolName) + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("MsSql Elastic Pool still exists:\n%#v", resp.ElasticPoolProperties) + } + } + + return nil +} + +func testCheckAzureRMMsSqlElasticPoolDisappears(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + serverName := rs.Primary.Attributes["server_name"] + poolName := rs.Primary.Attributes["name"] + + client := testAccProvider.Meta().(*ArmClient).MsSqlElasticPoolsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + if _, err := client.Delete(ctx, resourceGroup, serverName, poolName); err != nil { + return fmt.Errorf("Bad: Delete on MsSqlElasticPoolsClient: %+v", err) + } + + return nil + } +} + +func testAccAzureRMMsSqlElasticPool_basic_DTU(rInt int, location string) string { + return testAccAzureRMMsSqlElasticPool_DTU_Template(rInt, location, "StandardPool", "Standard", 50, 0, 50) +} + +func testAccAzureRMMsSqlElasticPool_resize_DTU(rInt int, location string) string { + return testAccAzureRMMsSqlElasticPool_DTU_Template(rInt, location, "StandardPool", "Standard", 100, 50, 100) +} + +func testAccAzureRMMsSqlElasticPool_basic_vCore(rInt int, location string) string { + return testAccAzureRMMsSqlElasticPool_vCore_Template(rInt, location, "GP_Gen5", "GeneralPurpose", 4, "Gen5", 0.25, 4) +} + +func testAccAzureRMMsSqlElasticPool_resize_vCore(rInt int, location string) string { + return testAccAzureRMMsSqlElasticPool_vCore_Template(rInt, location, "GP_Gen5", "GeneralPurpose", 8, "Gen5", 0, 8) +} + +func testAccAzureRMMsSqlElasticPool_vCore_Template(rInt int, location string, skuName string, skuTier string, skuCapacity int, skuFamily string, databaseSettingsMin float64, databaseSettingsMax float64) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%s" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_mssql_elasticpool" "test" { + name = "acctest-pool-vcore-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "%[3]s" + tier = "%[4]s" + capacity = %[5]d + family = "%[6]s" + } + + per_database_settings { + min_capacity = %.2[7]f + max_capacity = %.2[8]f + } +} +`, rInt, location, skuName, skuTier, skuCapacity, skuFamily, databaseSettingsMin, databaseSettingsMax) +} + +func testAccAzureRMMsSqlElasticPool_DTU_Template(rInt int, location string, skuName string, skuTier string, skuCapacity int, databaseSettingsMin int, databaseSettingsMax int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%s" +} + +resource "azurerm_sql_server" "test" { + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" + administrator_login_password = "4-v3ry-53cr37-p455w0rd" +} + +resource "azurerm_mssql_elasticpool" "test" { + name = "acctest-pool-dtu-%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + server_name = "${azurerm_sql_server.test.name}" + + sku { + name = "%[3]s" + tier = "%[4]s" + capacity = %[5]d + } + + per_database_settings { + min_capacity = %[6]d + max_capacity = %[7]d + } +} +`, rInt, location, skuName, skuTier, skuCapacity, databaseSettingsMin, databaseSettingsMax) +} diff --git a/azurerm/resource_arm_sql2017_elasticpool_test.go b/azurerm/resource_arm_sql2017_elasticpool_test.go deleted file mode 100644 index 74f94488d138..000000000000 --- a/azurerm/resource_arm_sql2017_elasticpool_test.go +++ /dev/null @@ -1,373 +0,0 @@ -package azurerm - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform/helper/acctest" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMSqlElasticPool2017_basic_DTU(t *testing.T) { - resourceName := "azurerm_sql2017_elasticpool.test" - ri := acctest.RandInt() - config := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, testLocation()) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "sku.0.name", "StandardPool"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccAzureRMSqlElasticPool2017_basic_vCore(t *testing.T) { - resourceName := "azurerm_sql2017_elasticpool.test" - ri := acctest.RandInt() - config := testAccAzureRMSqlElasticPool2017_basic_vCore(ri, testLocation()) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "sku.0.name", "GP_Gen5"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccAzureRMSqlElasticPool2017_disappears(t *testing.T) { - resourceName := "azurerm_sql2017_elasticpool.test" - ri := acctest.RandInt() - config := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, testLocation()) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - testCheckAzureRMSqlElasticPool2017Disappears(resourceName), - ), - ExpectNonEmptyPlan: true, - }, - }, - }) -} - -func TestAccAzureRMSqlElasticPool2017_resize_DTU(t *testing.T) { - resourceName := "azurerm_sql2017_elasticpool.test" - ri := acctest.RandInt() - location := testLocation() - preConfig := testAccAzureRMSqlElasticPool2017_basic_DTU(ri, location) - postConfig := testAccAzureRMSqlElasticPool2017_resize_DTU(ri, location) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, - Steps: []resource.TestStep{ - { - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "50"), - ), - }, - { - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "50"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "100"), - ), - }, - }, - }) -} - -func TestAccAzureRMSqlElasticPool2017_resize_vCore(t *testing.T) { - resourceName := "azurerm_sql2017_elasticpool.test" - ri := acctest.RandInt() - location := testLocation() - preConfig := testAccAzureRMSqlElasticPool2017_basic_vCore(ri, location) - postConfig := testAccAzureRMSqlElasticPool2017_resize_vCore(ri, location) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSqlElasticPool2017Destroy, - Steps: []resource.TestStep{ - { - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0.25"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "4"), - ), - }, - { - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSqlElasticPool2017Exists(resourceName), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.min_capacity", "0"), - resource.TestCheckResourceAttr(resourceName, "per_database_settings.0.max_capacity", "8"), - ), - }, - }, - }) -} - -func testCheckAzureRMSqlElasticPool2017Exists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - serverName := rs.Primary.Attributes["server_name"] - poolName := rs.Primary.Attributes["name"] - - client := testAccProvider.Meta().(*ArmClient).sql2017ElasticPoolsClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext - - resp, err := client.Get(ctx, resourceGroup, serverName, poolName) - if err != nil { - return fmt.Errorf("Bad: Get on sql2017ElasticPoolsClient: %+v", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: SQL2017 Elastic Pool %q on server: %q (resource group: %q) does not exist", name, serverName, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMSqlElasticPool2017Destroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).sql2017ElasticPoolsClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_sql2017_elasticpool" { - continue - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - serverName := rs.Primary.Attributes["server_name"] - poolName := rs.Primary.Attributes["name"] - - resp, err := client.Get(ctx, resourceGroup, serverName, poolName) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("SQL2017 Elastic Pool still exists:\n%#v", resp.ElasticPoolProperties) - } - } - - return nil -} - -func testCheckAzureRMSqlElasticPool2017Disappears(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - // Ensure we have enough information in state to look up in API - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - resourceGroup := rs.Primary.Attributes["resource_group_name"] - serverName := rs.Primary.Attributes["server_name"] - poolName := rs.Primary.Attributes["name"] - - client := testAccProvider.Meta().(*ArmClient).sql2017ElasticPoolsClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext - - _, err := client.Delete(ctx, resourceGroup, serverName, poolName) - if err != nil { - return fmt.Errorf("Bad: Delete on sql2017ElasticPoolsClient: %+v", err) - } - - return nil - } -} - -func testAccAzureRMSqlElasticPool2017_basic_DTU(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctest-%[1]d" - location = "%s" -} - -resource "azurerm_sql_server" "test" { - name = "acctest%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "4dm1n157r470r" - administrator_login_password = "4-v3ry-53cr37-p455w0rd" -} - -resource "azurerm_sql2017_elasticpool" "test" { - name = "acctest-pool-dtu-%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - server_name = "${azurerm_sql_server.test.name}" - - sku { - name = "StandardPool" - tier = "Standard" - capacity = 50 - } - - per_database_settings { - min_capacity = 0 - max_capacity = 50 - } -} -`, rInt, location) -} - -func testAccAzureRMSqlElasticPool2017_basic_vCore(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctest-%[1]d" - location = "%s" -} - -resource "azurerm_sql_server" "test" { - name = "acctest%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "4dm1n157r470r" - administrator_login_password = "4-v3ry-53cr37-p455w0rd" -} - -resource "azurerm_sql2017_elasticpool" "test" { - name = "acctest-pool-vcore-%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - server_name = "${azurerm_sql_server.test.name}" - - sku { - name = "GP_Gen5" - tier = "GeneralPurpose" - capacity = 4 - family = "Gen5" - } - - per_database_settings { - min_capacity = 0.25 - max_capacity = 4 - } -} -`, rInt, location) -} - -func testAccAzureRMSqlElasticPool2017_resize_DTU(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctest-%[1]d" - location = "%s" -} - -resource "azurerm_sql_server" "test" { - name = "acctest%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "4dm1n157r470r" - administrator_login_password = "4-v3ry-53cr37-p455w0rd" -} - -resource "azurerm_sql2017_elasticpool" "test" { - name = "acctest-pool-dtu-%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - server_name = "${azurerm_sql_server.test.name}" - - sku { - name = "StandardPool" - tier = "Standard" - capacity = 100 - } - - per_database_settings { - min_capacity = 50 - max_capacity = 100 - } -} -`, rInt, location) -} - -func testAccAzureRMSqlElasticPool2017_resize_vCore(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctest-%[1]d" - location = "%s" -} - -resource "azurerm_sql_server" "test" { - name = "acctest%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "4dm1n157r470r" - administrator_login_password = "4-v3ry-53cr37-p455w0rd" -} - -resource "azurerm_sql2017_elasticpool" "test" { - name = "acctest-pool-vcore-%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - server_name = "${azurerm_sql_server.test.name}" - - sku { - name = "GP_Gen5" - tier = "GeneralPurpose" - capacity = 8 - family = "Gen5" - } - - per_database_settings { - min_capacity = 0 - max_capacity = 8 - } -} -`, rInt, location) -} diff --git a/website/azurerm.erb b/website/azurerm.erb index 910e8660df9f..38391d2043a7 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -523,8 +523,8 @@ azurerm_sql_elasticpool - > - azurerm_sql2017_elasticpool + > + azurerm_mssql_elasticpool > diff --git a/website/docs/r/sql2017_elasticpool.html.markdown b/website/docs/r/mssql_elasticpool.html.markdown similarity index 87% rename from website/docs/r/sql2017_elasticpool.html.markdown rename to website/docs/r/mssql_elasticpool.html.markdown index cf08102ead24..26a8f2830f65 100644 --- a/website/docs/r/sql2017_elasticpool.html.markdown +++ b/website/docs/r/mssql_elasticpool.html.markdown @@ -1,14 +1,14 @@ --- layout: "azurerm" -page_title: "Azure Resource Manager: azurerm_sql2017_elasticpool" -sidebar_current: "docs-azurerm-resource-database-sql2017-elasticpool" +page_title: "Azure Resource Manager: azurerm_mssql_elasticpool" +sidebar_current: "docs-azurerm-resource-database-mssql-elasticpool" description: |- - Manages a SQL2017 Elastic Pool. + Manages a SQL Elastic Pool. --- -# azurerm_sql2017_elasticpool +# azurerm_mssql_elasticpool -Allows you to manage an Azure SQL2017 Elastic Pool. +Allows you to manage an Azure SQL Elastic Pool via the `2017-10-01-preview` API which allows for `vCore` and `DTU` based configurations. ## Example Usage @@ -27,7 +27,7 @@ resource "azurerm_sql_server" "test" { administrator_login_password = "4-v3ry-53cr37-p455w0rd" } -resource "azurerm_sql2017_elasticpool" "test" { +resource "azurerm_mssql_elasticpool" "test" { name = "test-epool" resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" @@ -91,6 +91,6 @@ The following arguments are supported: The following attributes are exported: -* `id` - The SQL2017 Elastic Pool ID. +* `id` - The MsSQL Elastic Pool ID. -* `creation_date` - The creation date of the SQL2017 Elastic Pool. +* `creation_date` - The creation date of the MsSQL Elastic Pool. From 41e87dc803d50fc6dbf45766d7a63c06857632af Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Nov 2018 15:58:12 -0800 Subject: [PATCH 21/38] Corrected lint errors --- azurerm/helpers/azure/validate.go | 4 ++-- azurerm/resource_arm_mssql_elasticpool.go | 3 --- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/azurerm/helpers/azure/validate.go b/azurerm/helpers/azure/validate.go index 472fbdc75a55..284a2be5ce86 100644 --- a/azurerm/helpers/azure/validate.go +++ b/azurerm/helpers/azure/validate.go @@ -39,7 +39,7 @@ func ValidateServiceName(i interface{}, k string) (_ []string, errors []error) { v, ok := i.(string) if !ok { errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) - return + return _, errors } //First, second, and last characters must be a letter or number with a total length between 3 to 50 lowercase characters. @@ -56,5 +56,5 @@ func ValidateServiceName(i interface{}, k string) (_ []string, errors []error) { errors = append(errors, fmt.Errorf("%q must not contain any consecutive hyphens", k)) } - return + return _, errors } diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index 022e41bcae9b..eced97e5f112 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -207,9 +207,6 @@ func resourceArmMsSqlElasticPool() *schema.Resource { // Addutional checks based of SKU type... if strings.HasPrefix(strings.ToLower(name.(string)), "gp_") || strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { // vCore based - capacity, _ := diff.GetOk("sku.0.capacity") - minCapacity, _ := diff.GetOk("per_database_settings.0.min_capacity") - maxCapacity, _ := diff.GetOk("per_database_settings.0.max_capacity") if maxCapacity.(float64) > float64(capacity.(int)) { return fmt.Errorf("BusinessCritical pricing tier must have a capacity of 2, 4, 8, 16, 24, 32, 40, or 80 vCores") From 078e91bde2d08d91948ccb420798f3b589278346 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Nov 2018 16:02:57 -0800 Subject: [PATCH 22/38] Fixed validation function --- azurerm/helpers/azure/validate.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azurerm/helpers/azure/validate.go b/azurerm/helpers/azure/validate.go index 284a2be5ce86..85ea875a11d1 100644 --- a/azurerm/helpers/azure/validate.go +++ b/azurerm/helpers/azure/validate.go @@ -39,7 +39,7 @@ func ValidateServiceName(i interface{}, k string) (_ []string, errors []error) { v, ok := i.(string) if !ok { errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) - return _, errors + return nil, errors } //First, second, and last characters must be a letter or number with a total length between 3 to 50 lowercase characters. @@ -56,5 +56,5 @@ func ValidateServiceName(i interface{}, k string) (_ []string, errors []error) { errors = append(errors, fmt.Errorf("%q must not contain any consecutive hyphens", k)) } - return _, errors + return nil, errors } From 0212fac392e3759ca2a977a9c5039f8d0b319b1f Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Nov 2018 16:31:56 -0800 Subject: [PATCH 23/38] Corrected fmt errors --- azurerm/config.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index 9a1cb0e270d6..799d32e70cd4 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -183,11 +183,11 @@ type ArmClient struct { sqlDatabaseThreatDetectionPoliciesClient sql.DatabaseThreatDetectionPoliciesClient sqlElasticPoolsClient sql.ElasticPoolsClient // Client for the new 2017-10-01-preview SQL API which implements vCore, DTU, and Azure data standards - MsSqlElasticPoolsClient MsSql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - sqlServerAzureADAdministratorsClient sql.ServerAzureADAdministratorsClient - sqlVirtualNetworkRulesClient sql.VirtualNetworkRulesClient + MsSqlElasticPoolsClient MsSql.ElasticPoolsClient + sqlFirewallRulesClient sql.FirewallRulesClient + sqlServersClient sql.ServersClient + sqlServerAzureADAdministratorsClient sql.ServerAzureADAdministratorsClient + sqlVirtualNetworkRulesClient sql.VirtualNetworkRulesClient // Data Lake Store dataLakeStoreAccountClient storeAccount.AccountsClient From d3405b6e8b2358994e13af6058461cbd7d634e5d Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Nov 2018 17:32:47 -0800 Subject: [PATCH 24/38] Updated CustomizeDiff --- azurerm/resource_arm_mssql_elasticpool.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index eced97e5f112..c9ebfd621bff 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -177,7 +177,6 @@ func resourceArmMsSqlElasticPool() *schema.Resource { default: return fmt.Errorf("GeneralPurpose pricing tier must have a capacity of 1, 2, 4, 8, 16, or 24 vCores") } - } if strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { @@ -207,11 +206,6 @@ func resourceArmMsSqlElasticPool() *schema.Resource { // Addutional checks based of SKU type... if strings.HasPrefix(strings.ToLower(name.(string)), "gp_") || strings.HasPrefix(strings.ToLower(name.(string)), "bc_") { // vCore based - - if maxCapacity.(float64) > float64(capacity.(int)) { - return fmt.Errorf("BusinessCritical pricing tier must have a capacity of 2, 4, 8, 16, 24, 32, 40, or 80 vCores") - } - if maxCapacity.(float64) > float64(capacity.(int)) { return fmt.Errorf("BusinessCritical and GeneralPurpose pricing tiers perDatabaseSettings maxCapacity must not be higher than the SKUs capacity value") } From 86961486b67fd529a5c789a2f50e49035b6d1b48 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Nov 2018 18:40:14 -0800 Subject: [PATCH 25/38] Upgraded to 1.11.2 ran make fmt --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index c9ebfd621bff..a25d2ea9eef2 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -248,7 +248,7 @@ func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ - Sku: sku, + Sku: sku, ElasticPoolProperties: properties, Location: &location, Tags: expandTags(tags), From 23642a6ae4a1641e7a888acec5ae6b228cd87282 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 13 Nov 2018 12:39:32 -0800 Subject: [PATCH 26/38] Update azurerm/resource_arm_mssql_elasticpool.go Co-Authored-By: jeffreyCline --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index a25d2ea9eef2..dc725422bd61 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -60,7 +60,7 @@ func resourceArmMsSqlElasticPool() *schema.Resource { "BC_Gen4", "BC_Gen5", }, true), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "capacity": { From ee2783b182ecea96ab7f272a8195bf09300f59f2 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 13 Nov 2018 12:39:58 -0800 Subject: [PATCH 27/38] Update azurerm/resource_arm_mssql_elasticpool.go Co-Authored-By: jeffreyCline --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index dc725422bd61..27d0a3230ebd 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -78,7 +78,7 @@ func resourceArmMsSqlElasticPool() *schema.Resource { "GeneralPurpose", "BusinessCritical", }, true), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "family": { From d255c7bc6ce713cfa668dd4f8351ded3be99ff48 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 13 Nov 2018 12:40:30 -0800 Subject: [PATCH 28/38] Update azurerm/resource_arm_mssql_elasticpool.go Co-Authored-By: jeffreyCline --- azurerm/resource_arm_mssql_elasticpool.go | 1 - 1 file changed, 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index 27d0a3230ebd..feefc0870fbd 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -332,7 +332,6 @@ func resourceArmMsSqlElasticPoolDelete(d *schema.ResourceData, meta interface{}) } _, err = client.Delete(ctx, resGroup, serverName, name) - return err } From f27fbfe401893f6837bbb05149b012874f12a1e2 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Nov 2018 12:41:46 -0800 Subject: [PATCH 29/38] update casing of client --- azurerm/config.go | 4 ++-- azurerm/resource_arm_mssql_elasticpool.go | 8 ++++---- azurerm/resource_arm_mssql_elasticpool_test.go | 10 +++++----- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index 799d32e70cd4..3b3634da5e45 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -183,7 +183,7 @@ type ArmClient struct { sqlDatabaseThreatDetectionPoliciesClient sql.DatabaseThreatDetectionPoliciesClient sqlElasticPoolsClient sql.ElasticPoolsClient // Client for the new 2017-10-01-preview SQL API which implements vCore, DTU, and Azure data standards - MsSqlElasticPoolsClient MsSql.ElasticPoolsClient + msSqlElasticPoolsClient MsSql.ElasticPoolsClient sqlFirewallRulesClient sql.FirewallRulesClient sqlServersClient sql.ServersClient sqlServerAzureADAdministratorsClient sql.ServerAzureADAdministratorsClient @@ -795,7 +795,7 @@ func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth auto MsSqlEPClient := MsSql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&MsSqlEPClient.Client, auth) - c.MsSqlElasticPoolsClient = MsSqlEPClient + c.msSqlElasticPoolsClient = MsSqlEPClient sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&sqlSrvClient.Client, auth) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index a25d2ea9eef2..1ed0b1cba75c 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -234,7 +234,7 @@ func resourceArmMsSqlElasticPool() *schema.Resource { } func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).MsSqlElasticPoolsClient + client := meta.(*ArmClient).msSqlElasticPoolsClient ctx := meta.(*ArmClient).StopContext log.Printf("[INFO] preparing arguments for MsSQL ElasticPool creation.") @@ -248,7 +248,7 @@ func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ - Sku: sku, + Sku: sku, ElasticPoolProperties: properties, Location: &location, Tags: expandTags(tags), @@ -279,7 +279,7 @@ func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) } func resourceArmMsSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).MsSqlElasticPoolsClient + client := meta.(*ArmClient).msSqlElasticPoolsClient ctx := meta.(*ArmClient).StopContext resGroup, serverName, name, err := parseArmMsSqlElasticPoolId(d.Id()) @@ -323,7 +323,7 @@ func resourceArmMsSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) e } func resourceArmMsSqlElasticPoolDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).MsSqlElasticPoolsClient + client := meta.(*ArmClient).msSqlElasticPoolsClient ctx := meta.(*ArmClient).StopContext resGroup, serverName, name, err := parseArmSqlElasticPoolId(d.Id()) diff --git a/azurerm/resource_arm_mssql_elasticpool_test.go b/azurerm/resource_arm_mssql_elasticpool_test.go index 8cec020fd57a..e61fca478918 100644 --- a/azurerm/resource_arm_mssql_elasticpool_test.go +++ b/azurerm/resource_arm_mssql_elasticpool_test.go @@ -187,12 +187,12 @@ func testCheckAzureRMMsSqlElasticPoolExists(name string) resource.TestCheckFunc serverName := rs.Primary.Attributes["server_name"] poolName := rs.Primary.Attributes["name"] - client := testAccProvider.Meta().(*ArmClient).MsSqlElasticPoolsClient + client := testAccProvider.Meta().(*ArmClient).msSqlElasticPoolsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext resp, err := client.Get(ctx, resourceGroup, serverName, poolName) if err != nil { - return fmt.Errorf("Bad: Get on MsSqlElasticPoolsClient: %+v", err) + return fmt.Errorf("Bad: Get on msSqlElasticPoolsClient: %+v", err) } if resp.StatusCode == http.StatusNotFound { @@ -204,7 +204,7 @@ func testCheckAzureRMMsSqlElasticPoolExists(name string) resource.TestCheckFunc } func testCheckAzureRMMsSqlElasticPoolDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).MsSqlElasticPoolsClient + client := testAccProvider.Meta().(*ArmClient).msSqlElasticPoolsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext for _, rs := range s.RootModule().Resources { @@ -241,11 +241,11 @@ func testCheckAzureRMMsSqlElasticPoolDisappears(name string) resource.TestCheckF serverName := rs.Primary.Attributes["server_name"] poolName := rs.Primary.Attributes["name"] - client := testAccProvider.Meta().(*ArmClient).MsSqlElasticPoolsClient + client := testAccProvider.Meta().(*ArmClient).msSqlElasticPoolsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext if _, err := client.Delete(ctx, resourceGroup, serverName, poolName); err != nil { - return fmt.Errorf("Bad: Delete on MsSqlElasticPoolsClient: %+v", err) + return fmt.Errorf("Bad: Delete on msSqlElasticPoolsClient: %+v", err) } return nil From 95a741ee3a8de9fb699d9f5bc58218fb0abc0a8f Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Nov 2018 13:13:56 -0800 Subject: [PATCH 30/38] Addressing PR comments --- azurerm/helpers/azure/validate.go | 2 +- azurerm/helpers/azure/validate_test.go | 6 ++--- azurerm/resource_arm_mssql_elasticpool.go | 5 ++-- .../resource_arm_mssql_elasticpool_test.go | 24 +++++++++---------- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/azurerm/helpers/azure/validate.go b/azurerm/helpers/azure/validate.go index 85ea875a11d1..2d225f7273d8 100644 --- a/azurerm/helpers/azure/validate.go +++ b/azurerm/helpers/azure/validate.go @@ -35,7 +35,7 @@ func ValidateResourceIDOrEmpty(i interface{}, k string) (_ []string, errors []er } //true for a resource ID or an empty string -func ValidateServiceName(i interface{}, k string) (_ []string, errors []error) { +func ValidateMsSqlServiceName(i interface{}, k string) (_ []string, errors []error) { v, ok := i.(string) if !ok { errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) diff --git a/azurerm/helpers/azure/validate_test.go b/azurerm/helpers/azure/validate_test.go index ed14ed873078..9f9ba62be475 100644 --- a/azurerm/helpers/azure/validate_test.go +++ b/azurerm/helpers/azure/validate_test.go @@ -91,7 +91,7 @@ func TestAzureResourceIDOrEmpty(t *testing.T) { } } -func TestAzureValidateServiceName(t *testing.T) { +func TestAzureValidateMsSqlServiceName(t *testing.T) { cases := []struct { ServiceName string Errors int @@ -140,10 +140,10 @@ func TestAzureValidateServiceName(t *testing.T) { for _, tc := range cases { t.Run(tc.ServiceName, func(t *testing.T) { - _, errors := ValidateServiceName(tc.ServiceName, "name") + _, errors := ValidateMsSqlServiceName(tc.ServiceName, "name") if len(errors) < tc.Errors { - t.Fatalf("Expected TestAzureValidateServiceName to have %d not %d errors for %q", tc.Errors, len(errors), tc.ServiceName) + t.Fatalf("Expected TestAzureValidateMsSqlServiceName to have %d not %d errors for %q", tc.Errors, len(errors), tc.ServiceName) } }) } diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index 025941ca764e..a5292cbfb376 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -28,7 +29,7 @@ func resourceArmMsSqlElasticPool() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateServiceName, + ValidateFunc: azure.ValidateMsSqlServiceName, }, "location": locationSchema(), @@ -39,7 +40,7 @@ func resourceArmMsSqlElasticPool() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateServiceName, + ValidateFunc: azure.ValidateMsSqlServiceName, }, "sku": { diff --git a/azurerm/resource_arm_mssql_elasticpool_test.go b/azurerm/resource_arm_mssql_elasticpool_test.go index e61fca478918..934fd8d15243 100644 --- a/azurerm/resource_arm_mssql_elasticpool_test.go +++ b/azurerm/resource_arm_mssql_elasticpool_test.go @@ -271,16 +271,16 @@ func testAccAzureRMMsSqlElasticPool_resize_vCore(rInt int, location string) stri func testAccAzureRMMsSqlElasticPool_vCore_Template(rInt int, location string, skuName string, skuTier string, skuCapacity int, skuFamily string, databaseSettingsMin float64, databaseSettingsMax float64) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%[1]d" + name = "acctestRG-%[1]d" location = "%s" } resource "azurerm_sql_server" "test" { - name = "acctest%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "4dm1n157r470r" + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" administrator_login_password = "4-v3ry-53cr37-p455w0rd" } @@ -308,16 +308,16 @@ resource "azurerm_mssql_elasticpool" "test" { func testAccAzureRMMsSqlElasticPool_DTU_Template(rInt int, location string, skuName string, skuTier string, skuCapacity int, databaseSettingsMin int, databaseSettingsMax int) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%[1]d" + name = "acctestRG-%[1]d" location = "%s" } resource "azurerm_sql_server" "test" { - name = "acctest%[1]d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - version = "12.0" - administrator_login = "4dm1n157r470r" + name = "acctest%[1]d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + version = "12.0" + administrator_login = "4dm1n157r470r" administrator_login_password = "4-v3ry-53cr37-p455w0rd" } From efdf2236e7ae0f5d065da42dc110e4f44effc75a Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Nov 2018 15:47:25 -0800 Subject: [PATCH 31/38] Last of the PR comments --- azurerm/resource_arm_mssql_elasticpool.go | 27 +++++++++++------------ 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index a5292cbfb376..e1d19debdb59 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -65,8 +65,9 @@ func resourceArmMsSqlElasticPool() *schema.Resource { }, "capacity": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntAtLeast(0), }, "tier": { @@ -89,7 +90,7 @@ func resourceArmMsSqlElasticPool() *schema.Resource { "Gen4", "Gen5", }, true), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, }, }, @@ -249,7 +250,7 @@ func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) tags := d.Get("tags").(map[string]interface{}) elasticPool := sql.ElasticPool{ - Sku: sku, + Sku: sku, ElasticPoolProperties: properties, Location: &location, Tags: expandTags(tags), @@ -352,16 +353,12 @@ func expandAzureRmMsSqlElasticPoolProperties(d *schema.ResourceData) *sql.Elasti minCapacity := perDatabaseSetting["min_capacity"].(float64) maxCapacity := perDatabaseSetting["max_capacity"].(float64) - elasticPoolPerDatabaseSettings := &sql.ElasticPoolPerDatabaseSettings{ - MinCapacity: utils.Float(minCapacity), - MaxCapacity: utils.Float(maxCapacity), - } - - props := &sql.ElasticPoolProperties{ - PerDatabaseSettings: elasticPoolPerDatabaseSettings, + return &sql.ElasticPoolProperties{ + PerDatabaseSettings: &sql.ElasticPoolPerDatabaseSettings{ + MinCapacity: utils.Float(minCapacity), + MaxCapacity: utils.Float(maxCapacity), + }, } - - return props } func expandAzureRmMsSqlElasticPoolSku(d *schema.ResourceData) *sql.Sku { @@ -388,7 +385,9 @@ func flattenAzureRmMsSqlElasticPoolSku(resp *sql.Sku) []interface{} { values["name"] = *name } - values["tier"] = *resp.Tier + if tier := resp.Tier; tier != nil { + values["tier"] = *tier + } if family := resp.Family; family != nil { values["family"] = *family From a60c7d2a51f638085fe1d59071863aefe7a1fcd9 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Nov 2018 20:18:49 -0800 Subject: [PATCH 32/38] Final updates --- azurerm/helpers/azure/validate.go | 21 +++++ azurerm/helpers/azure/validate_test.go | 81 +++++++++++++++++++ azurerm/resource_arm_mssql_elasticpool.go | 13 +-- .../docs/r/mssql_elasticpool.html.markdown | 8 ++ website/docs/r/sql_elasticpool.html.markdown | 2 + 5 files changed, 119 insertions(+), 6 deletions(-) diff --git a/azurerm/helpers/azure/validate.go b/azurerm/helpers/azure/validate.go index 2d225f7273d8..a60f4845f18e 100644 --- a/azurerm/helpers/azure/validate.go +++ b/azurerm/helpers/azure/validate.go @@ -3,6 +3,8 @@ package azure import ( "fmt" "regexp" + + "github.com/hashicorp/terraform/helper/schema" ) func ValidateResourceID(i interface{}, k string) (_ []string, errors []error) { @@ -58,3 +60,22 @@ func ValidateMsSqlServiceName(i interface{}, k string) (_ []string, errors []err return nil, errors } + +// FloatAtLeast returns a SchemaValidateFunc which tests if the provided value +// is of type float64 and is at least min (inclusive) +func FloatAtLeast(min float64) schema.SchemaValidateFunc { + return func(i interface{}, k string) (_ []string, errors []error) { + v, ok := i.(float64) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be float64", k)) + return nil, errors + } + + if v < min { + errors = append(errors, fmt.Errorf("expected %s to be at least (%f), got %f", k, min, v)) + return nil, errors + } + + return nil, errors + } +} diff --git a/azurerm/helpers/azure/validate_test.go b/azurerm/helpers/azure/validate_test.go index 9f9ba62be475..f1a6a652d5c1 100644 --- a/azurerm/helpers/azure/validate_test.go +++ b/azurerm/helpers/azure/validate_test.go @@ -148,3 +148,84 @@ func TestAzureValidateMsSqlServiceName(t *testing.T) { }) } } + +func TestAzureFloatAtLeast(t *testing.T) { + cases := []struct { + Name string + MinValue float64 + ActualValue float64 + Errors int + }{ + { + Name: "Min_Full_Stop_Zero_Greater", + MinValue: 0.0, + ActualValue: 1.0, + Errors: 0, + }, + { + Name: "Min_One_Full_Stop_Zero_Lesser", + MinValue: 1.0, + ActualValue: 0.0, + Errors: 1, + }, + { + Name: "Min_Full_Stop_Two_Five_Greater", + MinValue: 0.25, + ActualValue: 0.26, + Errors: 0, + }, + { + Name: "Min_Full_Stop_Two_Five_Equal", + MinValue: 0.25, + ActualValue: 0.25, + Errors: 0, + }, + { + Name: "Min_Full_Stop_Two_Five_Lesser", + MinValue: 0.25, + ActualValue: 0.24, + Errors: 1, + }, + { + Name: "Min_Full_Stop_Long_Zero_Lesser", + MinValue: 0.0000000000000000000000000000000000000001, + ActualValue: 0, + Errors: 1, + }, + { + Name: "Min_Full_Stop_Long_Greater", + MinValue: 0.0000000000000000000000000000000000000001, + ActualValue: -0, + Errors: 1, + }, + { + Name: "Min_Negative_Full_Stop_Two_Five_Greater", + MinValue: -0.25, + ActualValue: 1, + Errors: 0, + }, + { + Name: "Min_Zero_No_Full_Stop_Equal", + MinValue: 0, + ActualValue: -0, + Errors: 0, + }, + { + Name: "Min_Negative_Full_Stop_Two_Five_Lesser", + MinValue: -0.25, + ActualValue: -0.26, + Errors: 1, + }, + } + + for _, tc := range cases { + t.Run(tc.Name, func(t *testing.T) { + validateFunc := FloatAtLeast(tc.MinValue) + _, errors := validateFunc(tc.ActualValue, "floatValue") + + if len(errors) < tc.Errors { + t.Fatalf("Expected FloatAtLeast to have %d not %d errors for %q", tc.Errors, len(errors), tc.Name) + } + }) + } +} diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index e1d19debdb59..fb34213f862b 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -103,13 +103,15 @@ func resourceArmMsSqlElasticPool() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "min_capacity": { - Type: schema.TypeFloat, - Required: true, + Type: schema.TypeFloat, + Required: true, + ValidateFunc: azure.FloatAtLeast(0.0), }, "max_capacity": { - Type: schema.TypeFloat, - Required: true, + Type: schema.TypeFloat, + Required: true, + ValidateFunc: azure.FloatAtLeast(0.0), }, }, }, @@ -262,8 +264,7 @@ func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) return err } - err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { return err } diff --git a/website/docs/r/mssql_elasticpool.html.markdown b/website/docs/r/mssql_elasticpool.html.markdown index 26a8f2830f65..0559157baa36 100644 --- a/website/docs/r/mssql_elasticpool.html.markdown +++ b/website/docs/r/mssql_elasticpool.html.markdown @@ -94,3 +94,11 @@ The following attributes are exported: * `id` - The MsSQL Elastic Pool ID. * `creation_date` - The creation date of the MsSQL Elastic Pool. + +## Import + +SQL Elastic Pool can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_mssql_elasticpool.test /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Sql/servers/myserver/elasticPools/myelasticpoolname +``` diff --git a/website/docs/r/sql_elasticpool.html.markdown b/website/docs/r/sql_elasticpool.html.markdown index f8838a84a121..162776325334 100644 --- a/website/docs/r/sql_elasticpool.html.markdown +++ b/website/docs/r/sql_elasticpool.html.markdown @@ -10,6 +10,8 @@ description: |- Allows you to manage an Azure SQL Elastic Pool. +~> **NOTE:** - This version of the `Elasticpool` resource is being **deprecated** and should no longer be used. Please use the [azurerm_mssql_elasticpool](./mssql_elasticpool.html) version instead. + ## Example Usage ```hcl From ddcd066e4ea9d12500fb7e1f3d62bac9f31c028c Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 13 Nov 2018 20:19:25 -0800 Subject: [PATCH 33/38] Update azurerm/resource_arm_mssql_elasticpool.go Co-Authored-By: jeffreyCline --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index fb34213f862b..7d6dc8a6eeb5 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -309,7 +309,7 @@ func resourceArmMsSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) e d.Set("server_name", serverName) if err := d.Set("sku", flattenAzureRmMsSqlElasticPoolSku(resp.Sku)); err != nil { - return fmt.Errorf("Error flattening `sku`: %+v", err) + return fmt.Errorf("Error setting `sku`: %+v", err) } if err := d.Set("elastic_pool_properties", flattenAzureRmMsSqlElasticPoolProperties(resp.ElasticPoolProperties)); err != nil { From a31537e734c33dc30b1d7316a84bfdc3284291b8 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 13 Nov 2018 20:22:18 -0800 Subject: [PATCH 34/38] Update azurerm/resource_arm_mssql_elasticpool.go Co-Authored-By: jeffreyCline --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index 7d6dc8a6eeb5..99876e5ecc34 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -313,7 +313,7 @@ func resourceArmMsSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) e } if err := d.Set("elastic_pool_properties", flattenAzureRmMsSqlElasticPoolProperties(resp.ElasticPoolProperties)); err != nil { - return fmt.Errorf("Error flattening `elastic_pool_properties`: %+v", err) + return fmt.Errorf("Error setting `elastic_pool_properties`: %+v", err) } if err := d.Set("per_database_settings", flattenAzureRmMsSqlElasticPoolPerDatabaseSettings(resp.ElasticPoolProperties.PerDatabaseSettings)); err != nil { From 40504e65b7d3ff91f7f8224d4bb44dad30d76291 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 13 Nov 2018 20:22:40 -0800 Subject: [PATCH 35/38] Update azurerm/resource_arm_mssql_elasticpool.go Co-Authored-By: jeffreyCline --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index 99876e5ecc34..8c77fa49e367 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -317,7 +317,7 @@ func resourceArmMsSqlElasticPoolRead(d *schema.ResourceData, meta interface{}) e } if err := d.Set("per_database_settings", flattenAzureRmMsSqlElasticPoolPerDatabaseSettings(resp.ElasticPoolProperties.PerDatabaseSettings)); err != nil { - return fmt.Errorf("Error flattening `per_database_settings`: %+v", err) + return fmt.Errorf("Error setting `per_database_settings`: %+v", err) } flattenAndSetTags(d, resp.Tags) From 359c273a16e481bd2eacc524f14c6bd59b04d170 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Nov 2018 22:41:09 -0800 Subject: [PATCH 36/38] Update azurerm/resource_arm_mssql_elasticpool.go --- azurerm/resource_arm_mssql_elasticpool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index 8c77fa49e367..c1ba4b4bf6c7 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -264,7 +264,7 @@ func resourceArmMsSqlElasticPoolCreate(d *schema.ResourceData, meta interface{}) return err } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { return err } From 900b6a2be8497fdc1f1f285a4b8a3cc3739db359 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 14 Nov 2018 13:25:23 -0800 Subject: [PATCH 37/38] moved FloatAtLeast to new file --- azurerm/helpers/azure/validate.go | 21 ------ azurerm/helpers/azure/validate_test.go | 81 ---------------------- azurerm/helpers/validate/float.go | 25 +++++++ azurerm/helpers/validate/float_test.go | 83 +++++++++++++++++++++++ azurerm/resource_arm_mssql_elasticpool.go | 5 +- 5 files changed, 111 insertions(+), 104 deletions(-) create mode 100644 azurerm/helpers/validate/float.go create mode 100644 azurerm/helpers/validate/float_test.go diff --git a/azurerm/helpers/azure/validate.go b/azurerm/helpers/azure/validate.go index a60f4845f18e..2d225f7273d8 100644 --- a/azurerm/helpers/azure/validate.go +++ b/azurerm/helpers/azure/validate.go @@ -3,8 +3,6 @@ package azure import ( "fmt" "regexp" - - "github.com/hashicorp/terraform/helper/schema" ) func ValidateResourceID(i interface{}, k string) (_ []string, errors []error) { @@ -60,22 +58,3 @@ func ValidateMsSqlServiceName(i interface{}, k string) (_ []string, errors []err return nil, errors } - -// FloatAtLeast returns a SchemaValidateFunc which tests if the provided value -// is of type float64 and is at least min (inclusive) -func FloatAtLeast(min float64) schema.SchemaValidateFunc { - return func(i interface{}, k string) (_ []string, errors []error) { - v, ok := i.(float64) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be float64", k)) - return nil, errors - } - - if v < min { - errors = append(errors, fmt.Errorf("expected %s to be at least (%f), got %f", k, min, v)) - return nil, errors - } - - return nil, errors - } -} diff --git a/azurerm/helpers/azure/validate_test.go b/azurerm/helpers/azure/validate_test.go index f1a6a652d5c1..9f9ba62be475 100644 --- a/azurerm/helpers/azure/validate_test.go +++ b/azurerm/helpers/azure/validate_test.go @@ -148,84 +148,3 @@ func TestAzureValidateMsSqlServiceName(t *testing.T) { }) } } - -func TestAzureFloatAtLeast(t *testing.T) { - cases := []struct { - Name string - MinValue float64 - ActualValue float64 - Errors int - }{ - { - Name: "Min_Full_Stop_Zero_Greater", - MinValue: 0.0, - ActualValue: 1.0, - Errors: 0, - }, - { - Name: "Min_One_Full_Stop_Zero_Lesser", - MinValue: 1.0, - ActualValue: 0.0, - Errors: 1, - }, - { - Name: "Min_Full_Stop_Two_Five_Greater", - MinValue: 0.25, - ActualValue: 0.26, - Errors: 0, - }, - { - Name: "Min_Full_Stop_Two_Five_Equal", - MinValue: 0.25, - ActualValue: 0.25, - Errors: 0, - }, - { - Name: "Min_Full_Stop_Two_Five_Lesser", - MinValue: 0.25, - ActualValue: 0.24, - Errors: 1, - }, - { - Name: "Min_Full_Stop_Long_Zero_Lesser", - MinValue: 0.0000000000000000000000000000000000000001, - ActualValue: 0, - Errors: 1, - }, - { - Name: "Min_Full_Stop_Long_Greater", - MinValue: 0.0000000000000000000000000000000000000001, - ActualValue: -0, - Errors: 1, - }, - { - Name: "Min_Negative_Full_Stop_Two_Five_Greater", - MinValue: -0.25, - ActualValue: 1, - Errors: 0, - }, - { - Name: "Min_Zero_No_Full_Stop_Equal", - MinValue: 0, - ActualValue: -0, - Errors: 0, - }, - { - Name: "Min_Negative_Full_Stop_Two_Five_Lesser", - MinValue: -0.25, - ActualValue: -0.26, - Errors: 1, - }, - } - - for _, tc := range cases { - t.Run(tc.Name, func(t *testing.T) { - validateFunc := FloatAtLeast(tc.MinValue) - _, errors := validateFunc(tc.ActualValue, "floatValue") - - if len(errors) < tc.Errors { - t.Fatalf("Expected FloatAtLeast to have %d not %d errors for %q", tc.Errors, len(errors), tc.Name) - } - }) - } -} diff --git a/azurerm/helpers/validate/float.go b/azurerm/helpers/validate/float.go new file mode 100644 index 000000000000..78e980efdabc --- /dev/null +++ b/azurerm/helpers/validate/float.go @@ -0,0 +1,25 @@ +package validate + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" +) + +// FloatAtLeast returns a SchemaValidateFunc which tests if the provided value +// is of type float64 and is at least min (inclusive) +func FloatAtLeast(min float64) schema.SchemaValidateFunc { + return func(i interface{}, k string) (_ []string, errors []error) { + v, ok := i.(float64) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be float64", k)) + return nil, errors + } + + if v < min { + errors = append(errors, fmt.Errorf("expected %s to be at least (%f), got %f", k, min, v)) + return nil, errors + } + + return nil, errors + } +} diff --git a/azurerm/helpers/validate/float_test.go b/azurerm/helpers/validate/float_test.go new file mode 100644 index 000000000000..02d21d80b7e0 --- /dev/null +++ b/azurerm/helpers/validate/float_test.go @@ -0,0 +1,83 @@ +package validate + +import "testing" + +func TestAzureFloatAtLeast(t *testing.T) { + cases := []struct { + Name string + MinValue float64 + ActualValue float64 + Errors int + }{ + { + Name: "Min_Full_Stop_Zero_Greater", + MinValue: 0.0, + ActualValue: 1.0, + Errors: 0, + }, + { + Name: "Min_One_Full_Stop_Zero_Lesser", + MinValue: 1.0, + ActualValue: 0.0, + Errors: 1, + }, + { + Name: "Min_Full_Stop_Two_Five_Greater", + MinValue: 0.25, + ActualValue: 0.26, + Errors: 0, + }, + { + Name: "Min_Full_Stop_Two_Five_Equal", + MinValue: 0.25, + ActualValue: 0.25, + Errors: 0, + }, + { + Name: "Min_Full_Stop_Two_Five_Lesser", + MinValue: 0.25, + ActualValue: 0.24, + Errors: 1, + }, + { + Name: "Min_Full_Stop_Long_Zero_Lesser", + MinValue: 0.0000000000000000000000000000000000000001, + ActualValue: 0, + Errors: 1, + }, + { + Name: "Min_Full_Stop_Long_Greater", + MinValue: 0.0000000000000000000000000000000000000001, + ActualValue: -0, + Errors: 1, + }, + { + Name: "Min_Negative_Full_Stop_Two_Five_Greater", + MinValue: -0.25, + ActualValue: 1, + Errors: 0, + }, + { + Name: "Min_Zero_No_Full_Stop_Equal", + MinValue: 0, + ActualValue: -0, + Errors: 0, + }, + { + Name: "Min_Negative_Full_Stop_Two_Five_Lesser", + MinValue: -0.25, + ActualValue: -0.26, + Errors: 1, + }, + } + + for _, tc := range cases { + t.Run(tc.Name, func(t *testing.T) { + _, errors := FloatAtLeast(tc.MinValue)(tc.ActualValue, "floatValue") + + if len(errors) < tc.Errors { + t.Fatalf("Expected FloatAtLeast to have %d not %d errors for %q", tc.Errors, len(errors), tc.Name) + } + }) + } +} diff --git a/azurerm/resource_arm_mssql_elasticpool.go b/azurerm/resource_arm_mssql_elasticpool.go index c1ba4b4bf6c7..b502629b17e6 100644 --- a/azurerm/resource_arm_mssql_elasticpool.go +++ b/azurerm/resource_arm_mssql_elasticpool.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -105,13 +106,13 @@ func resourceArmMsSqlElasticPool() *schema.Resource { "min_capacity": { Type: schema.TypeFloat, Required: true, - ValidateFunc: azure.FloatAtLeast(0.0), + ValidateFunc: validate.FloatAtLeast(0.0), }, "max_capacity": { Type: schema.TypeFloat, Required: true, - ValidateFunc: azure.FloatAtLeast(0.0), + ValidateFunc: validate.FloatAtLeast(0.0), }, }, }, From c2a2792f7c6eabb7683b7ad0120de1a6e6a4e009 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 14 Nov 2018 14:18:27 -0800 Subject: [PATCH 38/38] Fix lint error --- azurerm/helpers/validate/float.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/helpers/validate/float.go b/azurerm/helpers/validate/float.go index 78e980efdabc..12d8335d0395 100644 --- a/azurerm/helpers/validate/float.go +++ b/azurerm/helpers/validate/float.go @@ -2,6 +2,7 @@ package validate import ( "fmt" + "github.com/hashicorp/terraform/helper/schema" )