github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/influxdb/resource_database.go (about) 1 package influxdb 2 3 import ( 4 "fmt" 5 6 "github.com/hashicorp/terraform/helper/schema" 7 "github.com/influxdata/influxdb/client" 8 ) 9 10 func resourceDatabase() *schema.Resource { 11 return &schema.Resource{ 12 Create: createDatabase, 13 Read: readDatabase, 14 Delete: deleteDatabase, 15 16 Schema: map[string]*schema.Schema{ 17 "name": &schema.Schema{ 18 Type: schema.TypeString, 19 Required: true, 20 ForceNew: true, 21 }, 22 }, 23 } 24 } 25 26 func createDatabase(d *schema.ResourceData, meta interface{}) error { 27 conn := meta.(*client.Client) 28 29 name := d.Get("name").(string) 30 queryStr := fmt.Sprintf("CREATE DATABASE %s", quoteIdentifier(name)) 31 query := client.Query{ 32 Command: queryStr, 33 } 34 35 resp, err := conn.Query(query) 36 if err != nil { 37 return err 38 } 39 if resp.Err != nil { 40 return resp.Err 41 } 42 43 d.SetId(name) 44 45 return nil 46 } 47 48 func readDatabase(d *schema.ResourceData, meta interface{}) error { 49 conn := meta.(*client.Client) 50 name := d.Id() 51 52 // InfluxDB doesn't have a command to check the existence of a single 53 // database, so we instead must read the list of all databases and see 54 // if ours is present in it. 55 query := client.Query{ 56 Command: "SHOW DATABASES", 57 } 58 59 resp, err := conn.Query(query) 60 if err != nil { 61 return err 62 } 63 if resp.Err != nil { 64 return resp.Err 65 } 66 67 for _, result := range resp.Results[0].Series[0].Values { 68 if result[0] == name { 69 return nil 70 } 71 } 72 73 // If we fell out here then we didn't find our database in the list. 74 d.SetId("") 75 76 return nil 77 } 78 79 func deleteDatabase(d *schema.ResourceData, meta interface{}) error { 80 conn := meta.(*client.Client) 81 name := d.Id() 82 83 queryStr := fmt.Sprintf("DROP DATABASE %s", quoteIdentifier(name)) 84 query := client.Query{ 85 Command: queryStr, 86 } 87 88 resp, err := conn.Query(query) 89 if err != nil { 90 return err 91 } 92 if resp.Err != nil { 93 return resp.Err 94 } 95 96 d.SetId("") 97 98 return nil 99 }