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