github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/google/resource_bigquery_dataset.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"regexp"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/helper/validation"
    11  	"google.golang.org/api/bigquery/v2"
    12  	"google.golang.org/api/googleapi"
    13  )
    14  
    15  func resourceBigQueryDataset() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceBigQueryDatasetCreate,
    18  		Read:   resourceBigQueryDatasetRead,
    19  		Update: resourceBigQueryDatasetUpdate,
    20  		Delete: resourceBigQueryDatasetDelete,
    21  		Importer: &schema.ResourceImporter{
    22  			State: schema.ImportStatePassthrough,
    23  		},
    24  		Schema: map[string]*schema.Schema{
    25  			// DatasetId: [Required] A unique ID for this dataset, without the
    26  			// project name. The ID must contain only letters (a-z, A-Z), numbers
    27  			// (0-9), or underscores (_). The maximum length is 1,024 characters.
    28  			"dataset_id": {
    29  				Type:     schema.TypeString,
    30  				Required: true,
    31  				ForceNew: true,
    32  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    33  					value := v.(string)
    34  					if !regexp.MustCompile(`^[0-9A-Za-z_]+$`).MatchString(value) {
    35  						errors = append(errors, fmt.Errorf(
    36  							"%q must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_)", k))
    37  					}
    38  
    39  					if len(value) > 1024 {
    40  						errors = append(errors, fmt.Errorf(
    41  							"%q cannot be greater than 1,024 characters", k))
    42  					}
    43  
    44  					return
    45  				},
    46  			},
    47  
    48  			// ProjectId: [Optional] The ID of the project containing this dataset.
    49  			"project": {
    50  				Type:     schema.TypeString,
    51  				Optional: true,
    52  				ForceNew: true,
    53  			},
    54  
    55  			// FriendlyName: [Optional] A descriptive name for the dataset.
    56  			"friendly_name": {
    57  				Type:     schema.TypeString,
    58  				Optional: true,
    59  			},
    60  
    61  			// Description: [Optional] A user-friendly description of the dataset.
    62  			"description": {
    63  				Type:     schema.TypeString,
    64  				Optional: true,
    65  			},
    66  
    67  			// Location: [Experimental] The geographic location where the dataset
    68  			// should reside. Possible values include EU and US. The default value
    69  			// is US.
    70  			"location": {
    71  				Type:         schema.TypeString,
    72  				Optional:     true,
    73  				ForceNew:     true,
    74  				Default:      "US",
    75  				ValidateFunc: validation.StringInSlice([]string{"US", "EU"}, false),
    76  			},
    77  
    78  			// DefaultTableExpirationMs: [Optional] The default lifetime of all
    79  			// tables in the dataset, in milliseconds. The minimum value is 3600000
    80  			// milliseconds (one hour). Once this property is set, all newly-created
    81  			// tables in the dataset will have an expirationTime property set to the
    82  			// creation time plus the value in this property, and changing the value
    83  			// will only affect new tables, not existing ones. When the
    84  			// expirationTime for a given table is reached, that table will be
    85  			// deleted automatically. If a table's expirationTime is modified or
    86  			// removed before the table expires, or if you provide an explicit
    87  			// expirationTime when creating a table, that value takes precedence
    88  			// over the default expiration time indicated by this property.
    89  			"default_table_expiration_ms": {
    90  				Type:     schema.TypeInt,
    91  				Optional: true,
    92  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    93  					value := v.(int)
    94  					if value < 3600000 {
    95  						errors = append(errors, fmt.Errorf("%q cannot be shorter than 3600000 milliseconds (one hour)", k))
    96  					}
    97  
    98  					return
    99  				},
   100  			},
   101  
   102  			// Labels: [Experimental] The labels associated with this dataset. You
   103  			// can use these to organize and group your datasets. You can set this
   104  			// property when inserting or updating a dataset.
   105  			"labels": &schema.Schema{
   106  				Type:     schema.TypeMap,
   107  				Optional: true,
   108  				Elem:     schema.TypeString,
   109  			},
   110  
   111  			// SelfLink: [Output-only] A URL that can be used to access the resource
   112  			// again. You can use this URL in Get or Update requests to the
   113  			// resource.
   114  			"self_link": {
   115  				Type:     schema.TypeString,
   116  				Computed: true,
   117  			},
   118  
   119  			// Etag: [Output-only] A hash of the resource.
   120  			"etag": {
   121  				Type:     schema.TypeString,
   122  				Computed: true,
   123  			},
   124  
   125  			// CreationTime: [Output-only] The time when this dataset was created,
   126  			// in milliseconds since the epoch.
   127  			"creation_time": {
   128  				Type:     schema.TypeInt,
   129  				Computed: true,
   130  			},
   131  
   132  			// LastModifiedTime: [Output-only] The date when this dataset or any of
   133  			// its tables was last modified, in milliseconds since the epoch.
   134  			"last_modified_time": {
   135  				Type:     schema.TypeInt,
   136  				Computed: true,
   137  			},
   138  		},
   139  	}
   140  }
   141  
   142  func resourceDataset(d *schema.ResourceData, meta interface{}) (*bigquery.Dataset, error) {
   143  	config := meta.(*Config)
   144  
   145  	project, err := getProject(d, config)
   146  	if err != nil {
   147  		return nil, err
   148  	}
   149  
   150  	dataset := &bigquery.Dataset{
   151  		DatasetReference: &bigquery.DatasetReference{
   152  			DatasetId: d.Get("dataset_id").(string),
   153  			ProjectId: project,
   154  		},
   155  	}
   156  
   157  	if v, ok := d.GetOk("friendly_name"); ok {
   158  		dataset.FriendlyName = v.(string)
   159  	}
   160  
   161  	if v, ok := d.GetOk("description"); ok {
   162  		dataset.Description = v.(string)
   163  	}
   164  
   165  	if v, ok := d.GetOk("location"); ok {
   166  		dataset.Location = v.(string)
   167  	}
   168  
   169  	if v, ok := d.GetOk("default_table_expiration_ms"); ok {
   170  		dataset.DefaultTableExpirationMs = int64(v.(int))
   171  	}
   172  
   173  	if v, ok := d.GetOk("labels"); ok {
   174  		labels := map[string]string{}
   175  
   176  		for k, v := range v.(map[string]interface{}) {
   177  			labels[k] = v.(string)
   178  		}
   179  
   180  		dataset.Labels = labels
   181  	}
   182  
   183  	return dataset, nil
   184  }
   185  
   186  func resourceBigQueryDatasetCreate(d *schema.ResourceData, meta interface{}) error {
   187  	config := meta.(*Config)
   188  
   189  	project, err := getProject(d, config)
   190  	if err != nil {
   191  		return err
   192  	}
   193  
   194  	dataset, err := resourceDataset(d, meta)
   195  	if err != nil {
   196  		return err
   197  	}
   198  
   199  	log.Printf("[INFO] Creating BigQuery dataset: %s", dataset.DatasetReference.DatasetId)
   200  
   201  	res, err := config.clientBigQuery.Datasets.Insert(project, dataset).Do()
   202  	if err != nil {
   203  		return err
   204  	}
   205  
   206  	log.Printf("[INFO] BigQuery dataset %s has been created", res.Id)
   207  
   208  	d.SetId(res.Id)
   209  
   210  	return resourceBigQueryDatasetRead(d, meta)
   211  }
   212  
   213  func resourceBigQueryDatasetParseID(id string) (string, string) {
   214  	// projectID, datasetID
   215  	parts := strings.Split(id, ":")
   216  	return parts[0], parts[1]
   217  }
   218  
   219  func resourceBigQueryDatasetRead(d *schema.ResourceData, meta interface{}) error {
   220  	config := meta.(*Config)
   221  
   222  	log.Printf("[INFO] Reading BigQuery dataset: %s", d.Id())
   223  
   224  	projectID, datasetID := resourceBigQueryDatasetParseID(d.Id())
   225  
   226  	res, err := config.clientBigQuery.Datasets.Get(projectID, datasetID).Do()
   227  	if err != nil {
   228  		if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
   229  			log.Printf("[WARN] Removing BigQuery dataset %q because it's gone", datasetID)
   230  			// The resource doesn't exist anymore
   231  			d.SetId("")
   232  
   233  			return nil
   234  		}
   235  
   236  		return err
   237  	}
   238  
   239  	d.Set("etag", res.Etag)
   240  	d.Set("labels", res.Labels)
   241  	d.Set("location", res.Location)
   242  	d.Set("self_link", res.SelfLink)
   243  	d.Set("description", res.Description)
   244  	d.Set("friendly_name", res.FriendlyName)
   245  	d.Set("creation_time", res.CreationTime)
   246  	d.Set("last_modified_time", res.LastModifiedTime)
   247  	d.Set("dataset_id", res.DatasetReference.DatasetId)
   248  	d.Set("default_table_expiration_ms", res.DefaultTableExpirationMs)
   249  
   250  	return nil
   251  }
   252  
   253  func resourceBigQueryDatasetUpdate(d *schema.ResourceData, meta interface{}) error {
   254  	config := meta.(*Config)
   255  
   256  	dataset, err := resourceDataset(d, meta)
   257  	if err != nil {
   258  		return err
   259  	}
   260  
   261  	log.Printf("[INFO] Updating BigQuery dataset: %s", d.Id())
   262  
   263  	projectID, datasetID := resourceBigQueryDatasetParseID(d.Id())
   264  
   265  	if _, err = config.clientBigQuery.Datasets.Update(projectID, datasetID, dataset).Do(); err != nil {
   266  		return err
   267  	}
   268  
   269  	return resourceBigQueryDatasetRead(d, meta)
   270  }
   271  
   272  func resourceBigQueryDatasetDelete(d *schema.ResourceData, meta interface{}) error {
   273  	config := meta.(*Config)
   274  
   275  	log.Printf("[INFO] Deleting BigQuery dataset: %s", d.Id())
   276  
   277  	projectID, datasetID := resourceBigQueryDatasetParseID(d.Id())
   278  
   279  	if err := config.clientBigQuery.Datasets.Delete(projectID, datasetID).Do(); err != nil {
   280  		return err
   281  	}
   282  
   283  	d.SetId("")
   284  	return nil
   285  }